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

$conn = db();
$taskId = isset($_GET['task_id']) ? (int)$_GET['task_id'] : null;

if (!$taskId) {
    http_response_code(400);
    echo json_encode(["error" => "task_id is required"]);
    exit;
}

$sql = "SELECT id, task_id, title, is_completed, created_at FROM subtasks WHERE task_id = ? ORDER BY id ASC";
$stmt = sqlsrv_query($conn, $sql, [$taskId]);

$subtasks = [];
if ($stmt !== false) {
    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
        $subtasks[] = [
            "id" => (int)$row['id'],
            "task_id" => (int)$row['task_id'],
            "title" => $row['title'],
            "is_completed" => (bool)$row['is_completed']
        ];
    }
}

echo json_encode($subtasks);