<?php
// view_job.php
// Handles LLG, Misc-without-appliance-data, Training, and NDT jobs (i.e.
// every category EXCEPT Appliance/Misc-with-appliance-data, which uses
// view_appliance_job.php instead — see openInspectionModal() in index.php).
//
// This file REPLACES the old view_job.php + view_llg_job.php, which were
// near-duplicates of each other (a maintenance risk: any fix had to be
// applied twice). Delete view_llg_job.php from your project — nothing
// references it anymore.
//
// Loaded as a FRAGMENT into index.php's shared modal. POST returns JSON.

require_once 'includes/auth.php';
require_role(['admin', 'inspector'], true);

require_once 'db.php';
require_once 'includes/activity_log.php';
require_once 'includes/checklist_helper.php';

$id = $_GET['id'] ?? ($_POST['id'] ?? 0);
$isAjax = $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_job']);

// ---------------------------------------------------------------------------
// AJAX update handler — returns JSON, never redirects.
// ---------------------------------------------------------------------------
if ($isAjax) {
    header('Content-Type: application/json');
    require_csrf();

    // SECURITY FIX (Issue 2): fetch Item_Name from DB here — never trust
    // POST for non-editable fields. Also include Is_Locked so the locked-
    // certificate gate below works without a second query.
    $categoryStmt = $pdo->prepare("SELECT Category, Is_Locked, Item_Name, ClientID FROM tbl_jobs WHERE ID = ?");
    $categoryStmt->execute([$id]);
    $jobRow = $categoryStmt->fetch(PDO::FETCH_ASSOC);

    // CRITICAL FIX: this check previously existed only on the display side
    // (deciding whether to show the read-only banner or the edit form) —
    // it was completely absent here on the save side, meaning a locked/
    // approved certificate could still be silently edited via a direct
    // POST request, bypassing the entire Approve & Lock feature. The real
    // gate has to be server-side, not just a hidden form.
    if (!$jobRow) {
        echo json_encode(['status' => 'error', 'message' => 'Job not found.']);
        exit;
    }
    if ((int) $jobRow['Is_Locked'] === 1) {
        echo json_encode(['status' => 'error', 'message' => 'This certificate is approved and locked. An Admin must unlock it before it can be edited.']);
        exit;
    }

    $jobCategory = $jobRow['Category'];
    $isTrainingJob = strcasecmp((string) $jobCategory, 'Training') === 0;

    // SECURITY FIX (Issue 2, extended by docx item 7): Item_Name/Course Name
    // is now readonly in the UI for EVERY job type, including Training, and
    // must never be overridden from POST — it's set once at creation via the
    // Master Bank/Course selector. Always read the current DB value instead
    // of trusting $_POST['item_name'], regardless of job type.
    $itemName = trim($jobRow['Item_Name'] ?? '');

    $serialNo   = trim($_POST['serial_no'] ?? '');
    $approval   = $_POST['approval'] ?? 'Pass';
    // FIX (docx item 2): Work Order Ref is set once at job creation and must
    // stay immutable afterward — no longer read from POST or written here at
    // all (removed from the UPDATE below too), so a direct/tampered POST
    // can't change it either.
    $issueDate = $_POST['issue_date'] ?? null;
    $expiryDate = $_POST['expiry_date'] ?? null;

    // NEW (docx items 1 & 3): Site Name / Sub Location / Type of Inspection,
    // shared job-level fields across every category (LLG, Training, Misc).
    $siteIdRaw   = $_POST['site_id'] ?? '';
    $siteId      = ($siteIdRaw === '' || $siteIdRaw === '0') ? null : (int) $siteIdRaw;
    $subLocation = trim($_POST['sub_location'] ?? '');

    $allowedInspectionTypes = [
        'In-Service Thorough Examination',
        'Pre-Use Inspection',
        'Initial Examination',
        'Periodic Examination',
        'Exceptional Examination',
        'Visual Inspection',
        'Proof Load Testing',
        'Maintenance Inspection',
    ];
    $inspectionType = trim($_POST['inspection_type'] ?? '');
    if (!in_array($inspectionType, $allowedInspectionTypes, true)) {
        $inspectionType = 'In-Service Thorough Examination';
    }

    // Anti-IDOR: only accept a Site_ID that actually belongs to this job's
    // own client, so a tampered request can't attach another client's site.
    if ($siteId !== null) {
        $siteCheck = $pdo->prepare('SELECT SiteID FROM tbl_client_sites WHERE SiteID = ? AND ClientID = ? AND Deleted_At IS NULL LIMIT 1');
        $siteCheck->execute([$siteId, $jobRow['ClientID'] ?? 0]);
        if (!$siteCheck->fetchColumn()) {
            $siteId = null;
        }
    }

    try {
        $pdo->beginTransaction();

        $sqlJob = "UPDATE tbl_jobs SET Item_Name = ?, Serial_No = ?, Approval = ?, Issue_Date = ?, Expiry_Date = ?, Site_ID = ?, Sub_Location = ?, Inspection_Type = ? WHERE ID = ?";
        $stmtJob = $pdo->prepare($sqlJob);
        $stmtJob->execute([$itemName, $serialNo, $approval, $issueDate ?: null, $expiryDate ?: null, $siteId, $subLocation, $inspectionType, $id]);

        if ($isTrainingJob) {
            // -----------------------------------------------------------
            // TRAINING — separate, much simpler save path: no technical
            // inspection fields, no checklist, no certificate notes.
            // -----------------------------------------------------------
            $traineeName = trim($_POST['trainee_name'] ?? '');
            $traineeId   = trim($_POST['trainee_id'] ?? '');
            $nationality = trim($_POST['nationality'] ?? '');
            $courseContent = $_POST['course_content'] ?? '';
            $trainingParameters = $_POST['training_parameters'] ?? '';

            if ($traineeName === '') {
                $pdo->rollBack();
                echo json_encode(['status' => 'error', 'message' => 'Trainee Name is required.']);
                exit;
            }

            $sqlTraining = "UPDATE tbl_training_records SET
                             Trainee_Name = ?, Trainee_ID = ?, Nationality = ?, Course_Name = ?, Course_Content = ?, Training_Parameters = ?, Approval_Status = ?
                             WHERE JobID = ?";
            $stmtTraining = $pdo->prepare($sqlTraining);
            $stmtTraining->execute([$traineeName, $traineeId, $nationality, $itemName, $courseContent, $trainingParameters, $approval, $id]);

            $pdo->commit();
            logActivity($pdo, (int) $id, 'edited', 'Training record updated');
            echo json_encode(['status' => 'success', 'message' => 'Training record saved successfully.', 'job_id' => (int) $id]);
            exit;
        }

        // -----------------------------------------------------------
        // LLG (and any other non-Appliance, non-Training job) — the
        // original full technical inspection + checklist save path.
        // -----------------------------------------------------------
        // NOTE: reference_standards and inspection_procedure are readonly
        // in the UI (Issue 2 fix) and are NOT accepted from POST.
        // They are read-only DB values displayed for reference only.
        $details   = $_POST['item_details'] ?? '';
        $markedSwl = $_POST['marked_swl'] ?? '';
        $proofLoad = $_POST['proof_load'] ?? '';

        // New certificate note fields (shared with Appliance's own copies).
        $equipmentUsed = trim($_POST['equipment_used'] ?? '');
        $colourCode    = trim($_POST['colour_code'] ?? '');
        $deviations    = $_POST['deviations'] ?? '';
        $subcontracted = $_POST['subcontracted'] ?? '';
        $comments      = $_POST['comments'] ?? '';
        $prevInspection = $_POST['previous_inspection_details'] ?? '';

        $chkResults = $_POST['checklist_results'] ?? [];
        $chkRemarks = $_POST['checklist_remarks'] ?? [];
        $loadStandardLlg = isset($_POST['load_standard_llg']) && $_POST['load_standard_llg'] == '1';

        // NOTE: intentionally no Job_No or Category field is accepted/updated
        // here — Job Number is immutable after creation (enforced by simply
        // never reading it from $_POST), and Category changes are out of scope
        // for this quick-edit form to avoid silently breaking which report
        // template a job renders under.

        $chkStmt = $pdo->prepare("SELECT COUNT(*) FROM tbl_llg_inspections WHERE JobID = ?");
        $chkStmt->execute([$id]);
        $exists = $chkStmt->fetchColumn();

        if ($exists) {
            $sqlLlg = "UPDATE tbl_llg_inspections SET
                        Item_Description = ?, Marked_SWL = ?, Proof_Load = ?,
                        Equipment_Used = ?, Colour_Code = ?, Deviations = ?,
                        Subcontracted = ?, Comments = ?, Previous_Inspection_Details = ?
                       WHERE JobID = ?";
            $stmtLlg = $pdo->prepare($sqlLlg);
            $stmtLlg->execute([
                $details, $markedSwl, $proofLoad,
                $equipmentUsed, $colourCode, $deviations,
                $subcontracted, $comments, $prevInspection,
                $id,
            ]);
        } else {
            // BUG FIX (Issue 3): Original INSERT had 12 columns but only
            // 11 VALUES — Proof_Load was incorrectly set to literal 'Pass'
            // and Previous_Inspection_Details was missing from the VALUES
            // list, causing a MySQL "Column count doesn't match" fatal error
            // whenever a new tbl_llg_inspections record needed to be created.
            $sqlIns = "INSERT INTO tbl_llg_inspections
                        (JobID, Item_Description, Marked_SWL, Proof_Load, Visual_Inspection, Approval_Status,
                         Equipment_Used, Colour_Code, Deviations, Subcontracted, Comments, Previous_Inspection_Details)
                       VALUES (?, ?, ?, ?, 'Pass', 'Pass', ?, ?, ?, ?, ?, ?)";
            $stmtIns = $pdo->prepare($sqlIns);
            $stmtIns->execute([
                $id, $details, $markedSwl, $proofLoad,
                $equipmentUsed, $colourCode, $deviations, $subcontracted, $comments, $prevInspection,
            ]);
        }

        if ($loadStandardLlg) {
            $clearStmt = $pdo->prepare("DELETE FROM tbl_job_checklists WHERE JobID = ?");
            $clearStmt->execute([$id]);

            // BUG FIX (Issue 3): previously used a raw query that only fetched
            // generic LLG items (item_name IS NULL OR ''), while approve_job.php
            // calls getApplicableChecklistIds() which ALSO includes item-specific
            // rows. After "Load Standard" save, the approve check found
            // actualCount < expectedCount and blocked approval.
            // Now we use the SAME helper so both sides always agree on which
            // items count as "applicable".
            $applicableIds = getApplicableChecklistIds($pdo, $jobCategory, $itemName);
            if (!empty($applicableIds)) {
                $insStd = $pdo->prepare("INSERT INTO tbl_job_checklists (JobID, MasterCheckID, Result, Remarks, Updated_At) VALUES (?, ?, 'Pass', '', NOW())");
                foreach ($applicableIds as $mcId) {
                    $insStd->execute([$id, $mcId]);
                }
            }
        } else {
            foreach ($chkResults as $masterCheckID => $resultVal) {
                $remarkVal = $chkRemarks[$masterCheckID] ?? '';

                $checkExist = $pdo->prepare("SELECT ChecklistID FROM tbl_job_checklists WHERE JobID = ? AND MasterCheckID = ?");
                $checkExist->execute([$id, $masterCheckID]);
                $existingId = $checkExist->fetchColumn();

                if ($existingId) {
                    $updChk = $pdo->prepare("UPDATE tbl_job_checklists SET Result = ?, Remarks = ?, Updated_At = NOW() WHERE ChecklistID = ?");
                    $updChk->execute([$resultVal, $remarkVal, $existingId]);
                } else {
                    $insChk = $pdo->prepare("INSERT INTO tbl_job_checklists (JobID, MasterCheckID, Result, Remarks, Updated_At) VALUES (?, ?, ?, ?, NOW())");
                    $insChk->execute([$id, $masterCheckID, $resultVal, $remarkVal]);
                }
            }
        }

        $pdo->commit();

        logActivity($pdo, (int) $id, 'edited', 'LLG inspection and checklist updated');

        echo json_encode(['status' => 'success', 'message' => 'Changes saved successfully.', 'job_id' => (int) $id]);
        exit;

    } catch (\PDOException $e) {
        $pdo->rollBack();
        error_log('view_job.php update error: ' . $e->getMessage());
        echo json_encode(['status' => 'error', 'message' => 'A database error occurred while saving.']);
        exit;
    }
}

