<?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;
    }

    if ($newStatus === 'completed' && !auth_is_admin_like()) {
        // Fetch project budget and installation_cost
        $stmtP = $pdo->prepare("SELECT budget FROM projects WHERE id = ?");
        $stmtP->execute([$projectId]);
        $proj = $stmtP->fetch(PDO::FETCH_ASSOC);

        if (!$proj) {
            echo json_encode(['ok' => false, 'error' => 'Το έργο δεν βρέθηκε.']);
            exit;
        }

        $budget = (float)($proj['budget'] ?? 0);

        if ($budget <= 0) {
            echo json_encode(['ok' => false, 'error' => 'Πρέπει να ορίσετε τη χρέωση (budget) του έργου πριν την ολοκλήρωση.']);
            exit;
        }

        // Check if fully paid
        $stmtPay = $pdo->prepare("SELECT COALESCE(SUM(amount), 0) FROM project_payments WHERE project_id = ? AND payment_type IN ('deposit', 'payment')");
        $stmtPay->execute([$projectId]);
        $totalPaid = (float)$stmtPay->fetchColumn();

        if ($totalPaid < $budget) {
            $diff = $budget - $totalPaid;
            echo json_encode(['ok' => false, 'error' => "Το έργο δεν είναι εξοφλημένο. Υπολείπονται ακόμη €" . number_format($diff, 2) . " για την εξόφληση."]);
            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']);
}

