<?php
// backend/api/tasks/stream.php

set_time_limit(0);
ignore_user_abort(true);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
session_write_close(); // Prevent session locking

if (function_exists('apache_setenv')) {
    @apache_setenv('no-gzip', 1);
}
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);

while (ob_get_level() > 0) {
    ob_end_flush();
}
ob_implicit_flush(true);

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache, no-transform');
header('Connection: keep-alive');
header('X-Accel-Buffering: no');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');

$projectId = $_GET['project_id'] ?? null;
if (!$projectId) {
    echo "data: " . json_encode(["status" => "error", "message" => "Missing project_id"]) . "\n\n";
    flush();
    exit;
}

require_once __DIR__ . '/../services/db.php';

try {
    $conn = db();
} catch (Throwable $e) {
    echo "data: " . json_encode(["status" => "error", "message" => "DB connection failed"]) . "\n\n";
    flush();
    exit;
}

// 1. Connection Handshake
echo "data: " . json_encode(["status" => "connected", "project_id" => $projectId]) . "\n\n";
flush();

$lastChecksum = '';
$startTime = time();

while (time() - $startTime < 300) {
    if (connection_aborted()) {
        break;
    }

    $currentTasks = [];
    $checksumString = '';

    if (function_exists('sqlsrv_query') && !($conn instanceof PDO)) {
        $sql = "SELECT id, section_id, sort_order, title FROM tasks WHERE project_id = ? ORDER BY id ASC";
        $stmt = sqlsrv_query($conn, $sql, [(int)$projectId]);

        if ($stmt !== false) {
            while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $currentTasks[] = $row;
                $checksumString .= "{$row['id']}-{$row['section_id']}-{$row['sort_order']};";
            }
        }
    } else if ($conn instanceof PDO) {
        $sql = "SELECT id, section_id, sort_order, title FROM tasks WHERE project_id = :pid ORDER BY id ASC";
        $stmt = $conn->prepare($sql);
        $stmt->execute([':pid' => $projectId]);
        $currentTasks = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($currentTasks as $row) {
            $checksumString .= "{$row['id']}-{$row['section_id']}-{$row['sort_order']};";
        }
    }

    $currentChecksum = md5($checksumString);

    // Initial baseline on stream connect
    if ($lastChecksum === '') {
        $lastChecksum = $currentChecksum;
    } 
    // Trigger update whenever section_id or sort_order changes in the DB
    else if ($currentChecksum !== $lastChecksum) {
        $lastChecksum = $currentChecksum;
        $jsonPayload = json_encode($currentTasks);

        echo "data: {$jsonPayload}\n\n";
        echo "event: task_update\n";
        echo "data: {$jsonPayload}\n\n";
        flush();
    }

    // Ping heartbeat
    echo ": ping\n\n";
    flush();

    sleep(1);
}