<?php
// ============================================================
// EquipmentController
// ============================================================
requireRole(['admin', 'front_desk', 'lab_officer']);
$db     = Database::getInstance();
$action = $_GET['action'] ?? 'index';

switch ($action) {
    case 'index':
        $cid  = (int)($_GET['company_id'] ?? 0);
        $q    = sanitize($_GET['q'] ?? '');
        $where = 'WHERE 1=1';
        $params = [];
        if ($cid)  { $where .= ' AND e.company_id = ?'; $params[] = $cid; }
        if ($q)    { $where .= ' AND (e.equipment_name LIKE ? OR e.serial_number LIKE ?)'; $params[] = "%$q%"; $params[] = "%$q%"; }
        $stmt = $db->prepare("
            SELECT e.*, c.company_name FROM equipment e
            JOIN companies c ON e.company_id = c.company_id
            $where ORDER BY e.equipment_name
        ");
        $stmt->execute($params);
        $equipments = $stmt->fetchAll();
        $companies  = $db->query('SELECT company_id, company_name FROM companies ORDER BY company_name')->fetchAll();
        include __DIR__ . '/../views/frontdesk/equipment_index.php';
        break;

    case 'create':
        requireRole(['admin', 'front_desk']);
        $cid = (int)($_GET['company_id'] ?? 0);
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verifyCsrf();
            $cid  = (int)($_POST['company_id'] ?? 0);
            $db->prepare('INSERT INTO equipment (company_id,equipment_name,model,serial_number,manufacturer,range_capacity) VALUES (?,?,?,?,?,?)')
               ->execute([$cid, sanitize($_POST['equipment_name']), sanitize($_POST['model']), sanitize($_POST['serial_number']), sanitize($_POST['manufacturer']), sanitize($_POST['range_capacity'])]);
            $eid = $db->lastInsertId();
            logActivity('create_equipment', 'equipment', "Added equipment for company $cid", $eid);
            setFlash('success', 'Equipment added successfully.');
            header('Location: ' . APP_URL . '/index.php?page=equipment&company_id=' . $cid);
            exit;
        }
        $companies = $db->query('SELECT company_id, company_name FROM companies ORDER BY company_name')->fetchAll();
        $equipment = null;
        include __DIR__ . '/../views/frontdesk/equipment_form.php';
        break;

    case 'edit':
        requireRole(['admin', 'front_desk']);
        $eid  = (int)($_GET['id'] ?? 0);
        $stmt = $db->prepare('SELECT * FROM equipment WHERE equipment_id = ?');
        $stmt->execute([$eid]);
        $equipment = $stmt->fetch();
        if (!$equipment) { setFlash('error', 'Equipment not found.'); header('Location: ' . APP_URL . '/index.php?page=equipment'); exit; }
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verifyCsrf();
            $db->prepare('UPDATE equipment SET equipment_name=?,model=?,serial_number=?,manufacturer=?,range_capacity=? WHERE equipment_id=?')
               ->execute([sanitize($_POST['equipment_name']), sanitize($_POST['model']), sanitize($_POST['serial_number']), sanitize($_POST['manufacturer']), sanitize($_POST['range_capacity']), $eid]);
            logActivity('update_equipment', 'equipment', "Updated equipment ID $eid", $eid);
            setFlash('success', 'Equipment updated.');
            header('Location: ' . APP_URL . '/index.php?page=equipment&company_id=' . $equipment['company_id']);
            exit;
        }
        $companies = $db->query('SELECT company_id, company_name FROM companies ORDER BY company_name')->fetchAll();
        include __DIR__ . '/../views/frontdesk/equipment_form.php';
        break;

    case 'delete':
        requireRole(['admin', 'front_desk']);
        $eid = (int)($_GET['id'] ?? 0);
        $db->prepare('DELETE FROM equipment WHERE equipment_id = ?')->execute([$eid]);
        logActivity('delete_equipment', 'equipment', "Deleted equipment ID $eid", $eid);
        setFlash('success', 'Equipment deleted.');
        header('Location: ' . APP_URL . '/index.php?page=equipment');
        exit;
}