// ---------------------------------------------------------------------------
// GET — fetch job data for display
// ---------------------------------------------------------------------------
$job = null;
try {
    $stmtCat = $pdo->prepare("SELECT Category FROM tbl_jobs WHERE ID = ? OR Job_No = ?");
    $stmtCat->execute([$id, $id]);
    $categoryProbe = $stmtCat->fetchColumn();
    $isTraining = strcasecmp((string) $categoryProbe, 'Training') === 0;

    if ($isTraining) {
        $sqlFetch = "SELECT j.*, t.*
                     FROM tbl_jobs j
                     LEFT JOIN tbl_training_records t ON j.ID = t.JobID
                     WHERE j.ID = ? OR j.Job_No = ?";
    } else {
        $sqlFetch = "SELECT j.*, l.*
                     FROM tbl_jobs j
                     LEFT JOIN tbl_llg_inspections l ON j.ID = l.JobID
                     WHERE j.ID = ? OR j.Job_No = ?";
    }
    $stmt = $pdo->prepare($sqlFetch);
    $stmt->execute([$id, $id]);
    $job = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (\PDOException $e) {}

if (!$job) {
    $stmt = $pdo->prepare("SELECT * FROM tbl_jobs WHERE ID = ? OR Job_No = ?");
    $stmt->execute([$id, $id]);
    $job = $stmt->fetch(PDO::FETCH_ASSOC);
}

if (!$job) {
    echo '<div class="alert alert-danger m-3">Error: Job ID #' . htmlspecialchars($id) . ' does not exist in the database.</div>';
    exit;
}

$isTraining = $isTraining ?? false;

$jobId        = $job['ID'] ?? $job['id'] ?? $id;
$jobPkId      = $jobId; // used by includes/photo_manager.php
$jobNo        = $job['Job_No'] ?? $job['job_no'] ?? ('JOB-' . $jobId);
$clientVal    = $job['Client_Name'] ?? $job['client_name'] ?? $job['Client'] ?? '';
$category     = strtoupper($job['Category'] ?? $job['category'] ?? 'LLG');
$itemNameVal  = $job['Item_Name'] ?? $job['item_name'] ?? '';
$serialVal    = $job['Serial_No'] ?? $job['serial_no'] ?? $job['s_n'] ?? '';
$approvalVal  = $job['Approval'] ?? $job['approval'] ?? 'Pass';
$engineerVal  = $job['Engineer'] ?? $job['engineer'] ?? 'Abdulla Qasim';

$standardsVal = $job['Reference_Standards'] ?? $job['Reference_Standard'] ?? 'US FED SPEC.RR-C-271D / BSEN 13889';
$procedureVal = $job['Inspection_Procedure'] ?? $job['procedure'] ?? 'DOC/SH/005, ISSUE : 02/REV01, 22.02.2017';
$detailsVal   = $job['Item_Description'] ?? $job['Required_Details'] ?? $job['item_details'] ?? '';
$markedSwlVal = $job['Marked_SWL'] ?? '';
$proofLoadVal = $job['Proof_Load'] ?? '';

$equipmentUsedVal = $job['Equipment_Used'] ?? '';
$colourCodeVal    = $job['Colour_Code'] ?? '';
$deviationsVal    = $job['Deviations'] ?? '';
$subcontractedVal = $job['Subcontracted'] ?? '';
$commentsVal      = $job['Comments'] ?? '';
$prevInspectionVal = $job['Previous_Inspection_Details'] ?? '';

// NEW (docx items 1 & 3): Site Name / Sub Location / Type of Inspection,
// shared job-level fields across every category (LLG, Training, Misc).
// $job here already comes from "SELECT j.*, ..." on tbl_jobs, so Site_ID /
// Sub_Location / Inspection_Type / ClientID are already present.
$jobClientId = $job['ClientID'] ?? null;

$clientSites = [];
if ($jobClientId) {
    try {
        $stmtSites = $pdo->prepare("SELECT SiteID, Site_Name FROM tbl_client_sites WHERE ClientID = ? AND Deleted_At IS NULL ORDER BY Site_Name ASC");
        $stmtSites->execute([$jobClientId]);
        $clientSites = $stmtSites->fetchAll(PDO::FETCH_ASSOC);
    } catch (\PDOException $e) { $clientSites = []; }
}

$inspectionTypeOptions = [
    'In-Service Thorough Examination',
    'Pre-Use Inspection',
    'Initial Examination',
    'Periodic Examination',
    'Exceptional Examination',
    'Visual Inspection',
    'Proof Load Testing',
    'Maintenance Inspection',
];
$currentInspectionType = trim($job['Inspection_Type'] ?? '') ?: 'In-Service Thorough Examination';
$currentSiteId = $job['Site_ID'] ?? '';
$currentSubLocation = $job['Sub_Location'] ?? '';

// Training-only fields
$traineeNameVal   = $job['Trainee_Name'] ?? '';
$traineeIdVal     = $job['Trainee_ID'] ?? '';
$nationalityVal   = $job['Nationality'] ?? '';
$courseContentVal = $job['Course_Content'] ?? '';
$trainingParametersVal = $job['Training_Parameters'] ?? '';

// Master Checklists & Saved Answers (not applicable to Training)
$checklist_items = [];
$loadStandardLlgGet = isset($_GET['load_standard_llg']) && $_GET['load_standard_llg'] == '1';

if (!$isTraining) {
try {
    if ($loadStandardLlgGet) {
        $chkQuery = "SELECT m.MasterCheckID, m.CheckItem, m.DisplayOrder, c.Result, c.Remarks
                     FROM tbl_master_checklists m
                     LEFT JOIN tbl_job_checklists c ON c.MasterCheckID = m.MasterCheckID AND c.JobID = ?
                     WHERE m.Category = 'LLG' AND (m.item_name IS NULL OR m.item_name = '') AND m.IsActive = 1
                     ORDER BY m.DisplayOrder ASC";
        $chkStmt = $pdo->prepare($chkQuery);
        $chkStmt->execute([$jobId]);
        $checklist_items = $chkStmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        // Uses the same shared helper approve_job.php validates against —
        // eliminates any chance of this list ever silently drifting from
        // what the approval check counts (the exact bug that broke Misc
        // approval before).
        $checklist_items = getChecklistItemsForDisplay($pdo, $jobId, $job['Category'] ?? 'LLG', $itemNameVal);
    }
} catch (\Exception $e) {}
}

$me = current_user();
$isLocked = (int) ($job['Is_Locked'] ?? 0) === 1;
?>
<div class="modal-header bg-dark text-white">
    <h5 class="modal-title font-monospace"><i class="fa-solid fa-file-contract me-2"></i> <?= htmlspecialchars($jobNo); ?></h5>
    <div class="ms-auto d-flex align-items-center gap-2">
        <?php // BUG FIX: was target="_blank" (new tab) — now opens the shared
              // certificate modal defined in index.php, matching Reports. ?>
        <?php if ($isLocked): ?>
            <button type="button" class="btn btn-sm btn-primary fw-bold" onclick="if (window.openCertificateModal) openCertificateModal(<?= (int) $jobId; ?>, 'html');"><i class="fa-solid fa-print me-1"></i> Certificate</button>
        <?php elseif ($me && in_array($me['role'], ['admin', 'inspector'], true)): ?>
            <?php // FIX (same class of bug the admin reported for the
                  // Appliance form: "I write something in Certificate Title
                  // and it's not printed"): this button used to open the
                  // certificate straight from the DATABASE, ignoring any
                  // unsaved edit sitting in the form below. Now it saves
                  // first and only opens the preview once that save
                  // actually succeeds. ?>
            <button type="button" class="btn btn-sm btn-outline-light fw-bold" onclick="previewJobAfterSave(<?= (int) $jobId; ?>);"><i class="fa-solid fa-eye me-1"></i> Preview</button>
        <?php endif; ?>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
    </div>
</div>

<?php if ($isLocked): ?>
    <!-- A certificate reaching this locked state here is an edge case (the
         register only ever lists unlocked jobs) — but defend against direct
         navigation regardless. No edit form at all while locked; only an
         Admin can unlock it to make it editable again. -->
    <div class="modal-body">
        <div class="alert alert-success d-flex justify-content-between align-items-center">
            <div>
                <i class="fa-solid fa-lock me-2"></i>
                <strong>This certificate is approved and locked.</strong> It cannot be edited unless unlocked.
            </div>
            <?php if ($me && $me['role'] === 'admin'): ?>
                <button type="button" class="btn btn-sm btn-outline-warning" id="unlockFromModalBtn" data-job-id="<?= $jobId; ?>">
                    <i class="fa-solid fa-lock-open me-1"></i> Unlock
                </button>
            <?php endif; ?>
        </div>
    </div>
    <script>
    (function () {
        var btn = document.getElementById('unlockFromModalBtn');
        if (!btn) return;
        btn.addEventListener('click', function () {
            if (!confirm('Unlock this certificate for editing?')) return;
            var formData = new FormData();
            formData.append('job_id', btn.getAttribute('data-job-id'));
                formData.append('csrf_token', document.querySelector('meta[name="csrf-token"]').content);
            fetch('unlock_job.php', { method: 'POST', body: formData })
                .then(function (r) { return r.json(); })
                .then(function (data) {
                    if (data.status === 'success') {
                        bootstrap.Modal.getOrCreateInstance(document.getElementById('inspectionModal')).hide();
                        showToast(data.message, false);
                        refreshTable();
                    } else {
                        showToast(data.message, true);
                    }
                });
        });
    })();
    </script>
<?php else: ?>
<div class="modal-body">
    <form class="ajax-job-form" method="POST" action="view_job.php">
        <input type="hidden" name="update_job" value="1">
        <input type="hidden" name="id" value="<?= $jobId; ?>">
        <?php csrf_field(); ?>

        <!-- Header Info -->
        <div class="row g-3 mb-4">
            <div class="col-md-3">
                <label class="form-label small text-muted fw-bold">Client Name</label>
                <input type="text" class="form-control bg-light" value="<?= htmlspecialchars($clientVal); ?>" readonly tabindex="-1">
            </div>
            <div class="col-md-3">
                <label class="form-label small text-muted fw-bold">Job No</label>
                <input type="text" class="form-control bg-light font-monospace fw-bold text-primary" value="<?= htmlspecialchars($jobNo); ?>" readonly tabindex="-1">
            </div>
            <div class="col-md-3">
                <label class="form-label small text-muted fw-bold">Work Order Ref <i class="fa-solid fa-lock text-muted" title="Set once at job creation — cannot be changed here"></i></label>
                <!-- FIX (docx item 2): Work Order Ref is set once at job
                     creation (add_job.php) and must not drift afterward — it
                     links the certificate to the client's accounting record.
                     Readonly here is UI-only; the real enforcement is that
                     the AJAX save handler below no longer accepts this field
                     from POST at all. -->
                <input type="text" class="form-control bg-light" value="<?= htmlspecialchars($job['Work_Order_Ref'] ?? ''); ?>" readonly tabindex="-1">
            </div>
            <div class="col-md-3">
                <label class="form-label small text-muted fw-bold">Overall Status</label>
                <select name="approval" class="form-select fw-bold <?= strtolower($approvalVal) === 'pass' ? 'text-success' : 'text-danger'; ?>">
                    <option value="Pass" <?= strtolower($approvalVal) === 'pass' ? 'selected' : ''; ?>>PASS</option>
                    <option value="Fail" <?= strtolower($approvalVal) === 'fail' ? 'selected' : ''; ?>>FAIL</option>
                    <option value="Pending" <?= strtolower($approvalVal) === 'pending' ? 'selected' : ''; ?>>PENDING</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label small text-muted fw-bold">Issue Date <i class="fa-solid fa-triangle-exclamation text-warning" title="Changing this affects the official record"></i></label>
                <input type="date" name="issue_date" class="form-control js-date-warning" data-original="<?= htmlspecialchars($job['Issue_Date'] ?? ''); ?>" value="<?= htmlspecialchars($job['Issue_Date'] ?? ''); ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label small text-muted fw-bold">Expiry Date <i class="fa-solid fa-triangle-exclamation text-warning" title="Changing this affects the official record"></i></label>
                <input type="date" name="expiry_date" class="form-control js-date-warning" data-original="<?= htmlspecialchars($job['Expiry_Date'] ?? ''); ?>" value="<?= htmlspecialchars($job['Expiry_Date'] ?? ''); ?>">
            </div>
        </div>

        <!-- NEW (docx items 1 & 3): Site Name / Sub Location / Type of
             Inspection -- shared job-level fields, apply to every category
             (LLG, Training, Misc), so they sit here in the common Header
             Info area rather than inside either category-specific branch
             below. -->
        <div class="row g-3 mb-4">
            <div class="col-md-4">
                <label class="form-label small text-muted fw-bold">Site Name</label>
                <select class="form-select" name="site_id">
                    <option value="">-- Select Site --</option>
                    <?php foreach ($clientSites as $siteOpt): ?>
                    <option value="<?= htmlspecialchars($siteOpt['SiteID']); ?>" <?= ((string) $currentSiteId === (string) $siteOpt['SiteID']) ? 'selected' : ''; ?>><?= htmlspecialchars($siteOpt['Site_Name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label small text-muted fw-bold">Sub Location</label>
                <input type="text" class="form-control" name="sub_location" value="<?= htmlspecialchars($currentSubLocation); ?>">
            </div>
            <div class="col-md-4">
                <label class="form-label small text-muted fw-bold">Type Of Inspection</label>
                <select class="form-select" name="inspection_type">
                    <?php foreach ($inspectionTypeOptions as $typeOpt): ?>
                    <option value="<?= htmlspecialchars($typeOpt); ?>" <?= ($currentInspectionType === $typeOpt) ? 'selected' : ''; ?>><?= htmlspecialchars($typeOpt); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <hr>

        <?php if ($isTraining): ?>
            <!-- ==================== TRAINING FORM ==================== -->
            <h6 class="fw-bold text-primary mb-3"><i class="fa-solid fa-user-graduate me-1"></i> Trainee & Course Details</h6>
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label small fw-bold">Trainee Name</label>
                    <input type="text" name="trainee_name" class="form-control" value="<?= htmlspecialchars($traineeNameVal); ?>" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label small fw-bold">Trainee ID (Identification No.)</label>
                    <input type="text" name="trainee_id" class="form-control font-monospace" value="<?= htmlspecialchars($traineeIdVal); ?>">
                </div>
                <div class="col-md-6">
                    <label class="form-label small fw-bold">Nationality</label>
                    <input type="text" name="nationality" class="form-control" value="<?= htmlspecialchars($nationalityVal); ?>">
                </div>
                <div class="col-md-12">
                    <label class="form-label small fw-bold">Course Name <i class="fa-solid fa-lock text-muted" title="Set once at job creation — cannot be changed here"></i></label>
                    <!-- FIX (docx item 7): Course Name is set once at job
                         creation via the Master Bank/Course selector and must
                         not be editable afterward. Readonly here is UI-only;
                         the AJAX save handler below no longer accepts this
                         field from POST for Training jobs either. -->
                    <input type="text" class="form-control bg-light" value="<?= htmlspecialchars($itemNameVal); ?>" readonly tabindex="-1">
                    <div class="form-text">This doubles as "Item Name" on the job record.</div>
                </div>
                <div class="col-12">
                    <label class="form-label small fw-bold text-primary">
                        <i class="fa-solid fa-clipboard-list me-1"></i> Course Content (shown on certificate)
                    </label>
                    <textarea name="course_content" class="form-control font-monospace" rows="6"><?= htmlspecialchars($courseContentVal); ?></textarea>
                </div>
                <div class="col-12">
                    <label class="form-label small fw-bold text-primary">
                        <i class="fa-solid fa-sliders me-1"></i> Training Parameters (shown on certificate)
                    </label>
                    <textarea name="training_parameters" class="form-control" rows="3"><?= htmlspecialchars($trainingParametersVal); ?></textarea>
                </div>
            </div>
            <input type="hidden" name="serial_no" value="">

            <div class="d-flex justify-content-between align-items-center mt-4 pt-3 border-top">
                <span class="small text-muted">Trainer/Assessor: <strong><?= htmlspecialchars($engineerVal); ?></strong></span>
                <div>
                    <?php if ($me && $me['role'] === 'admin'): ?>
                        <button type="button" class="btn btn-outline-success me-2 js-approve-btn" data-job-id="<?= $jobId; ?>"><i class="fa-solid fa-check-double me-1"></i> Approve & Lock</button>
                    <?php endif; ?>
                    <button type="button" class="btn btn-secondary me-2" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary fw-bold px-4"><i class="fa-solid fa-save me-1"></i> Save Training Record</button>
                </div>
            </div>

        <?php else: ?>
            <!-- ==================== LLG / TECHNICAL FORM ==================== -->
        <h6 class="fw-bold text-primary mb-3"><i class="fa-solid fa-gears me-1"></i> Technical Inspection Specifications</h6>

        <div class="row g-3">
            <div class="col-md-6">
                <!-- ISSUE 2 FIX: Item Name is non-editable — it comes from
                     Master Items and must not be changed on the inspection form.
                     The readonly attribute prevents UI editing; the server-side
                     handler ignores $_POST['item_name'] for non-Training jobs. -->
                <label class="form-label small fw-bold">
                    Item Name / Description
                    <i class="fa-solid fa-lock text-secondary ms-1" title="This field is set from Master Items and cannot be changed here."></i>
                </label>
                <input type="text" name="item_name" class="form-control bg-light" value="<?= htmlspecialchars($itemNameVal); ?>" readonly tabindex="-1">
            </div>
            <div class="col-md-6">
                <label class="form-label small fw-bold">Serial / ID Number</label>
                <input type="text" name="serial_no" class="form-control font-monospace" value="<?= htmlspecialchars($serialVal); ?>">
            </div>

            <div class="col-md-6">
                <label class="form-label small fw-bold text-success"><i class="fa-solid fa-weight-scale me-1"></i> Safe Working Load (SWL)</label>
                <input type="text" name="marked_swl" class="form-control fw-bold" value="<?= htmlspecialchars($markedSwlVal); ?>" placeholder="e.g., 5.0 TONS">
            </div>
            <div class="col-md-6">
                <label class="form-label small fw-bold text-primary"><i class="fa-solid fa-dumbbell me-1"></i> Proof Load</label>
                <input type="text" name="proof_load" class="form-control fw-bold" value="<?= htmlspecialchars($proofLoadVal); ?>" placeholder="e.g., 7.5 TONS">
            </div>

            <div class="col-md-6">
                <!-- ISSUE 2 FIX: Reference Standard is defined at the company
                     level and must not be altered per-job. Display only. -->
                <label class="form-label small fw-bold">
                    Reference Standard
                    <i class="fa-solid fa-lock text-secondary ms-1" title="Standard is fixed and cannot be changed per-job."></i>
                </label>
                <input type="text" class="form-control bg-light" value="<?= htmlspecialchars($standardsVal); ?>" readonly tabindex="-1">
            </div>
            <div class="col-md-6">
                <!-- ISSUE 2 FIX: Inspection Procedure is fixed per company
                     document control and must not be altered per-job. Display only. -->
                <label class="form-label small fw-bold">
                    Inspection Procedure
                    <i class="fa-solid fa-lock text-secondary ms-1" title="Procedure is fixed and cannot be changed per-job."></i>
                </label>
                <input type="text" class="form-control bg-light" value="<?= htmlspecialchars($procedureVal); ?>" readonly tabindex="-1">
            </div>

            <div class="col-12 mt-3">
                <label class="form-label small fw-bold text-primary">
                    <i class="fa-solid fa-clipboard-list text-primary me-1"></i> Required Certificate Details (Editable)
                </label>
                <textarea name="item_details" class="form-control font-monospace" rows="5"><?= htmlspecialchars($detailsVal); ?></textarea>
            </div>
        </div>

        <hr class="my-4">

        <!-- Certificate Note Fields — now real, DB-backed columns -->
        <h6 class="fw-bold text-primary mb-3"><i class="fa-solid fa-note-sticky me-1"></i> Certificate Notes</h6>
        <div class="row g-3">
            <div class="col-md-6">
                <label class="form-label small fw-bold">Equipment Used</label>
                <input type="text" name="equipment_used" class="form-control" value="<?= htmlspecialchars($equipmentUsedVal); ?>">
            </div>
            <div class="col-md-6">
                <label class="form-label small fw-bold">Colour Code</label>
                <input type="text" name="colour_code" class="form-control" value="<?= htmlspecialchars($colourCodeVal); ?>">
            </div>
            <div class="col-md-6">
                <label class="form-label small fw-bold">Details of Deviations/Omissions from original scope of work</label>
                <textarea name="deviations" class="form-control" rows="2"><?= htmlspecialchars($deviationsVal); ?></textarea>
            </div>
            <div class="col-md-6">
                <label class="form-label small fw-bold">Details of Sub Contracted Work</label>
                <textarea name="subcontracted" class="form-control" rows="2"><?= htmlspecialchars($subcontractedVal); ?></textarea>
            </div>
            <div class="col-md-6">
                <label class="form-label small fw-bold">Previous Inspection/Test Details</label>
                <textarea name="previous_inspection_details" class="form-control" rows="2"><?= htmlspecialchars($prevInspectionVal); ?></textarea>
            </div>
            <div class="col-md-6">
                <label class="form-label small fw-bold">Comments</label>
                <textarea name="comments" class="form-control" rows="2"><?= htmlspecialchars($commentsVal); ?></textarea>
            </div>
        </div>

        <hr class="my-4">

        <!-- Quick Load LLG Standard Checklist Option -->
        <div class="alert alert-info py-2 d-flex justify-content-between align-items-center mb-3">
            <div>
                <i class="fa-solid fa-circle-info me-1"></i> Want to load standard default items instead of item-specific ones?
            </div>
            <div class="form-check m-0">
                <input class="form-check-input" type="checkbox" name="load_standard_llg" value="1" id="loadLlgCheck" <?= $loadStandardLlgGet ? 'checked' : ''; ?>>
                <label class="form-check-label fw-bold text-dark small" for="loadLlgCheck">
                    Load Standard LLG Checklist Only
                </label>
            </div>
        </div>

        <div class="d-flex justify-content-between align-items-center mb-3">
            <h6 class="fw-bold text-dark m-0"><i class="fa-solid fa-list-check text-success me-1"></i> Inspection Checklist Annex</h6>
            <div>
                <button type="button" class="btn btn-sm btn-outline-success me-2 js-pass-all-btn"><i class="fa-solid fa-check-double me-1"></i> Pass All</button>
                <span class="badge bg-secondary"><?= count($checklist_items); ?> Criteria Loaded</span>
            </div>
        </div>

        <?php if (!empty($checklist_items)): ?>
            <div class="table-responsive">
                <table class="table table-bordered align-middle">
                    <thead class="table-light">
                        <tr>
                            <th style="width: 5%;" class="text-center">#</th>
                            <th style="width: 55%;">Checklist Criteria</th>
                            <th style="width: 20%;" class="text-center">Result</th>
                            <th style="width: 20%;">Remarks</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $n = 1; foreach ($checklist_items as $chk):
                            $mId = $chk['MasterCheckID'];
                            $currResult = $chk['Result'] ?? 'Pass';
                            $currRemarks = $chk['Remarks'] ?? '';
                        ?>
                            <tr>
                                <td class="text-center fw-bold"><?= $n++; ?></td>
                                <td><?= htmlspecialchars($chk['CheckItem']); ?></td>
                                <td class="text-center">
                                    <select name="checklist_results[<?= $mId; ?>]" class="form-select form-select-sm fw-bold <?= $currResult === 'Pass' ? 'text-success' : 'text-danger'; ?>">
                                        <option value="Pass" <?= $currResult === 'Pass' ? 'selected' : ''; ?>>PASS</option>
                                        <option value="Fail" <?= $currResult === 'Fail' ? 'selected' : ''; ?>>FAIL</option>
                                        <option value="N/A" <?= $currResult === 'N/A' ? 'selected' : ''; ?>>N/A</option>
                                    </select>
                                </td>
                                <td>
                                    <input type="text" name="checklist_remarks[<?= $mId; ?>]" class="form-control form-control-sm" value="<?= htmlspecialchars($currRemarks); ?>" placeholder="Optional notes...">
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="alert alert-warning py-2 small">
                <i class="fa-solid fa-triangle-exclamation me-1"></i> No checklist items found. Ensure standard LLG items or item-specific rows are added in `tbl_master_checklists`.
            </div>
        <?php endif; ?>

        <div class="d-flex justify-content-between align-items-center mt-4 pt-3 border-top">
            <span class="small text-muted">Inspector: <strong><?= htmlspecialchars($engineerVal); ?></strong></span>
            <div>
                <?php if ($me && $me['role'] === 'admin'): ?>
                    <button type="button" class="btn btn-outline-success me-2 js-approve-btn" data-job-id="<?= $jobId; ?>"><i class="fa-solid fa-check-double me-1"></i> Approve & Lock</button>
                <?php endif; ?>
                <button type="button" class="btn btn-secondary me-2" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary fw-bold px-4"><i class="fa-solid fa-save me-1"></i> Save Changes & Checklist</button>
            </div>
        </div>
        <?php endif; ?>
    </form>

    <hr class="my-4">

    <?php
    $currentPageUrl = null; // signals to photo_manager.php: AJAX mode, no page navigation
    $photoManagerTrainingMode = $isTraining;
    include 'includes/photo_manager.php';
    ?>

    <script>
    // BUG FIX ("I write something in Certificate Title and it's not printed
    // in the certificate" — same root cause here even though this file has
    // no Certificate Title field: the header "Preview" button opened the
    // certificate straight from the database, completely bypassing any
    // unsaved edit sitting in this form). Saves the main job form first
    // (same POST this form's own Save button already sends, and the same
    // Issue/Expiry Date safety confirm() it already shows) and only opens
    // the certificate preview once that save actually succeeds — never
    // shows stale data again. Deliberately does NOT reuse index.php's
    // shared `.ajax-job-form` submit handler (which closes this edit modal
    // on success) — Preview should just refresh what's shown on top of the
    // still-open edit form, not close it.
    function previewJobAfterSave(jobId) {
        var form = document.querySelector('form.ajax-job-form');
        if (!form) {
            if (window.openCertificateModal) openCertificateModal(jobId, 'html');
            return;
        }

        var changedDates = [];
        document.querySelectorAll('.js-date-warning').forEach(function (input) {
            if (input.value !== input.getAttribute('data-original')) {
                changedDates.push(input.name === 'issue_date' ? 'Issue Date' : 'Expiry Date');
            }
        });
        if (changedDates.length > 0) {
            var ok = confirm('You changed the ' + changedDates.join(' and ') + ' on this job. This affects the official record. Continue saving?');
            if (!ok) return;
        }

        var formData = new FormData(form);
        fetch(form.getAttribute('action'), { method: 'POST', body: formData })
            .then(function (response) {
                if (response.status === 401) {
                    window.location.href = 'login.php';
                    return Promise.reject(new Error('Session expired.'));
                }
                return response.text().then(function (text) {
                    try { return JSON.parse(text); }
                    catch (e) { throw new Error('Server response error: ' + text.substring(0, 200)); }
                });
            })
            .then(function (data) {
                if (data.status === 'success') {
                    if (window.openCertificateModal) openCertificateModal(jobId, 'html');
                } else if (window.showToast) {
                    showToast(data.message || 'Could not save before preview.', true);
                }
            })
            .catch(function (err) {
                if (window.showToast) showToast(err.message, true);
                console.error(err);
            });
    }

    (function () {
        document.querySelectorAll('.js-pass-all-btn').forEach(function (btn) {
            btn.addEventListener('click', function () {
                document.querySelectorAll('select[name^="checklist_results"]').forEach(function (sel) {
                    sel.value = 'Pass';
                    sel.classList.remove('text-danger');
                    sel.classList.add('text-success');
                });
            });
        });

        // Warn before submitting if Issue Date or Expiry Date was changed
        // from its original value — these affect the official record.
        var mainForm = document.querySelector('form.ajax-job-form');
        if (mainForm) {
            mainForm.addEventListener('submit', function (e) {
                var changedDates = [];
                document.querySelectorAll('.js-date-warning').forEach(function (input) {
                    if (input.value !== input.getAttribute('data-original')) {
                        changedDates.push(input.name === 'issue_date' ? 'Issue Date' : 'Expiry Date');
                    }
                });
                if (changedDates.length > 0) {
                    var ok = confirm('You changed the ' + changedDates.join(' and ') + ' on this job. This affects the official record. Continue saving?');
                    if (!ok) { e.preventDefault(); e.stopImmediatePropagation(); }
                }
            });
        }

        document.querySelectorAll('.js-approve-btn').forEach(function (btn) {
            btn.addEventListener('click', function () {
                if (!confirm('Approve and lock this certificate? It will move to Reports and can no longer be edited unless an Admin unlocks it.')) return;

                var formData = new FormData();
                formData.append('job_id', btn.getAttribute('data-job-id'));
                formData.append('csrf_token', document.querySelector('meta[name="csrf-token"]').content);
                btn.disabled = true;

                fetch('approve_job.php', { method: 'POST', body: formData })
                    .then(function (r) {
                        if (r.status === 401) { window.location.href = 'login.php'; return Promise.reject(new Error('Session expired.')); }
                        return r.json();
                    })
                    .then(function (data) {
                        if (data.status === 'success') {
                            bootstrap.Modal.getOrCreateInstance(document.getElementById('inspectionModal')).hide();
                            showToast(data.message, false);
                            refreshTable();
                        } else {
                            showToast(data.message, true);
                            btn.disabled = false;
                        }
                    })
                    .catch(function (err) {
                        showToast(err.message, true);
                        btn.disabled = false;
                    });
            });
        });
    })();
    </script>
</div>
<?php endif; ?>
