<?php
/**
 * API: Delete a project photo
 */
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'Method not allowed']);
    exit;
}

auth_require_login();
$pdo = crm_pdo();
header('Content-Type: application/json; charset=utf-8');

try {
    $input     = json_decode(file_get_contents('php://input'), true);
    $photoId   = (int)($input['photo_id']   ?? 0);
    $projectId = (int)($input['project_id'] ?? 0);
    $csrfToken = (string)($input['csrf_token'] ?? '');

    // CSRF check (token from JSON body)
    if (!csrf_verify($csrfToken)) {
        http_response_code(419);
        echo json_encode(['ok' => false, 'error' => 'CSRF token invalid. Please refresh the page.']);
        exit;
    }

    if ($photoId <= 0 || $projectId <= 0) {
        throw new Exception('Invalid parameters.');
    }

    // Require edit access to this project
    gp_require_project_edit($pdo, $projectId);

    // Fetch the photo record
    $st = $pdo->prepare("SELECT filename FROM project_photos WHERE id = :id AND project_id = :pid LIMIT 1");
    $st->execute([':id' => $photoId, ':pid' => $projectId]);
    $photo = $st->fetch();

    if (!$photo) {
        throw new Exception('Photo not found.');
    }

    // Delete file from disk (try both upload dirs)
    foreach (['project_photos', 'photos'] as $subdir) {
        $filePath = gp_upload_path($subdir) . '/' . basename($photo['filename']);
        if (file_exists($filePath)) {
            @unlink($filePath);
            break;
        }
    }

    // Delete DB record
    $pdo->prepare("DELETE FROM project_photos WHERE id = :id AND project_id = :pid")
        ->execute([':id' => $photoId, ':pid' => $projectId]);

    echo json_encode(['ok' => true]);

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
