<?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 messages sent by this user, utilizing Recursive CTE to find the conversation root (thread grouping)
    // This allows us to group replies into a single conversation view
    $stmt = $pdo->prepare("
        WITH RECURSIVE hierarchy AS (
           SELECT id AS origin_id, id, parent_id
           FROM notification_messages
           WHERE from_user_id = ?
           
           UNION ALL
           
           SELECT h.origin_id, nm.id, nm.parent_id
           FROM notification_messages nm
           JOIN hierarchy h ON nm.id = h.parent_id
        )
        SELECT nm.id, nm.from_user_id, nm.subject, nm.body, nm.created_at, nm.parent_id, nm.can_reply,
               roots.root_id,
               GROUP_CONCAT(DISTINCT CONCAT(u.first_name, ' ', u.last_name) SEPARATOR ', ') as recipient_names
        FROM notification_messages nm
        JOIN (
            SELECT origin_id, id as root_id
            FROM hierarchy
            WHERE parent_id IS NULL
        ) as roots ON roots.origin_id = nm.id
        LEFT JOIN notification_recipients nr ON nr.notification_id = nm.id
        LEFT JOIN users u ON u.id = nr.user_id
        WHERE nm.from_user_id = ?
        GROUP BY nm.id
        ORDER BY nm.created_at DESC
    ");
    $stmt->execute([$userId, $userId]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $list = [];
    $seenRoots = [];

    // Get user role to determine display format
    $stmtRole = $pdo->prepare("SELECT role FROM users WHERE id = ?");
    $stmtRole->execute([$userId]);
    $userRoleVal = $stmtRole->fetchColumn();
    $userRoleVal = strtoupper(trim($userRoleVal ?? ''));
    $isMember = ($userRoleVal === 'R.O' || $userRoleVal === 'C.R.O' || $userRoleVal === '');

    foreach ($rows as $r) {
        $root = $r['root_id'];

        // If we have already seen this conversation root, skip (since we ordered by DESC, we already have the latest)
        if (in_array($root, $seenRoots)) {
            continue;
        }
        $seenRoots[] = $root;

        // If user is a Member, they always message AC/AAC. Show "AC/AAC" instead of specific names.
        // If user is an Officer, show specific names.
        $recipientDisplay = $r['recipient_names'] ?? 'No recipients';
        if ($isMember) {
            $recipientDisplay = 'AC/AAC';
        }

        $list[] = [
            'id' => (int) $r['id'],
            'from_user_id' => (int) $r['from_user_id'],
            'subject' => $r['subject'],
            'body' => $r['body'],
            'created_at' => $r['created_at'],
            'parent_id' => $r['parent_id'] ? (int) $r['parent_id'] : null,
            'recipient_names' => $recipientDisplay,
            'can_reply' => (int) ($r['can_reply'] ?? 1),
        ];
    }

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