<?php
// restore_job.php
// Restores a soft-deleted job out of the Trash (see delete_job.php /
// trash.php) back into the active register. Admin-only.

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, 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 ($job['Deleted_At'] === null) {
        echo json_encode(['status' => 'error', 'message' => 'This job is not in the Trash.']);
        exit;
    }

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

    logActivity($pdo, $jobId, 'restored', 'Restored from Trash by ' . ($me['name'] ?? 'unknown'));

    echo json_encode(['status' => 'success', 'message' => 'Job ' . $job['Job_No'] . ' restored to the active register.']);

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