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

$conn = db();

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

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

$name = trim($data["name"] ?? '');
$description = trim($data["description"] ?? '');
$dueDate = !empty($data["due_date"]) ? $data["due_date"] : null;
$userId = $authUser["id"] ?? $authUser["user_id"];

if (empty($name)) {
    http_response_code(400);
    echo json_encode(["error" => "Project name is required"]);
    exit;
}

// 1. Insert Project
$sql = "INSERT INTO projects (name, description, owner_id, due_date, status, created_at)
        VALUES (?, ?, ?, ?, 'Active', GETDATE())";

$stmt = sqlsrv_query($conn, $sql, [$name, $description, $userId, $dueDate]);

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

// 2. Fetch New Project ID
$res = sqlsrv_query($conn, "SELECT SCOPE_IDENTITY() AS id");
$row = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC);
$pid = $row["id"];

// 3. Add Creator to project_members as 'owner'
sqlsrv_query(
    $conn,
    "INSERT INTO project_members (project_id, user_id, role) VALUES (?, ?, 'owner')",
    [$pid, $userId]
);

// 4. Auto-generate default Asana sections for the project board
$defaultSections = ['To Do', 'In Progress', 'Done'];
foreach ($defaultSections as $index => $secName) {
    sqlsrv_query(
        $conn,
        "INSERT INTO sections (project_id, name, display_order) VALUES (?, ?, ?)",
        [$pid, $secName, $index + 1]
    );
}

echo json_encode([
    "success" => true,
    "project_id" => $pid,
    "message" => "Project and default board sections created successfully."
]);