<?php
// delete_photo.php
// Called via fetch() from includes/photo_manager.php. Always returns JSON.

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

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

$photoId = isset($_GET['photo_id']) ? (int) $_GET['photo_id'] : 0;

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

$stmt = $pdo->prepare("SELECT PhotoID, Photo_Path, JobID FROM tbl_inspection_photos WHERE PhotoID = ?");
$stmt->execute([$photoId]);
$photo = $stmt->fetch(PDO::FETCH_ASSOC);

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

// SECURITY FIX: same lock-bypass class as upload_photo.php — deleting
// evidence from an approved certificate must be blocked exactly like
// adding it is.
$lockCheck = $pdo->prepare("SELECT Is_Locked FROM tbl_jobs WHERE ID = ?");
$lockCheck->execute([$photo['JobID']]);
if ((int) $lockCheck->fetchColumn() === 1) {
    echo json_encode(['status' => 'error', 'message' => 'This certificate is approved and locked. Photos cannot be changed unless an Admin unlocks it.']);
    exit;
}

$filePath = __DIR__ . '/' . $photo['Photo_Path'];
if (is_file($filePath)) {
    @unlink($filePath);
}

$del = $pdo->prepare("DELETE FROM tbl_inspection_photos WHERE PhotoID = ?");
$del->execute([$photoId]);

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