<?php
// ============================================================
// RequestController
// ============================================================
requireLogin();
$db     = Database::getInstance();
$action = $_GET['action'] ?? 'index';
$uid    = (int)$_SESSION['user_id'];
$role   = $_SESSION['role'];

// Build lab restriction clause
$userLabs  = getUserLabs($uid);
$labIds    = array_column($userLabs, 'lab_id');
$labFilter = '';
$labParams = [];
if ($role === 'lab_officer' && !empty($labIds)) {
    $placeholders = implode(',', array_fill(0, count($labIds), '?'));
    $labFilter = " AND r.lab_id IN ($placeholders)";
    $labParams = $labIds;
} elseif ($role === 'front_desk') {
    $labFilter = " AND r.created_by = ?";
    $labParams = [$uid];
}

switch ($action) {
    case 'index':
        $status = sanitize($_GET['status'] ?? '');
        $q      = sanitize($_GET['q'] ?? '');
        $extra  = '';
        $params = $labParams;

        if ($status) { $extra .= ' AND r.status = ?'; $params[] = $status; }
        if ($q)      { $extra .= ' AND (c.company_name LIKE ? OR r.request_number LIKE ?)'; $params[] = "%$q%"; $params[] = "%$q%"; }

        $stmt = $db->prepare("
            SELECT r.*, c.company_name, e.equipment_name, l.lab_name, u.officer_name AS created_by_name
            FROM requests r
            JOIN companies c   ON r.company_id   = c.company_id
            JOIN equipment e   ON r.equipment_id  = e.equipment_id
            JOIN laboratories l ON r.lab_id        = l.lab_id
            JOIN users u       ON r.created_by     = u.user_id
            WHERE 1=1 $labFilter $extra
            ORDER BY r.date_created DESC
        ");
        $stmt->execute($params);
        $requests = $stmt->fetchAll();
        include __DIR__ . '/../views/shared/requests_index.php';
        break;

    case 'create':
        requireRole(['admin', 'front_desk']);
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verifyCsrf();
            $compId  = (int)($_POST['company_id']   ?? 0);
            $equipId = (int)($_POST['equipment_id'] ?? 0);
            $labId   = (int)($_POST['lab_id']       ?? 0);
            $contId  = ($_POST['contact_id'] ?? '') ?: null;
            $date    = sanitize($_POST['request_date'] ?? date('Y-m-d'));
            $notes   = sanitize($_POST['notes'] ?? '');
            $prio    = in_array($_POST['priority'] ?? '', ['normal','urgent']) ? $_POST['priority'] : 'normal';

            if (!$compId || !$equipId || !$labId) {
                setFlash('error', 'Company, equipment and laboratory are required.');
                header('Location: ' . APP_URL . '/index.php?page=requests&action=create');
                exit;
            }
            $reqNum = generateRequestNumber();
            $db->prepare('INSERT INTO requests (request_number,company_id,equipment_id,lab_id,contact_id,created_by,request_date,notes,priority) VALUES (?,?,?,?,?,?,?,?,?)')
               ->execute([$reqNum, $compId, $equipId, $labId, $contId, $uid, $date, $notes, $prio]);
            $rid = $db->lastInsertId();
            logActivity('create_request', 'requests', "Request $reqNum created", $rid);
            setFlash('success', "Request $reqNum created successfully.");
            header('Location: ' . APP_URL . '/index.php?page=requests&action=view&id=' . $rid);
            exit;
        }
        $companies = $db->query('SELECT company_id, company_name FROM companies ORDER BY company_name')->fetchAll();
        $labs      = $db->query('SELECT lab_id, lab_name FROM laboratories ORDER BY lab_name')->fetchAll();
        include __DIR__ . '/../views/shared/request_form.php';
        break;

    case 'view':
        $rid  = (int)($_GET['id'] ?? 0);
        $stmt = $db->prepare("
            SELECT r.*, c.company_name, c.address AS company_address, c.phone AS company_phone, c.email AS company_email,
                   e.equipment_name, e.model, e.serial_number, e.manufacturer, e.range_capacity,
                   l.lab_name, l.lab_code,
                   u.officer_name AS created_by_name,
                   a.officer_name AS assigned_to_name,
                   cp.contact_name, cp.phone_number AS contact_phone
            FROM requests r
            JOIN companies c    ON r.company_id   = c.company_id
            JOIN equipment e    ON r.equipment_id  = e.equipment_id
            JOIN laboratories l ON r.lab_id        = l.lab_id
            JOIN users u        ON r.created_by    = u.user_id
            LEFT JOIN users a   ON r.assigned_to   = a.user_id
            LEFT JOIN contact_persons cp ON r.contact_id = cp.contact_id
            WHERE r.request_id = ?
        ");
        $stmt->execute([$rid]);
        $request = $stmt->fetch();

        if (!$request) { setFlash('error', 'Request not found.'); header('Location: ' . APP_URL . '/index.php?page=requests'); exit; }

        // Access control for lab officers
        if ($role === 'lab_officer' && !userCanAccessLab($uid, $request['lab_id'])) {
            setFlash('error', 'Access denied.'); header('Location: ' . APP_URL . '/index.php?page=requests'); exit;
        }

        // Fetch associated form and certificate
        $stmt = $db->prepare('SELECT * FROM lab_work_forms WHERE request_id = ?');
        $stmt->execute([$rid]); $workForm = $stmt->fetch();

        $cert = null;
        if ($workForm) {
            $stmt = $db->prepare('SELECT * FROM certificates WHERE request_id = ?');
            $stmt->execute([$rid]); $cert = $stmt->fetch();
        }

        include __DIR__ . '/../views/shared/request_view.php';
        break;

    case 'update_status':
        requireRole(['admin', 'lab_officer']);
        $rid    = (int)($_GET['id'] ?? 0);
        $status = sanitize($_POST['status'] ?? '');
        if (in_array($status, ['pending','in_progress','completed','cancelled'])) {
            $db->prepare('UPDATE requests SET status = ? WHERE request_id = ?')->execute([$status, $rid]);
            logActivity('update_request_status', 'requests', "Status changed to $status for request $rid", $rid);
            setFlash('success', 'Request status updated.');
        }
        header('Location: ' . APP_URL . '/index.php?page=requests&action=view&id=' . $rid);
        exit;
}
