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

switch ($action) {
    case 'index':
        $labs = $db->query('SELECT l.*, COUNT(DISTINCT a.user_id) AS officer_count, COUNT(DISTINCT r.request_id) AS request_count FROM laboratories l LEFT JOIN user_lab_assignments a ON l.lab_id = a.lab_id LEFT JOIN requests r ON l.lab_id = r.lab_id GROUP BY l.lab_id ORDER BY l.lab_name')->fetchAll();
        include __DIR__ . '/../views/admin/labs_index.php';
        break;
    case 'create':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verifyCsrf();
            $db->prepare('INSERT INTO laboratories (lab_name, lab_code, department, description) VALUES (?,?,?,?)')
               ->execute([sanitize($_POST['lab_name']), strtoupper(sanitize($_POST['lab_code'])), sanitize($_POST['department']), sanitize($_POST['description'] ?? '')]);
            logActivity('create_lab', 'laboratories', 'Created lab: ' . $_POST['lab_name']);
            setFlash('success', 'Laboratory created.'); header('Location: ' . APP_URL . '/index.php?page=labs'); exit;
        }
        $lab = null;
        include __DIR__ . '/../views/admin/lab_form.php'; break;
    case 'edit':
        $lid  = (int)($_GET['id'] ?? 0);
        $stmt = $db->prepare('SELECT * FROM laboratories WHERE lab_id = ?'); $stmt->execute([$lid]); $lab = $stmt->fetch();
        if (!$lab) { setFlash('error', 'Lab not found.'); header('Location: ' . APP_URL . '/index.php?page=labs'); exit; }
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verifyCsrf();
            $db->prepare('UPDATE laboratories SET lab_name=?,lab_code=?,department=?,description=? WHERE lab_id=?')
               ->execute([sanitize($_POST['lab_name']), strtoupper(sanitize($_POST['lab_code'])), sanitize($_POST['department']), sanitize($_POST['description'] ?? ''), $lid]);
            logActivity('update_lab', 'laboratories', "Updated lab $lid", $lid);
            setFlash('success', 'Laboratory updated.'); header('Location: ' . APP_URL . '/index.php?page=labs'); exit;
        }
        include __DIR__ . '/../views/admin/lab_form.php'; break;
}
