<?php
// ============================================================
// WorkFormController  (Lab Officer + Admin)
// Routes to lab-specific or generic form handler via LabRegistry.
// ============================================================
requireRole(['admin', 'lab_officer']);

require_once __DIR__ . '/../helpers/ILabForm.php';
require_once __DIR__ . '/../helpers/LabRegistry.php';

$db     = Database::getInstance();
$action = $_GET['action'] ?? 'edit';
$uid    = (int)$_SESSION['user_id'];

// ── Load request with all joined data ──────────────────────
$rid  = (int)($_GET['request_id'] ?? 0);
$stmt = $db->prepare('
    SELECT r.*,
           l.lab_id, l.lab_name, l.lab_code,
           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
    FROM requests r
    JOIN laboratories l ON r.lab_id       = l.lab_id
    JOIN companies   c  ON r.company_id   = c.company_id
    JOIN equipment   e  ON r.equipment_id = e.equipment_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;
}

// ── Lab access check ────────────────────────────────────────
if (!userCanAccessLab($uid, $request['lab_id'])) {
    setFlash('error', 'You are not assigned to this laboratory.');
    header('Location: ' . APP_URL . '/index.php?page=requests');
    exit;
}

// ── Resolve lab-specific or generic handler ─────────────────
$labCode    = strtoupper($request['lab_code']);
$formHandler = LabRegistry::getFormHandler($labCode);

// ── Load existing saved form data ──────────────────────────
$form = $formHandler->load($rid);

// ── POST: save the form ─────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();

    $errors = $formHandler->validate($_POST);
    if (!empty($errors)) {
        setFlash('error', implode(' ', $errors));
        header('Location: ' . APP_URL . '/index.php?page=workform&action=edit&request_id=' . $rid);
        exit;
    }

    $formId = $formHandler->save($rid, $uid, $request['lab_id'], $_POST);

    // Advance request status
    $db->prepare("UPDATE requests SET status='in_progress', assigned_to=? WHERE request_id=? AND status='pending'")
       ->execute([$uid, $rid]);

    logActivity('save_workform', 'workform', "Saved {$labCode} work form for request $rid", $formId);
    setFlash('success', 'Work form saved successfully.');

    if (($_POST['form_status'] ?? '') === 'submitted') {
        header('Location: ' . APP_URL . '/index.php?page=certificates&action=generate&request_id=' . $rid);
    } else {
        header('Location: ' . APP_URL . '/index.php?page=workform&action=edit&request_id=' . $rid);
    }
    exit;
}

// ── GET: render the appropriate form view ───────────────────
$formView = LabRegistry::getFormView($labCode);
include __DIR__ . '/../views/' . $formView;
