<?php

require_once __DIR__ . '/helpers.php';
api_require_admin();

try {
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $rows = db_all(
            $conn,
            'SELECT id, full_name, username, role, status, created_at
             FROM users
             ORDER BY id DESC'
        );
        json_response(['success' => true, 'data' => $rows]);
    }

    $action = $_POST['action'] ?? '';

    if ($action === 'save') {
        $id = (int) ($_POST['id'] ?? 0);
        $fullName = clean_text($_POST['full_name'] ?? '');
        $username = clean_text($_POST['username'] ?? '');
        $password = (string) ($_POST['password'] ?? '');
        $role = clean_text($_POST['role'] ?? 'Staff');
        $status = clean_text($_POST['status'] ?? 'Active');
        $role = in_array($role, ['Admin', 'Staff'], true) ? $role : 'Staff';
        $status = in_array($status, ['Active', 'Inactive'], true) ? $status : 'Active';

        if ($fullName === '' || $username === '') {
            json_response(['success' => false, 'message' => 'Full name and username are required.'], 422);
        }

        if ($id === 0 && trim($password) === '') {
            json_response(['success' => false, 'message' => 'Password is required for new users.'], 422);
        }

        if ($id === (int) (current_user()['id'] ?? 0) && ($role !== 'Admin' || $status !== 'Active')) {
            json_response(['success' => false, 'message' => 'You cannot remove your own admin access.'], 422);
        }

        $duplicateUser = db_one(
            $conn,
            'SELECT id FROM users WHERE username = ? AND id <> ? LIMIT 1',
            'si',
            [$username, $id]
        );

        if ($duplicateUser) {
            json_response(['success' => false, 'message' => 'Username already exists.'], 422);
        }

        if ($id > 0) {
            if (trim($password) !== '') {
                $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                db_execute(
                    $conn,
                    'UPDATE users
                     SET full_name = ?,
                         username = ?,
                         role = ?,
                         status = ?,
                         password = ?
                     WHERE id = ?',
                    'sssssi',
                    [$fullName, $username, $role, $status, $hashedPassword, $id]
                );
            } else {
                db_execute(
                    $conn,
                    'UPDATE users
                     SET full_name = ?,
                         username = ?,
                         role = ?,
                         status = ?
                     WHERE id = ?',
                    'ssssi',
                    [$fullName, $username, $role, $status, $id]
                );
            }
            log_activity($conn, 'Update User', "User {$username} was updated.");
        } else {
            db_execute(
                $conn,
                'INSERT INTO users (full_name, username, password, role, status)
                 VALUES (?, ?, ?, ?, ?)',
                'sssss',
                [$fullName, $username, password_hash($password, PASSWORD_DEFAULT), $role, $status]
            );
            log_activity($conn, 'Create User', "User {$username} was created.");
        }

        json_response(['success' => true, 'message' => 'User saved.']);
    }

    if ($action === 'delete') {
        $id = (int) ($_POST['id'] ?? 0);

        if ($id <= 0) {
            json_response(['success' => false, 'message' => 'Invalid user.'], 422);
        }

        if ($id === (int) (current_user()['id'] ?? 0)) {
            json_response(['success' => false, 'message' => 'You cannot delete your own account.'], 422);
        }

        db_execute($conn, 'DELETE FROM users WHERE id = ?', 'i', [$id]);
        log_activity($conn, 'Delete User', "User #{$id} was deleted.");

        json_response(['success' => true, 'message' => 'User deleted.']);
    }

    json_response(['success' => false, 'message' => 'Invalid request.'], 400);
} catch (Throwable $e) {
    json_response(['success' => false, 'message' => 'Request failed. Check your data and try again.'], 500);
}
