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

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

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

try {
    // Get current user role
    $stmtRole = $pdo->prepare("SELECT role FROM users WHERE id = ?");
    $stmtRole->execute([$userId]);
    $myRole = strtoupper(trim($stmtRole->fetchColumn() ?? ''));
    $isMeMember = ($myRole === 'R.O' || $myRole === 'C.R.O' || $myRole === '');

    $stmt = $pdo->prepare("
        SELECT nm.id, nm.from_user_id, nm.subject, nm.body, nm.created_at, nm.parent_id, nm.can_reply,
               nr.read_at,
               u.first_name, u.last_name, u.nroi_id, u.role
        FROM notification_recipients nr
        JOIN notification_messages nm ON nm.id = nr.notification_id
        JOIN users u ON u.id = nm.from_user_id
        WHERE nr.user_id = ?
        ORDER BY nm.created_at DESC
    ");
    $stmt->execute([$userId]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Build a lookup of all message IDs in our dataset for root traversal
    $parentMap = [];
    foreach ($rows as $r) {
        $parentMap[$r['id']] = $r['parent_id'];
    }

    // Also fetch parent_ids for messages whose parents may not be in the dataset
    // (e.g. when the root was sent to someone else and we only have a reply)
    $allIds = array_column($rows, 'id');
    $allParentIds = array_filter(array_column($rows, 'parent_id'));
    $missingParents = array_diff($allParentIds, $allIds);

    // For any parent_id not in our dataset, resolve the root via DB
    $rootCache = []; // message_id => root_id
    if (!empty($missingParents)) {
        foreach ($missingParents as $missingId) {
            // Traverse up in DB to find the root
            $curr = (int) $missingId;
            for ($d = 0; $d < 20; $d++) {
                $s = $pdo->prepare("SELECT parent_id FROM notification_messages WHERE id = ?");
                $s->execute([$curr]);
                $pid = $s->fetchColumn();
                if ($pid) {
                    $curr = (int) $pid;
                } else {
                    break;
                }
            }
            $rootCache[$missingId] = $curr;
        }
    }

    $grouped = [];
    foreach ($rows as $r) {
        // Resolve root ID to group threads
        $curr = $r['id'];
        $depth = 0;
        while (isset($parentMap[$curr]) && !empty($parentMap[$curr]) && $depth < 50) {
            $curr = $parentMap[$curr];
            $depth++;
        }
        // If still has unresolved parent, look it up in cache
        if (!empty($parentMap[$r['id']]) && isset($rootCache[$parentMap[$r['id']]])) {
            $rootId = $rootCache[$parentMap[$r['id']]];
        } else {
            $rootId = $curr;
        }

        // Determine display name
        $senderRole = strtoupper(trim($r['role'] ?? ''));
        $isSenderOfficer = ($senderRole === 'AC' || $senderRole === 'AAC');
        $displayName = trim(($r['first_name'] ?? '') . ' ' . ($r['last_name'] ?? ''));

        if ($isMeMember && $isSenderOfficer) {
            $displayName = 'AC/AAC';
        }

        // Group Key: RootID only — one entry per conversation thread regardless of sender.
        // Since rows are ordered DESC by created_at, the first row we encounter per thread
        // is already the latest message.
        $key = (string) $rootId;

        if (!isset($grouped[$key])) {
            $grouped[$key] = [
                'id' => (int) $r['id'],
                'root_id' => (int) $rootId,
                'from_user_id' => (int) $r['from_user_id'],
                'from_name' => $displayName,
                'nroi_id' => $r['nroi_id'] ?? '',
                'subject' => $r['subject'],
                'body' => $r['body'],
                'created_at' => $r['created_at'],
                'read_at' => $r['read_at'],
                'parent_id' => $r['parent_id'] ? (int) $r['parent_id'] : null,
                'can_reply' => (int) ($r['can_reply'] ?? 1),
            ];
        }
    }

    $list = array_values($grouped);

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