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

$conn = db();

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

// 1. Get session token
$token = $_COOKIE['session'] ?? null;

if (!$token) {
    $headers = getallheaders();
    $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    if (preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
        $token = $matches[1];
    }
}

if (!$token) {
    http_response_code(401);
    echo json_encode(["error" => "Unauthenticated - No session token provided"]);
    exit;
}

// 2. Resolve user ID from session token
$sessionSql = "SELECT user_id FROM sessions WHERE token = ?";
$sessionStmt = sqlsrv_query($conn, $sessionSql, [$token]);

if ($sessionStmt === false) {
    http_response_code(500);
    echo json_encode(["error" => "Session query error", "details" => sqlsrv_errors()]);
    exit;
}

$sessionRow = sqlsrv_fetch_array($sessionStmt, SQLSRV_FETCH_ASSOC);

if (!$sessionRow) {
    http_response_code(401);
    echo json_encode(["error" => "Invalid or expired session"]);
    exit;
}

$currentUserId = (int)$sessionRow['user_id'];

// 3. Try primary query with all optional columns
$fullSql = "SELECT 
                t.id,
                t.title,
                t.description,
                t.status,
                t.priority,
                t.due_date,
                t.project_id,
                t.assignee_id,
                p.name AS project_name,
                u.name AS assignee_name
            FROM tasks t
            JOIN projects p ON t.project_id = p.id
            LEFT JOIN users u ON t.assignee_id = u.id
            WHERE p.owner_id = ? OR p.id IN (SELECT project_id FROM project_members WHERE user_id = ?)
            ORDER BY t.id DESC";

$stmt = sqlsrv_query($conn, $fullSql, [$currentUserId, $currentUserId]);

// Fallback query if columns (e.g. priority, due_date) do not exist yet in DB
if ($stmt === false) {
    $fallbackSql = "SELECT 
                        t.id,
                        t.title,
                        t.status,
                        t.project_id,
                        p.name AS project_name
                    FROM tasks t
                    JOIN projects p ON t.project_id = p.id
                    WHERE p.owner_id = ? OR p.id IN (SELECT project_id FROM project_members WHERE user_id = ?)
                    ORDER BY t.id DESC";

    $stmt = sqlsrv_query($conn, $fallbackSql, [$currentUserId, $currentUserId]);

    if ($stmt === false) {
        http_response_code(500);
        echo json_encode([
            "error" => "Tasks query failed", 
            "details" => sqlsrv_errors()
        ]);
        exit;
    }
}

$tasks = [];
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" => strtolower($row['status'] ?? 'todo') === 'completed' ? 'completed' : ($row['status'] ?? 'todo'),
        "priority" => $row['priority'] ?? 'Normal',
        "due_date" => $formattedDueDate,
        "project_id" => (int)$row['project_id'],
        "project_name" => $row['project_name'] ?? 'Project',
        "assignee_id" => isset($row['assignee_id']) ? (int)$row['assignee_id'] : null,
        "assignee_name" => $row['assignee_name'] ?? 'Unassigned'
    ];
}

echo json_encode($tasks);