<?php
// upload_photo.php
// Called via fetch(FormData) from includes/photo_manager.php. Always
// returns JSON — never redirects, since every caller is now AJAX-based.
// Category-agnostic: works identically for every job category.

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

require 'db.php';
header('Content-Type: application/json');
require_csrf();

$jobId = isset($_POST['job_id']) ? (int) $_POST['job_id'] : 0;
$photoType = trim($_POST['photo_type'] ?? 'Overview');
$caption   = trim($_POST['caption'] ?? '');

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

$check = $pdo->prepare("SELECT ID, Is_Locked FROM tbl_jobs WHERE ID = ?");
$check->execute([$jobId]);
$jobRow = $check->fetch(PDO::FETCH_ASSOC);
if (!$jobRow) {
    echo json_encode(['status' => 'error', 'message' => 'Job not found.']);
    exit;
}

// SECURITY FIX: Approve & Lock is supposed to freeze a certificate's
// record permanently — this check was missing here, so photos could
// still be added to an already-approved, locked certificate, silently
// changing its evidence after the fact.
if ((int) $jobRow['Is_Locked'] === 1) {
    echo json_encode(['status' => 'error', 'message' => 'This certificate is approved and locked. Photos cannot be changed unless an Admin unlocks it.']);
    exit;
}

if (!isset($_FILES['photo']) || $_FILES['photo']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['status' => 'error', 'message' => 'No file received, or the upload failed.']);
    exit;
}

$allowedTypes = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime  = finfo_file($finfo, $_FILES['photo']['tmp_name']);
finfo_close($finfo);

if (!isset($allowedTypes[$mime])) {
    echo json_encode(['status' => 'error', 'message' => 'Only JPG, PNG, or WEBP images are allowed.']);
    exit;
}

if ($_FILES['photo']['size'] > 10 * 1024 * 1024) {
    echo json_encode(['status' => 'error', 'message' => 'Image is too large (max 10MB).']);
    exit;
}

$uploadDir = __DIR__ . '/uploads/inspections/' . $jobId . '/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$filename = bin2hex(random_bytes(16)) . '.' . $allowedTypes[$mime];
$destPath = $uploadDir . $filename;

if (!move_uploaded_file($_FILES['photo']['tmp_name'], $destPath)) {
    echo json_encode(['status' => 'error', 'message' => 'Could not save the uploaded file.']);
    exit;
}

$publicPath = 'uploads/inspections/' . $jobId . '/' . $filename;

$stmt = $pdo->prepare(
    "INSERT INTO tbl_inspection_photos (JobID, Photo_Path, Photo_Type, Caption)
     VALUES (?, ?, ?, ?)"
);
$stmt->execute([$jobId, $publicPath, $photoType ?: 'Overview', $caption ?: null]);

echo json_encode(['status' => 'success', 'message' => 'Photo uploaded.']);
