<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['ok' => false, 'error' => 'Invalid method']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

$projectId = (int)($input['project_id'] ?? 0);
$newStatus = trim((string)($input['status'] ?? ''));
$token = trim((string)($input['csrf_token'] ?? ''));

// Validate CSRF
if (empty($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $token)) {
    echo json_encode(['ok' => false, 'error' => 'CSRF verification failed']);
    exit;
}

if ($projectId <= 0 || $newStatus === '') {
    echo json_encode(['ok' => false, 'error' => 'Missing data']);
    exit;
}

$pdo = crm_pdo();
$role = gp_user_role($pdo);

// Check permissions
$canEdit = false;
if (gp_is_full_project_access_role($role)) {
    $canEdit = true;
} elseif (gp_is_secretary_like_role($role)) {
    $stmtCh = $pdo->prepare("SELECT can_edit FROM project_edit_permissions WHERE project_id = ? AND user_id = ?");
    $stmtCh->execute([$projectId, gp_current_user_id()]);
    if ((int)$stmtCh->fetchColumn() === 1) {
        $canEdit = true;
    }
}

if (!$canEdit) {
    echo json_encode(['ok' => false, 'error' => 'Permission denied']);
    exit;
}

try {
    // Validate if status is valid
    $stmtValid = $pdo->prepare("SELECT COUNT(*) FROM project_statuses WHERE status_code = ?");
    $stmtValid->execute([$newStatus]);
    if ($stmtValid->fetchColumn() == 0 && $newStatus !== 'unknown') {
        echo json_encode(['ok' => false, 'error' => 'Invalid status code']);
        exit;
    }

    $stmtUpdate = $pdo->prepare("UPDATE projects SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
    $stmtUpdate->execute([$newStatus, $projectId]);
    echo json_encode(['ok' => true]);
} catch (Throwable $e) {
    echo json_encode(['ok' => false, 'error' => 'Database error']);
}

