<?php
session_start();
require_once '../db/config.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

// Support both regular user and admin polling
$user_id = isset($_GET['user_id']) ? $_GET['user_id'] : $_SESSION['user_id'];

// Admin Poll Logic (Global notifications)
if (isset($_GET['admin_poll'])) {
    // Check for latest message ID
    $last_id = db()->query("SELECT MAX(id) FROM messages")->fetchColumn() ?: 0;
    
    // Check for pending/matching orders
    $pending_orders = db()->query("SELECT COUNT(*) FROM fiat_orders WHERE status IN ('matching', 'submitting')")->fetchColumn() ?: 0;
    
    // Get latest message content if it's a recharge notification
    $latest_msg = db()->query("SELECT message FROM messages WHERE sender = 'user' ORDER BY id DESC LIMIT 1")->fetchColumn();
    $is_recharge = ($latest_msg && strpos($latest_msg, '[RECHARGE_') === 0);

    echo json_encode([
        'last_id' => (int)$last_id,
        'pending_orders' => (int)$pending_orders,
        'is_recharge' => $is_recharge,
        'latest_msg' => $latest_msg
    ]);
    exit;
}

// Regular User or specific Chat Polling Logic
$stmt = db()->prepare("SELECT COUNT(*) FROM messages WHERE user_id = ?");
$stmt->execute([$user_id]);
$count = $stmt->fetchColumn();

echo json_encode(['count' => (int)$count]);