<?php
require_once '../config/cors.php';
header('Content-Type: application/json');

require_once '../config/db.php';

$messageId = isset($_GET['message_id']) ? (int) $_GET['message_id'] : 0;
if ($messageId < 1) {
    echo json_encode(['status' => 'error', 'message' => 'message_id required']);
    exit;
}

try {
    // 1. Find the root message ID (traverse up parents)
    $currId = $messageId;
    $rootId = $messageId;

    // Simple traversal to find the ultimate parent
    for ($i = 0; $i < 10; $i++) {
        $stmt = $pdo->prepare("SELECT id, parent_id FROM notification_messages WHERE id = ?");
        $stmt->execute([$currId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row && $row['parent_id']) {
            $currId = (int) $row['parent_id'];
            $rootId = $currId;
        } else {
            break;
        }
    }

    // 2. Fetch the whole thread using recursive CTE to get full conversation tree
    $stmt = $pdo->prepare("
        WITH RECURSIVE thread_tree AS (
            SELECT id, parent_id, from_user_id, subject, body, created_at
            FROM notification_messages
            WHERE id = ?

            UNION ALL

            SELECT nm.id, nm.parent_id, nm.from_user_id, nm.subject, nm.body, nm.created_at
            FROM notification_messages nm
            JOIN thread_tree tt ON nm.parent_id = tt.id
        )
        SELECT tt.id, tt.parent_id, tt.from_user_id, tt.subject, tt.body, tt.created_at,
               u.first_name, u.last_name, u.nroi_id, u.role
        FROM thread_tree tt
        JOIN users u ON u.id = tt.from_user_id
        ORDER BY tt.created_at ASC
    ");
    $stmt->execute([$rootId]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $thread = [];
    foreach ($rows as $r) {
        $thread[] = [
            'id' => (int) $r['id'],
            'parent_id' => $r['parent_id'] ? (int) $r['parent_id'] : null,
            'from_user_id' => (int) $r['from_user_id'],
            'from_name' => trim(($r['first_name'] ?? '') . ' ' . ($r['last_name'] ?? '')),
            'nroi_id' => $r['nroi_id'] ?? '',
            'role' => $r['role'] ?? '',
            'subject' => $r['subject'],
            'body' => $r['body'],
            'created_at' => $r['created_at'],
        ];
    }

    echo json_encode([
        'status' => 'success',
        'root_id' => $rootId,
        'thread' => $thread
    ]);
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
