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

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

$jobId = $_GET['id'] ?? null;
if (!$jobId) {
    echo '<div class="alert alert-danger m-3">Error: No Job ID provided.</div>';
    exit;
}

// 1. Fetch job details from master/jobs table
$job = null;
try {
    $stmtJob = $pdo->prepare("SELECT * FROM qry_jobs_master WHERE ID = ? OR Job_No = ?");
    $stmtJob->execute([$jobId, $jobId]);
    $job = $stmtJob->fetch(PDO::FETCH_ASSOC);
} catch (\PDOException $e) {}

if (!$job) {
    try {
        $stmtJob = $pdo->prepare("SELECT * FROM tbl_jobs WHERE id = ? OR JobID = ?");
        $stmtJob->execute([$jobId, $jobId]);
        $job = $stmtJob->fetch(PDO::FETCH_ASSOC);
    } catch (\PDOException $e) {}
}

if (!$job) {
    echo '<div class="alert alert-danger m-3">Error: Job record not found.</div>';
    exit;
}

// Extract the correct numeric primary key ID and the display Job Number
$jobPkId         = $job['ID'] ?? $job['id'] ?? $jobId;
$jobDisplayNo    = $job['Job_No'] ?? $job['job_no'] ?? $job['JobID'] ?? $jobPkId;
$defaultItemName = $job['Item_Name'] ?? $job['Equipment_Type'] ?? '';

// NEW (docx items 1-3 + latent bug fix): qry_jobs_master (the primary fast
// lookup above) is a narrow VIEW that does not expose ClientID, Site_ID,
// Sub_Location, Inspection_Type, or Work_Order_Ref -- so whenever that path
// wins, those keys are silently absent from $job. Backfill them here
// directly from tbl_jobs (the source of truth) regardless of which path
// populated $job above.
try {
    $stmtJobExtra = $pdo->prepare("SELECT ClientID, Site_ID, Sub_Location, Inspection_Type, Work_Order_Ref FROM tbl_jobs WHERE ID = ? LIMIT 1");
    $stmtJobExtra->execute([$jobPkId]);
    $jobExtra = $stmtJobExtra->fetch(PDO::FETCH_ASSOC);
    if ($jobExtra) {
        $job = array_merge($job, $jobExtra);
    }
} catch (\PDOException $e) { /* keep existing $job values */ }

$jobClientId = $job['ClientID'] ?? null;

// Fetch this client's active site list for the Site Name dropdown.
$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'] ?? '';

// 2. Check if appliance inspection record already exists for this Job ID (using numeric primary key ID)
$applianceData = null;
try {
    $stmtApp = $pdo->prepare("SELECT * FROM tbl_appliance_inspections WHERE JobID = ?");
    $stmtApp->execute([$jobPkId]);
    $applianceData = $stmtApp->fetch(PDO::FETCH_ASSOC);

    // If not found, automatically insert a blank row using the numeric foreign key ID
    if (!$applianceData) {
        $stmtInsert = $pdo->prepare("INSERT INTO tbl_appliance_inspections (JobID, ItemName, item_name_description) VALUES (?, ?, ?)");
        $stmtInsert->execute([$jobPkId, $defaultItemName, $defaultItemName]);

        // Fetch it back
        $stmtApp->execute([$jobPkId]);
        $applianceData = $stmtApp->fetch(PDO::FETCH_ASSOC);
    }
} catch (\PDOException $e) {
    echo '<div class="alert alert-danger m-3">Database error: ' . htmlspecialchars($e->getMessage()) . '</div>';
    exit;
}

$applianceId     = $applianceData['Appliance_ID'] ?? null;
// BUG FIX ("where did the field I set disappear to?"): was a plain `??`,
// which does not fall back when tbl_appliance_inspections.ItemName has
// been saved as an explicit empty string (e.g. an inspector cleared this
// exact field once and saved). Using firstNonEmpty() means this field
// keeps showing tbl_jobs.Item_Name (the value visible on the dashboard)
// until the inspector deliberately types a more specific Appliance-only
// name here, instead of silently rendering blank.
$currentItemName = firstNonEmpty($applianceData['ItemName'] ?? null, $defaultItemName) ?? '';

