<?php
// approve_job.php
// Admin-only. Locks a certificate and moves it from the active register
// into Reports. Validates completion criteria SERVER-SIDE — a disabled
// button in the browser is a UX nicety, not security; the real gate is
// here.

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

require_once 'db.php';
require_once 'includes/activity_log.php';
require_once 'includes/checklist_helper.php';
header('Content-Type: application/json');
require_csrf();

$jobId = isset($_POST['job_id']) ? (int) $_POST['job_id'] : 0;

if ($jobId <= 0) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid job reference.']);
    exit;
}

$stmt = $pdo->prepare("SELECT ID, Category, Item_Name, Is_Locked FROM tbl_jobs WHERE ID = ?");
$stmt->execute([$jobId]);
$job = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$job) {
    echo json_encode(['status' => 'error', 'message' => 'Job not found.']);
    exit;
}

if ((int) $job['Is_Locked'] === 1) {
    echo json_encode(['status' => 'error', 'message' => 'This certificate is already approved and locked.']);
    exit;
}

$isTraining = strcasecmp((string) $job['Category'], 'Training') === 0;

if ($isTraining) {
    // Training completion: Trainee Name + Trainee ID + Course Name filled.
    $stmtT = $pdo->prepare("SELECT Trainee_Name, Trainee_ID FROM tbl_training_records WHERE JobID = ?");
    $stmtT->execute([$jobId]);
    $t = $stmtT->fetch(PDO::FETCH_ASSOC);

    $missing = [];
    if (empty($t['Trainee_Name'])) $missing[] = 'Trainee Name';
    if (empty($t['Trainee_ID'])) $missing[] = 'Trainee ID';
    if (empty($job['Item_Name'])) $missing[] = 'Course Name';

    if (!empty($missing)) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Cannot approve — missing: ' . implode(', ', $missing) . '.',
        ]);
        exit;
    }
} else {
    // LLG / Appliance / Misc completion: every applicable checklist item
    // must have an actual saved answer (i.e. the checklist section was
    // engaged with — not just showing default text on an unsaved form).
    // BUG FIX: now uses the exact same getApplicableChecklistIds() logic
    // that view_appliance_job.php / view_job.php use to DECIDE which
    // items to show and save — previously this used a subtly different
    // (and looser) query, so it could count items the edit form never
    // even displayed, making approval impossible no matter what was saved.
    $applicableIds = getApplicableChecklistIds($pdo, $job['Category'], $job['Item_Name']);
    $expectedCount = count($applicableIds);

    // BUG FIX: this used to count EVERY row in tbl_job_checklists for the
    // job, including stale rows left over from a previous item name/category
    // or a since-deactivated master checklist item. That inflated count
    // could mask a real shortfall (e.g. 9 stale+current rows >= 8 currently
    // applicable, even though only 5 of the 8 CURRENTLY applicable ones were
    // actually answered) — restricting to the current applicable ID set
    // makes this an exact, trustworthy completeness check.
    if (!empty($applicableIds)) {
        $placeholders = implode(',', array_fill(0, count($applicableIds), '?'));
        $actualStmt = $pdo->prepare("SELECT COUNT(*) FROM tbl_job_checklists WHERE JobID = ? AND MasterCheckID IN ($placeholders)");
        $actualStmt->execute(array_merge([$jobId], $applicableIds));
        $actualCount = (int) $actualStmt->fetchColumn();
    } else {
        $actualCount = 0;
    }

    if ($expectedCount > 0 && $actualCount < $expectedCount) {
        echo json_encode([
            'status' => 'error',
            'message' => "Cannot approve — checklist incomplete ({$actualCount} of {$expectedCount} items saved). Open the job, review the checklist, and save it first.",
        ]);
        exit;
    }
}

$me = current_user();

$upd = $pdo->prepare(
    "UPDATE tbl_jobs SET Is_Locked = 1, Approved_By = ?, Approved_At = NOW() WHERE ID = ?"
);
$upd->execute([$me['id'], $jobId]);

logActivity($pdo, $jobId, 'approved', 'Approved and locked by ' . ($me['name'] ?? 'unknown'));

echo json_encode(['status' => 'success', 'message' => 'Certificate approved and locked. Moved to Reports.']);
