<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';

header('Content-Type: application/json');
auth_require_login();

$pdo = crm_pdo();

// Only admins/managers can delete projects
if (!gp_is_admin_like()) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'Μόνο οι Admins μπορούν να διαγράψουν έργα.']);
    exit;
}

$id = (int)($_POST['project_id'] ?? 0);
if ($id <= 0) {
    echo json_encode(['ok' => false, 'error' => 'Invalid project ID.']);
    exit;
}

// Verify project exists
$check = $pdo->prepare("SELECT title FROM projects WHERE id = ? LIMIT 1");
$check->execute([$id]);
$proj = $check->fetch();
if (!$proj) {
    echo json_encode(['ok' => false, 'error' => 'Το έργο δεν βρέθηκε.']);
    exit;
}

try {
    $pdo->beginTransaction();

    // ── Photos (physical files too) ──
    $photoStmt = $pdo->prepare("SELECT filename FROM project_photos WHERE project_id = ?");
    $photoStmt->execute([$id]);
    $photoFiles = $photoStmt->fetchAll(PDO::FETCH_COLUMN);
    foreach ($photoFiles as $fn) {
        $path = __DIR__ . '/../uploads/project_photos/' . $fn;
        if (file_exists($path)) @unlink($path);
    }
    $pdo->exec("DELETE FROM project_photos WHERE project_id = $id");

    // ── Employee job photos (linked via assignments) ──
    $pdo->exec("DELETE FROM employee_job_photos WHERE project_assignment_id IN (SELECT id FROM project_assignments WHERE project_id = $id)");

    // ── Assignments ──
    $pdo->exec("DELETE FROM project_assignments WHERE project_id = $id");

    // ── Comments ──
    try { $pdo->exec("DELETE FROM project_comments WHERE project_id = $id"); } catch (Throwable $e) {}

    // ── Visits ──
    $pdo->exec("DELETE FROM project_visits WHERE project_id = $id");

    // ── Equipment & sold equipment ──
    $pdo->exec("DELETE FROM project_equipment WHERE project_id = $id");
    try { $pdo->exec("DELETE FROM sold_equipment WHERE project_id = $id"); } catch (Throwable $e) {}

    // ── Payments & Expenses ──
    $pdo->exec("DELETE FROM project_payments WHERE project_id = $id");
    $pdo->exec("DELETE FROM project_expenses WHERE project_id = $id");
    try { $pdo->exec("DELETE FROM employee_expenses WHERE project_id = $id"); } catch (Throwable $e) {}

    // ── Partners & costings ──
    $pdo->exec("DELETE FROM project_partners WHERE project_id = $id");
    try { $pdo->exec("DELETE FROM partner_project_costings WHERE project_id = $id"); } catch (Throwable $e) {}

    // ── Tasks ──
    try { $pdo->exec("DELETE FROM project_tasks WHERE project_id = $id"); } catch (Throwable $e) {}

    // ── Misc ──
    try { $pdo->exec("DELETE FROM project_missing_parts WHERE project_id = $id"); } catch (Throwable $e) {}
    try { $pdo->exec("DELETE FROM project_duration_suggestions WHERE project_id = $id"); } catch (Throwable $e) {}
    try { $pdo->exec("DELETE FROM pool_calculator_specs WHERE project_id = $id"); } catch (Throwable $e) {}
    try { $pdo->exec("DELETE FROM project_user_access WHERE project_id = $id"); } catch (Throwable $e) {}

    // ── Finally delete the project ──
    $stmt = $pdo->prepare("DELETE FROM projects WHERE id = :id");
    $stmt->execute([':id' => $id]);

    gp_log_action($pdo, 'PROJECT_DELETE', 'project', $id, 'Deleted project: ' . $proj['title']);

    $pdo->commit();
    echo json_encode(['ok' => true, 'message' => 'Το έργο "' . $proj['title'] . '" διαγράφηκε.']);

} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(['ok' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