// 3. Fetch Test Parameters for this inspection
$testParams = [];
if ($applianceId) {
    try {
        $stmtParams = $pdo->prepare("SELECT * FROM tbl_appliance_test_parameters WHERE inspection_id = ? ORDER BY `row_number` ASC");
        $stmtParams->execute([$applianceId]);
        $testParams = $stmtParams->fetchAll(PDO::FETCH_ASSOC);
    } catch (\PDOException $e) {}
}

$indexedParams = [];
foreach ($testParams as $tp) {
    $indexedParams[$tp['row_number']] = $tp;
}

// 4. Item-Specific or General Appliance/Misc Checklists — via the shared
// helper (includes/checklist_helper.php). This is the exact fix for the
// "0 of 22 saved" bug: matching by $job['Category'] + $job['Item_Name']
// (tbl_jobs) — the same source approve_job.php checks — instead of
// $applianceData['ItemName'] (tbl_appliance_inspections), which could
// silently diverge from tbl_jobs.Item_Name and cause exactly this kind
// of "the form shows a different checklist than what gets validated"
// mismatch.
$applianceChecklists = getChecklistItemsForDisplay($pdo, $jobPkId, $job['Category'] ?? 'Appliance', $job['Item_Name'] ?? $currentItemName);

$me = current_user();
$isLocked = (int) ($job['Is_Locked'] ?? 0) === 1;
?>

