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

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

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

$db = db();
$admin_id = $_SESSION['admin_id'];

// Get admin info for agent check
$stmt = $db->prepare("SELECT is_agent FROM admins WHERE id = ?");
$stmt->execute([$admin_id]);
$admin = $stmt->fetch();

$action = $_GET['action'] ?? '';
if ($action === 'clear') {
    $type = $_GET['type'] ?? '';
    if ($type) {
        $_SESSION['admin_cleared_' . $type] = time();
    }
    echo json_encode(['success' => true]);
    exit;
}

$pending_recharge = 0;
$pending_withdrawal = 0;
$pending_kyc = 0;
$active_binary = 0;
$active_spot = 0;
$active_contract = 0;
$new_messages = 0;
$new_registrations = 0;

function getCount($db, $sql, $params) {
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    return (int)$stmt->fetchColumn();
}

if ($admin['is_agent']) {
    $agent_id = $admin_id;
    $pending_recharge = getCount($db, "SELECT COUNT(*) FROM finance_requests r JOIN users u ON r.user_id = u.id WHERE r.type = 'recharge' AND r.status IN ('0', 'pending', 'matched', '1', 'account_sent', '2', 'finished') AND u.agent_id = ?", [$agent_id]);
    $pending_withdrawal = getCount($db, "SELECT COUNT(*) FROM finance_requests r JOIN users u ON r.user_id = u.id WHERE r.type = 'withdrawal' AND r.status IN ('0', 'pending', '1', '2') AND u.agent_id = ?", [$agent_id]);
    $pending_kyc = getCount($db, "SELECT COUNT(*) FROM users WHERE kyc_status = 1 AND agent_id = ?", [$agent_id]);
    $active_binary = getCount($db, "SELECT COUNT(*) FROM binary_orders o JOIN users u ON o.user_id = u.id WHERE o.status = 'pending' AND u.agent_id = ?", [$agent_id]);
    $active_spot = getCount($db, "SELECT COUNT(*) FROM spot_orders o JOIN users u ON o.user_id = u.id WHERE o.status = 0 AND u.agent_id = ?", [$agent_id]);
    $active_contract = getCount($db, "SELECT COUNT(*) FROM contract_orders o JOIN users u ON o.user_id = u.id WHERE o.status = 'open' AND u.agent_id = ?", [$agent_id]);
    $new_messages = getCount($db, "SELECT COUNT(*) FROM messages m JOIN users u ON m.user_id = u.id WHERE m.sender = 'user' AND m.is_read = 0 AND u.agent_id = ?", [$agent_id]);
    $new_registrations = getCount($db, "SELECT COUNT(*) FROM users WHERE agent_id = ? AND created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)", [$agent_id]);
} else {
    $pending_recharge = getCount($db, "SELECT COUNT(*) FROM finance_requests WHERE type = 'recharge' AND status IN ('0', 'pending', 'matched', '1', 'account_sent', '2', 'finished')", []);
    $pending_withdrawal = getCount($db, "SELECT COUNT(*) FROM finance_requests WHERE type = 'withdrawal' AND status IN ('0', 'pending', '1', '2')", []);
    $pending_kyc = getCount($db, "SELECT COUNT(*) FROM users WHERE kyc_status = 1", []);
    $active_binary = getCount($db, "SELECT COUNT(*) FROM binary_orders WHERE status = 'pending'", []);
    $active_spot = getCount($db, "SELECT COUNT(*) FROM spot_orders WHERE status = 0", []);
    $active_contract = getCount($db, "SELECT COUNT(*) FROM contract_orders WHERE status = 'open'", []);
    $new_messages = getCount($db, "SELECT COUNT(*) FROM messages WHERE sender = 'user' AND is_read = 0", []);
    $new_registrations = getCount($db, "SELECT COUNT(*) FROM users WHERE created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)", []);
}

$total = $pending_recharge + $pending_withdrawal + $pending_kyc + $active_binary + $active_spot + $active_contract + $new_messages;
$sound_trigger_count = $total; // Trigger sound for any pending action

// Add dashboard stats if requested
$stats = [];
if (isset($_GET['stats'])) {
    $stats['total_users'] = getCount($db, "SELECT COUNT(*) FROM users", []);
    $stats['total_recharge'] = (float)getCount($db, "SELECT SUM(amount) FROM finance_requests WHERE type='recharge' AND status IN ('3', 'completed')", []) ?: 0;
    $stats['total_withdrawal'] = (float)getCount($db, "SELECT SUM(amount) FROM finance_requests WHERE type='withdrawal' AND status IN ('3', 'completed')", []) ?: 0;
    $stats['pending_tasks'] = $pending_recharge + $pending_withdrawal + $pending_kyc;
}

echo json_encode([
    'success' => true,
    'counts' => [
        'recharge' => $pending_recharge,
        'withdrawal' => $pending_withdrawal,
        'kyc' => $pending_kyc,
        'binary' => $active_binary,
        'spot' => $active_spot,
        'contract' => $active_contract,
        'messages' => $new_messages,
        'users' => $new_registrations,
        'total' => $total,
        'sound_total' => $sound_trigger_count
    ],
    'stats' => $stats
]);
