<?php
/**
 * SmartForex Admin Engine - Upgraded Chat Queue Command Center
 * Location: public_html/api/admin_chat_handler.php
 */
session_start();
require_once __DIR__ . '/../includes/functions.php'; 
header('Content-Type: application/json');

$action = $_GET['action'] ?? ($_POST['action'] ?? '');

// 1. FETCH ALL USERS WITH PENDING/UNREAD MESSAGE MARKERS
if ($action === 'get_active_chat_users') {
    try {
        // Yeh query saare unique users degi aur count karegi ki unka aakhiri message 'user' ka hai ya nahi
        $stmt = $pdo->query("
            SELECT DISTINCT u.id, u.username, u.email,
            (SELECT message_text FROM support_chats WHERE user_id = u.id ORDER BY created_at DESC LIMIT 1) AS last_msg,
            (SELECT sender FROM support_chats WHERE user_id = u.id ORDER BY created_at DESC LIMIT 1) AS last_sender,
            (SELECT created_at FROM support_chats WHERE user_id = u.id ORDER BY created_at DESC LIMIT 1) AS last_time,
            -- Agar last message 'user' ka hai toh unread counter 1 rahega, warna 0
            IF((SELECT sender FROM support_chats WHERE user_id = u.id ORDER BY created_at DESC LIMIT 1) = 'user', 1, 0) AS is_unread
            FROM users u
            INNER JOIN support_chats c ON u.id = c.user_id
            ORDER BY is_unread DESC, last_time DESC
        ");
        echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
    } catch (PDOException $e) {
        echo json_encode([]);
    }
    exit;
}

// 2. FETCH SPECIFIC USER CHAT STREAM
if ($action === 'get_user_stream_for_admin') {
    $target_user_id = intval($_GET['user_id'] ?? 0);
    try {
        $stmt = $pdo->prepare("SELECT sender, message_text, media_file, created_at FROM support_chats WHERE user_id = ? ORDER BY created_at ASC");
        $stmt->execute([$target_user_id]);
        echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
    } catch (PDOException $e) {
        echo json_encode([]);
    }
    exit;
}

// 3. TRANSMIT ADMIN REPLY
if ($action === 'send_admin_reply') {
    $target_user_id = intval($_POST['user_id'] ?? 0);
    $msg = trim($_POST['msg'] ?? '');
    
    if ($target_user_id <= 0 || empty($msg)) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid routing payload.']); exit;
    }

    try {
        $stmt = $pdo->prepare("INSERT INTO support_chats (user_id, sender, message_text) VALUES (?, 'admin', ?)");
        $stmt->execute([$target_user_id, $msg]);
        echo json_encode(['status' => 'success']);
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

// 4. CLOSE TICKET PROTOCOL (MARKS CHAT AS NOTIFIED / CLEARED)
if ($action === 'close_user_ticket') {
    $target_user_id = intval($_POST['user_id'] ?? 0);
    if ($target_user_id <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid target ID']); exit;
    }
    try {
        // System automated dummy clear tag to shift the last sender away from 'user'
        $stmt = $pdo->prepare("INSERT INTO support_chats (user_id, sender, message_text) VALUES (?, 'admin', '--- Ticket Closed By Administration ---')");
        $stmt->execute([$target_user_id]);
        echo json_encode(['status' => 'success']);
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}