<div class="card shadow-sm border-0" style="max-height: 85vh; display: flex; flex-direction: column;">
    <div class="card-header bg-dark text-white py-3 d-flex justify-content-between align-items-center flex-shrink-0">
        <h5 class="mb-0"><i class="fas fa-truck-monster me-2"></i> Heavy Equipment / Appliance Inspection — Job #<?= htmlspecialchars($jobDisplayNo) ?></h5>
        <div class="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) $jobPkId; ?>, 'html');"><i class="fas fa-print me-1"></i> Certificate</button>
            <?php elseif ($me && in_array($me['role'], ['admin', 'inspector'], true)): ?>
                <?php // FIX (admin report, 2026-08-25): "I write something in
                      // Certificate Title and it's not printed in the
                      // certificate." Root cause: this button used to open the
                      // certificate straight from the DATABASE, completely
                      // ignoring whatever the inspector just typed in the form
                      // above — that only reaches the database via the
                      // separate "Save" button further down. Now it saves the
                      // form first (identical to clicking Save) and only opens
                      // the preview once that save actually succeeds, so the
                      // preview always reflects exactly what's on screen. ?>
                <button type="button" class="btn btn-sm btn-outline-light fw-bold" onclick="previewApplianceAfterSave(<?= (int) $jobPkId; ?>);"><i class="fas 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): ?>
        <div class="card-body p-4 bg-light">
            <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="<?= $jobPkId; ?>">
                        <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="card-body p-4 bg-light" style="overflow-y: auto; flex-grow: 1;">
        <!-- Alert feedback container -->
        <div id="ajaxResponseAlert"></div>

        <form id="applianceInspectionForm">
            <input type="hidden" name="appliance_id" value="<?= htmlspecialchars($applianceId) ?>">
            <?php csrf_field(); ?>
            <input type="hidden" name="job_id" value="<?= htmlspecialchars($jobPkId) ?>">

            <!-- Section 1: Equipment Identification & Specifications -->
            <div class="card mb-4 shadow-sm border-0">
                <div class="card-header bg-secondary text-white py-2 small fw-bold">
                    <i class="fas fa-info-circle me-1"></i> Equipment Identification & Specifications
                </div>
                <div class="card-body">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label small fw-bold text-muted">Item Name</label>
                            <input type="text" class="form-control" name="ItemName" value="<?= htmlspecialchars($currentItemName) ?>" placeholder="e.g., Telescopic Mobile Crane">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label small fw-bold text-muted">Serial Number</label>
                            <input type="text" class="form-control font-monospace" name="Serial_No" value="<?= htmlspecialchars($applianceData['Serial_No'] ?? '') ?>" placeholder="Enter serial/chassis number">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label small fw-bold text-muted">Work Order Ref <i class="fas 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; save_appliance_job.php 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-4">
                            <label class="form-label small fw-bold text-muted">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 fw-bold text-muted">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 fw-bold text-muted">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 class="col-md-4">
                            <label class="form-label small fw-bold text-muted">Brand</label>
                            <input type="text" class="form-control" name="brand" value="<?= htmlspecialchars($applianceData['brand'] ?? '') ?>" placeholder="e.g., Sany, Liebherr">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label small fw-bold text-muted">Model</label>
                            <input type="text" class="form-control" name="model" value="<?= htmlspecialchars($applianceData['model'] ?? '') ?>" placeholder="e.g., QY50K">
                        </div>
                        <!-- "Item Name Description" removed as a visible
                             field — it duplicated "Item Name" above and
                             editing them independently caused mismatched
                             data. Kept as a hidden field so its existing
                             stored value is preserved, always mirroring
                             "Item Name" going forward. -->
                        <input type="hidden" name="item_name_description" id="itemNameDescriptionHidden" value="<?= htmlspecialchars($applianceData['item_name_description'] ?? $currentItemName) ?>">
                        <div class="col-md-4">
                            <label class="form-label small fw-bold text-muted">Certificate Title</label>
                            <!-- FIX (docx items 3/4): clarified placeholder +
                                 help text — this is the exact field that
                                 controls the wording printed on the
                                 certificate heading and asset description
                                 (generate_certificate.php), replacing the raw
                                 Item Name there. -->
                            <input type="text" class="form-control" name="Certificate_Title" value="<?= htmlspecialchars($applianceData['Certificate_Title'] ?? '') ?>" placeholder="EX: Diesel Powered Hydraulically Operated Mobile Crane">
                            <div class="form-text">Printed on the certificate heading in place of the raw Item Name above. Leave blank to fall back to Item Name.</div>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label small fw-bold text-muted">Inspection Result Status</label>
                            <select class="form-select fw-bold" name="Approval_Status">
                                <option value="Pass" <?= (($applianceData['Approval_Status'] ?? '') == 'Pass') ? 'selected' : '' ?>>Pass (Satisfactory)</option>
                                <option value="Fail" <?= (($applianceData['Approval_Status'] ?? '') == 'Fail') ? 'selected' : '' ?>>Fail (Unsatisfactory)</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Section 2: Item Description (Template Content) -->
            <div class="card mb-4 shadow-sm border-0">
                <div class="card-header bg-secondary text-white py-2 small fw-bold">
                    <i class="fas fa-file-alt me-1"></i> Item Description (Template Content)
                </div>
                <div class="card-body">
                    <textarea class="form-control font-monospace auto-expand" name="item_description" placeholder="Enter detailed technical description..." style="overflow:hidden; resize:vertical;"><?= htmlspecialchars($applianceData['item_description'] ?? '') ?></textarea>
                </div>
            </div>

            <!-- Section 2b: Certificate Notes -->
            <div class="card mb-4 shadow-sm border-0">
                <div class="card-header bg-secondary text-white py-2 small fw-bold">
                    <i class="fas fa-note-sticky me-1"></i> Certificate Notes
                </div>
                <div class="card-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label small fw-bold text-muted">Equipment Used</label>
                            <input type="text" class="form-control" name="equipment_used" value="<?= htmlspecialchars($applianceData['Equipment_Used'] ?? '') ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small fw-bold text-muted">Colour Code</label>
                            <input type="text" class="form-control" name="colour_code" value="<?= htmlspecialchars($applianceData['Colour_Code'] ?? '') ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small fw-bold text-muted">Details of Deviations/Omissions from original scope of work</label>
                            <textarea class="form-control" name="deviations" rows="2"><?= htmlspecialchars($applianceData['Deviations'] ?? '') ?></textarea>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small fw-bold text-muted">Details of Sub Contracted Work</label>
                            <textarea class="form-control" name="subcontracted" rows="2"><?= htmlspecialchars($applianceData['Subcontracted'] ?? '') ?></textarea>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small fw-bold text-muted">Previous Inspection/Test Details</label>
                            <textarea class="form-control" name="previous_inspection_details" rows="2"><?= htmlspecialchars($applianceData['Previous_Inspection_Details'] ?? '') ?></textarea>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small fw-bold text-muted">Comments</label>
                            <textarea class="form-control" name="comments" rows="2"><?= htmlspecialchars($applianceData['Comments'] ?? '') ?></textarea>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Section 3: Test Parameters (Load Chart Data) — hidden for
                 Misc items (A-Frames, slings, etc. don't have a load
                 chart the way Appliance/Crane equipment does). -->
            <?php if (strcasecmp($job['Category'] ?? '', 'Mis') !== 0): /* FIX (docx item 3): DB category is 'Mis', not 'Misc' — this condition never matched, so the test-parameters section (Boom Length/Radius/Tested Load/SWL) never hid for MIS jobs */ ?>
            <div class="card mb-4 shadow-sm border-0">
                <div class="card-header bg-secondary text-white py-2 small fw-bold">
                    <i class="fas fa-table me-1"></i> Test Parameters (Load Chart Data)
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive m-0">
                        <table class="table table-bordered table-striped align-middle mb-0">
                            <thead class="table-dark text-center small">
                                <tr>
                                    <th style="width: 8%;">S.No</th>
                                    <th style="width: 23%;">Boom Length</th>
                                    <th style="width: 23%;">Radius</th>
                                    <th style="width: 23%;">Tested Load</th>
                                    <th style="width: 23%;">Safe Working Load</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php for ($i = 1; $i <= 4; $i++):
                                    $rowD = $indexedParams[$i] ?? [];
                                ?>
                                    <tr>
                                        <td class="text-center fw-bold bg-light"><?= $i ?></td>
                                        <td><input type="text" class="form-control form-control-sm" name="test_params[<?= $i ?>][boom_length]" value="<?= htmlspecialchars($rowD['boom_length'] ?? '') ?>"></td>
                                        <td><input type="text" class="form-control form-control-sm" name="test_params[<?= $i ?>][radius]" value="<?= htmlspecialchars($rowD['radius'] ?? '') ?>"></td>
                                        <td><input type="text" class="form-control form-control-sm" name="test_params[<?= $i ?>][tested_load]" value="<?= htmlspecialchars($rowD['tested_load'] ?? '') ?>"></td>
                                        <td><input type="text" class="form-control form-control-sm" name="test_params[<?= $i ?>][safe_working_load]" value="<?= htmlspecialchars($rowD['safe_working_load'] ?? '') ?>"></td>
                                    </tr>
                                <?php endfor; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Section 4: Inspection Checklist Annex -->
            <div class="card mb-4 shadow-sm border-0">
                <div class="card-header bg-secondary text-white py-2 small fw-bold d-flex justify-content-between align-items-center">
                    <span><i class="fas fa-list-check me-1"></i> Inspection Checklist Annex</span>
                    <div>
                        <button type="button" class="btn btn-sm btn-outline-light me-2 js-pass-all-btn"><i class="fa-solid fa-check-double me-1"></i> Pass All</button>
                        <span class="badge bg-dark"><?= count($applianceChecklists); ?> Criteria Loaded</span>
                    </div>
                </div>
                <div class="card-body p-0">
                    <?php if (!empty($applianceChecklists)): ?>
                        <div class="table-responsive m-0">
                            <table class="table table-bordered table-striped align-middle mb-0">
                                <thead class="table-dark text-center small">
                                    <tr>
                                        <th style="width: 5%;">#</th>
                                        <th style="width: 55%;">Checklist Criteria</th>
                                        <th style="width: 20%;">Result</th>
                                        <th style="width: 20%;">Remarks</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $n = 1; foreach ($applianceChecklists as $chk):
                                        $mId = $chk['MasterCheckID'];
                                        $currResult = $chk['Result'] ?? 'Pass';
                                        $currRemarks = $chk['Remarks'] ?? '';
                                    ?>
                                        <tr>
                                            <td class="text-center fw-bold bg-light"><?= $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="p-3 text-muted small bg-white">
                            <i class="fas fa-info-circle me-1"></i> No specific checklist items found in master bank for item name: <strong><?= htmlspecialchars($currentItemName); ?></strong>.
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <hr class="my-4">

            <!-- Action Buttons -->
            <div class="d-flex justify-content-end align-items-center gap-2 pt-2">
                <?php if ($me && $me['role'] === 'admin'): ?>
                    <button type="button" class="btn btn-outline-success px-4 js-approve-btn" data-job-id="<?= $jobPkId; ?>"><i class="fa-solid fa-check-double me-1"></i> Approve & Lock</button>
                <?php endif; ?>
                <button type="button" class="btn btn-secondary px-4" data-bs-dismiss="modal">Close</button>
                <button type="button" id="saveApplianceBtn" class="btn btn-success px-5 fw-bold">
                    <i class="fas fa-save me-1"></i> Save Changes
                </button>
            </div>
        </form>

        <!-- Photo manager lives OUTSIDE the main form on purpose: it has
             its own independent upload <form>, and HTML forbids nesting
             one <form> inside another (browsers silently mis-handle it). -->
        <hr class="my-4">
        <?php
        $currentPageUrl = null; // AJAX mode, no page navigation
        include 'includes/photo_manager.php';
        ?>

        <script>
        (function () {
            // Keeps the now-hidden item_name_description in sync with the
            // visible Item Name field, instead of letting it drift independently.
            var itemNameField = document.querySelector('input[name="ItemName"]');
            var hiddenDesc = document.getElementById('itemNameDescriptionHidden');
            if (itemNameField && hiddenDesc) {
                itemNameField.addEventListener('input', function () {
                    hiddenDesc.value = itemNameField.value;
                });
            }

            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');
                    });
                });
            });

            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; ?>
