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

$projectId = isset($_GET['project']) ? (int)$_GET['project'] : (isset($_GET['project_id']) ? (int)$_GET['project_id'] : 1);

// Safely pull sort_order falling back to 0 or id order
$sql = "SELECT id, project_id, name, ISNULL(sort_order, 0) AS sort_order 
        FROM sections 
        WHERE project_id = ? 
        ORDER BY ISNULL(sort_order, 0) ASC, id ASC";

$stmt = sqlsrv_query($conn, $sql, [$projectId]);

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

$sections = [];
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
    $sections[] = [
        "id" => (int)$row['id'],
        "project_id" => (int)$row['project_id'],
        "name" => $row['name'],
        "sort_order" => (int)$row['sort_order']
    ];
}

echo json_encode($sections);