<?php
header("Content-Type: application/json");
require_once __DIR__ . "/../services/db.php";

$conn = db();

if (!$conn) {
    http_response_code(500);
    echo json_encode(["error" => "Database connection failed"]);
    exit;
}

// 1. Authenticate user session
$token = $_COOKIE['session'] ?? null;
if (!$token) {
    $headers = getallheaders();
    $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    if (preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
        $token = $matches[1];
    }
}

if (!$token) {
    http_response_code(401);
    echo json_encode(["error" => "Unauthenticated"]);
    exit;
}

$sessionSql = "SELECT user_id FROM sessions WHERE token = ?";
$sessionStmt = sqlsrv_query($conn, $sessionSql, [$token]);

if ($sessionStmt === false || !($sessionRow = sqlsrv_fetch_array($sessionStmt, SQLSRV_FETCH_ASSOC))) {
    http_response_code(401);
    echo json_encode(["error" => "Invalid or expired session"]);
    exit;
}

$currentUserId = (int)$sessionRow['user_id'];

// 2. Parse request payload
$input = json_decode(file_get_contents("php://input"), true);
$projectId = $input['project_id'] ?? null;

if (!$projectId) {
    http_response_code(400);
    echo json_encode(["error" => "Missing project_id"]);
    exit;
}

// 3. Verify user is the project owner
$ownerCheckSql = "SELECT id, owner_id FROM projects WHERE id = ?";
$ownerStmt = sqlsrv_query($conn, $ownerCheckSql, [$projectId]);

if ($ownerStmt === false || !($project = sqlsrv_fetch_array($ownerStmt, SQLSRV_FETCH_ASSOC))) {
    http_response_code(404);
    echo json_encode(["error" => "Project not found"]);
    exit;
}

if ((int)$project['owner_id'] !== $currentUserId) {
    http_response_code(403);
    echo json_encode(["error" => "Only the project owner can delete this project"]);
    exit;
}

// 4. Delete project data (Cascading tasks, members, sections, and the project)
sqlsrv_query($conn, "DELETE FROM tasks WHERE project_id = ?", [$projectId]);
sqlsrv_query($conn, "DELETE FROM project_members WHERE project_id = ?", [$projectId]);
sqlsrv_query($conn, "DELETE FROM sections WHERE project_id = ?", [$projectId]);
$deleteProjectStmt = sqlsrv_query($conn, "DELETE FROM projects WHERE id = ?", [$projectId]);

if ($deleteProjectStmt === false) {
    http_response_code(500);
    echo json_encode(["error" => "Failed to delete project", "details" => sqlsrv_errors()]);
    exit;
}

echo json_encode([
    "success" => true,
    "message" => "Project and all associated data deleted successfully"
]);