<?php
// delete_job.php
// Soft-deletes a NOT-YET-APPROVED job into the Trash (see trash.php /
// restore_job.php). Admin-only, same pattern as unlock_job.php.
//
// STRICT PROJECT RULE: never hard-delete certificates or inspection
// records. This only ever sets tbl_jobs.Deleted_At — the row, and every
// related tbl_appliance_inspections / tbl_llg_inspections /
// tbl_training_records / tbl_job_checklists / tbl_inspection_photos row
// (linked via JobID) stays fully intact and is fully restorable.
//
// SAFETY: refuses to delete a LOCKED (approved) certificate, even if
// somehow requested — approved certificates are legal documents and must
// never disappear from the register through this path. The register UI
// never even shows this button for a locked job (table_rows.php only
// lists Is_Locked = 0 rows to begin with), but the server enforces it too
// in case of a stale page or a tampered request.

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

require_once 'db.php';
require_once 'includes/activity_log.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;
}

$me = current_user();

try {
    $stmtFind = $pdo->prepare("SELECT ID, Job_No, Is_Locked, Deleted_At FROM tbl_jobs WHERE ID = ? LIMIT 1");
    $stmtFind->execute([$jobId]);
    $job = $stmtFind->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 — approved certificates cannot be deleted. Unlock it first if it genuinely needs to be removed.']);
        exit;
    }

    if ($job['Deleted_At'] !== null) {
        echo json_encode(['status' => 'error', 'message' => 'This job is already in the Trash.']);
        exit;
    }

    $stmtDel = $pdo->prepare("UPDATE tbl_jobs SET Deleted_At = NOW(), Updated_By = ? WHERE ID = ?");
    $stmtDel->execute([$me['id'] ?? null, $jobId]);

    logActivity($pdo, $jobId, 'deleted', 'Moved to Trash by ' . ($me['name'] ?? 'unknown'));

    echo json_encode(['status' => 'success', 'message' => 'Job ' . $job['Job_No'] . ' moved to Trash.']);

} catch (\PDOException $e) {
    error_log('delete_job.php DB error: ' . $e->getMessage());
    echo json_encode(['status' => 'error', 'message' => 'A database error occurred. Please try again.']);
}
