<?php
require_once __DIR__ . "/../auth/require-auth.php";
require_once __DIR__ . "/../services/db.php";

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

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

if (empty($data['name']) || empty($data['project_id'])) {
    die(json_encode(["error" => "Missing required fields"]));
}

// 1. Insert and select identity in ONE query block to bypass active cursor lock bugs
$sql = "INSERT INTO sections (project_id, name, sort_order) VALUES (?, ?, 999); 
        SELECT SCOPE_IDENTITY() AS last_id;";

$stmt = sqlsrv_query($conn, $sql, [$data['project_id'], $data['name']]);

if ($stmt === false) {
    die(json_encode(["error" => "Insert statement failed", "details" => sqlsrv_errors()]));
}

// Move past the implicit empty row created by INSERT to get the identity row result
sqlsrv_next_result($stmt);
$id_row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$last_id = $id_row['last_id'] ?? null;

if (!$last_id) {
    die(json_encode(["error" => "Could not extract identity column scope ID"]));
}

// 2. Clear query pointers cleanly and select the fresh row safely
sqlsrv_free_stmt($stmt);

$sql2 = "SELECT * FROM sections WHERE id = ?";
$stmt2 = sqlsrv_query($conn, $sql2, [$last_id]);
$row = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC);

sqlsrv_free_stmt($stmt2);

echo json_encode($row);