<?php
// ============================================================
// UserController  (Admin only)
// ============================================================
requireRole(['admin']);
$db     = Database::getInstance();
$action = $_GET['action'] ?? 'index';

switch ($action) {

    case 'index':
        $users = $db->query('
            SELECT u.*, GROUP_CONCAT(l.lab_name ORDER BY l.lab_name SEPARATOR ", ") AS labs
            FROM users u
            LEFT JOIN user_lab_assignments a ON u.user_id = a.user_id
            LEFT JOIN laboratories l ON a.lab_id = l.lab_id
            GROUP BY u.user_id
            ORDER BY u.date_created DESC
        ')->fetchAll();
        include __DIR__ . '/../views/admin/users_index.php';
        break;

    case 'create':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verifyCsrf();
            $name     = sanitize($_POST['officer_name'] ?? '');
            $email    = sanitize($_POST['email'] ?? '');
            $phone    = sanitize($_POST['phone_number'] ?? '');
            $role     = sanitize($_POST['role'] ?? 'front_desk');
            $password = $_POST['password'] ?? '';
            $labIds   = $_POST['lab_ids'] ?? [];

            if (!$name || !$email || !$password) {
                setFlash('error', 'Name, email, and password are required.');
                header('Location: ' . APP_URL . '/index.php?page=users&action=create');
                exit;
            }

            $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);

            try {
                $db->prepare('INSERT INTO users (officer_name, email, phone_number, role, password) VALUES (?, ?, ?, ?, ?)')
                   ->execute([$name, $email, $phone, $role, $hash]);
                $userId = $db->lastInsertId();

                // Assign labs
                if (!empty($labIds)) {
                    $insStmt = $db->prepare('INSERT IGNORE INTO user_lab_assignments (user_id, lab_id) VALUES (?, ?)');
                    foreach ($labIds as $lid) {
                        $insStmt->execute([$userId, (int)$lid]);
                    }
                }

                logActivity('create_user', 'users', "Created user: $name ($role)", $userId);
                setFlash('success', "User '$name' created successfully.");
                header('Location: ' . APP_URL . '/index.php?page=users');
            } catch (PDOException $e) {
                setFlash('error', 'Email already exists or database error.');
                header('Location: ' . APP_URL . '/index.php?page=users&action=create');
            }
            exit;
        }
        $labs = $db->query('SELECT * FROM laboratories ORDER BY lab_name')->fetchAll();
        include __DIR__ . '/../views/admin/users_form.php';
        break;

    case 'edit':
        $userId  = (int)($_GET['id'] ?? 0);
        $stmt    = $db->prepare('SELECT * FROM users WHERE user_id = ?');
        $stmt->execute([$userId]);
        $editUser = $stmt->fetch();
        if (!$editUser) { setFlash('error', 'User not found.'); header('Location: ' . APP_URL . '/index.php?page=users'); exit; }

        $stmt = $db->prepare('SELECT lab_id FROM user_lab_assignments WHERE user_id = ?');
        $stmt->execute([$userId]);
        $assignedLabs = array_column($stmt->fetchAll(), 'lab_id');

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verifyCsrf();
            $name   = sanitize($_POST['officer_name'] ?? '');
            $email  = sanitize($_POST['email'] ?? '');
            $phone  = sanitize($_POST['phone_number'] ?? '');
            $role   = sanitize($_POST['role'] ?? 'front_desk');
            $labIds = $_POST['lab_ids'] ?? [];
            $active = isset($_POST['is_active']) ? 1 : 0;

            $params = [$name, $email, $phone, $role, $active];
            $sql    = 'UPDATE users SET officer_name=?, email=?, phone_number=?, role=?, is_active=?';

            if (!empty($_POST['password'])) {
                $sql     .= ', password=?';
                $params[] = password_hash($_POST['password'], PASSWORD_BCRYPT, ['cost' => 12]);
            }
            $sql     .= ' WHERE user_id=?';
            $params[] = $userId;

            $db->prepare($sql)->execute($params);

            // Re-assign labs
            $db->prepare('DELETE FROM user_lab_assignments WHERE user_id = ?')->execute([$userId]);
            if (!empty($labIds)) {
                $ins = $db->prepare('INSERT INTO user_lab_assignments (user_id, lab_id) VALUES (?, ?)');
                foreach ($labIds as $lid) $ins->execute([$userId, (int)$lid]);
            }

            logActivity('update_user', 'users', "Updated user ID $userId", $userId);
            setFlash('success', 'User updated successfully.');
            header('Location: ' . APP_URL . '/index.php?page=users');
            exit;
        }
        $labs = $db->query('SELECT * FROM laboratories ORDER BY lab_name')->fetchAll();
        include __DIR__ . '/../views/admin/users_form.php';
        break;

    case 'delete':
        $userId = (int)($_GET['id'] ?? 0);
        if ($userId === (int)$_SESSION['user_id']) {
            setFlash('error', 'You cannot delete your own account.');
        } else {
            $db->prepare('DELETE FROM users WHERE user_id = ?')->execute([$userId]);
            logActivity('delete_user', 'users', "Deleted user ID $userId", $userId);
            setFlash('success', 'User deleted.');
        }
        header('Location: ' . APP_URL . '/index.php?page=users');
        exit;
}
