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

$conn = db();
$projectId = $_GET['project'] ?? $_GET['project_id'] ?? null;

if (!$projectId) {
    echo json_encode([]);
    exit;
}

// Join tasks with users table to get real assignee names
$sql = "SELECT 
            t.id,
            t.title,
            t.description,
            t.status,
            t.priority,
            t.due_date,
            t.section_id,
            t.assignee_id,
            u.name AS assignee_name
        FROM tasks t
        LEFT JOIN users u ON t.assignee_id = u.id
        WHERE t.project_id = ?
        ORDER BY t.id DESC";

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

$tasks = [];
if ($stmt !== false) {
    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
        $formattedDueDate = null;
        if (isset($row['due_date']) && $row['due_date'] instanceof DateTime) {
            $formattedDueDate = $row['due_date']->format('Y-m-d');
        } else if (!empty($row['due_date'])) {
            $formattedDueDate = (string)$row['due_date'];
        }

        $tasks[] = [
            "id" => (int)$row['id'],
            "title" => $row['title'],
            "description" => $row['description'] ?? '',
            "status" => $row['status'] ?? 'todo',
            "priority" => $row['priority'] ?? 'Normal',
            "due_date" => $formattedDueDate,
            "section_id" => $row['section_id'] ? (int)$row['section_id'] : null,
            "assignee_id" => $row['assignee_id'] ? (int)$row['assignee_id'] : null,
            // Use real database user name; default to null if unassigned
            "assignee" => $row['assignee_name'] ?? null,
            "assignee_name" => $row['assignee_name'] ?? null
        ];
    }
}

echo json_encode($tasks);