</div>

<script>
// Auto-expand textarea to fit content
function initAutoResize() {
    const textarea = document.querySelector('textarea.auto-expand');
    if (textarea) {
        function resize() {
            textarea.style.height = 'auto';
            textarea.style.height = (textarea.scrollHeight + 4) + 'px';
        }
        textarea.addEventListener('input', resize);
        // Trigger immediately to fit any pre-filled or loaded text
        resize();
    }
}

// Run immediately upon AJAX injection
initAutoResize();

// BUG FIX (admin report, 2026-08-25): "I write something in Certificate
// Title and it's not printed in the certificate." The "Save" button and the
// "Preview" button used to be completely unconnected — Preview opened the
// certificate straight from the database, so any unsaved edit sitting in
// this form (Certificate Title, Item Name, checklist answers, anything)
// silently would not appear. Extracted the save call into a reusable
// function both buttons now go through, so Preview always saves first and
// only opens once that save actually succeeds — it can never show stale
// data again. Returns the fetch promise so callers can chain on it.
function saveApplianceInspectionForm() {
    var form = document.getElementById('applianceInspectionForm');
    var formData = new FormData(form);
    var alertBox = document.getElementById('ajaxResponseAlert');

    alertBox.innerHTML = '<div class="alert alert-info py-2"><i class="fas fa-spinner fa-spin me-1"></i> Saving changes...</div>';

    return fetch('save_appliance_job.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            alertBox.innerHTML = '<div class="alert alert-success py-2"><i class="fas fa-check-circle me-1"></i> ' + data.message + '</div>';
            setTimeout(() => {
                alertBox.innerHTML = '';
            }, 3000);
        } else {
            alertBox.innerHTML = '<div class="alert alert-danger py-2"><i class="fas fa-exclamation-triangle me-1"></i> Error: ' + data.message + '</div>';
        }
        return data;
    })
    .catch(err => {
        alertBox.innerHTML = '<div class="alert alert-danger py-2">Network or server error occurred while saving.</div>';
        console.error(err);
        return { status: 'error', message: 'Network or server error occurred while saving.' };
    });
}

document.getElementById('saveApplianceBtn').addEventListener('click', function() {
    saveApplianceInspectionForm();
});

// Called by the header "Preview" button — saves first, then opens the
// certificate only if the save actually succeeded, so what's shown always
// matches what was just typed. On a save failure the error is already
// visible in the form's own alert box (see saveApplianceInspectionForm
// above); the preview simply does not open, instead of silently showing
// old data.
function previewApplianceAfterSave(jobId) {
    saveApplianceInspectionForm().then(function (data) {
        if (data && data.status === 'success' && window.openCertificateModal) {
            openCertificateModal(jobId, 'html');
        }
    });
}
</script>
