<?php
// unlock_job.php
// Admin-only. Moves an approved certificate back to the active register
// for editing. Approved_By/Approved_At are intentionally left as-is (the
// historical record of the last approval survives until it's re-approved,
// which overwrites them) — only Is_Locked flips.

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

$stmt = $pdo->prepare("UPDATE tbl_jobs SET Is_Locked = 0 WHERE ID = ?");
$stmt->execute([$jobId]);

$me = current_user();
logActivity($pdo, $jobId, 'unlocked', 'Unlocked by ' . ($me['name'] ?? 'unknown'));

echo json_encode(['status' => 'success', 'message' => 'Certificate unlocked and returned to the register.']);
