<?php
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(['error' => 'Method not allowed']);
    exit;
}

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

try {
    gp_require_csrf_api();

    $input = json_decode(file_get_contents('php://input'), true);
    $photoId = (int)($input['photo_id'] ?? 0);
    $projectId = (int)($input['project_id'] ?? 0);
    $shared = empty($input['shared']) ? 0 : 1;

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

    gp_require_project_edit($pdo, $projectId);

    $stmt = $pdo->prepare("UPDATE project_photos SET shared_with_crew = :s WHERE id = :id AND project_id = :pid");
    $stmt->execute([':s' => $shared, ':id' => $photoId, ':pid' => $projectId]);

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

} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
