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

$response = array('success' => false, 'data' => array());

// Get total users
$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM users");
$row = mysqli_fetch_assoc($result);
$response['data']['total_users'] = number_format($row['total']);

// Get active bots
$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM user_bot_subscriptions WHERE status = 'active'");
$row = mysqli_fetch_assoc($result);
$response['data']['active_bots'] = number_format($row['total']);

// Get today's profit
$today = date('Y-m-d');
$result = mysqli_query($conn, "SELECT SUM(amount) as total FROM transactions WHERE type = 'profit' AND DATE(date) = '$today' AND status = 'completed'");
$row = mysqli_fetch_assoc($result);
$response['data']['today_profit'] = number_format($row['total'] ? $row['total'] : 0, 2);

// Get pending transactions
$result = mysqli_query($conn, "SELECT 
    (SELECT COUNT(*) FROM deposits WHERE status = 'pending') +
    (SELECT COUNT(*) FROM withdrawals WHERE status = 'pending') as total");
$row = mysqli_fetch_assoc($result);
$response['data']['pending_transactions'] = number_format($row['total']);

// Get verified users
$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM users WHERE status = 'verified'");
$row = mysqli_fetch_assoc($result);
$response['data']['verified_users'] = number_format($row['total']);

// Get total deposits
$result = mysqli_query($conn, "SELECT SUM(amount) as total FROM transactions WHERE type = 'deposit' AND status = 'completed'");
$row = mysqli_fetch_assoc($result);
$response['data']['total_deposits'] = number_format($row['total'] ? $row['total'] : 0, 2);

// Get monthly revenue
$month_start = date('Y-m-01');
$month_end = date('Y-m-t');
$result = mysqli_query($conn, "SELECT SUM(amount) as total FROM transactions WHERE type IN ('fee', 'profit') AND DATE(date) BETWEEN '$month_start' AND '$month_end' AND status = 'completed'");
$row = mysqli_fetch_assoc($result);
$response['data']['monthly_revenue'] = number_format($row['total'] ? $row['total'] : 0, 2);

// Get open tickets
$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM support_tickets WHERE status = 'open'");
$row = mysqli_fetch_assoc($result);
$response['data']['open_tickets'] = number_format($row['total']);

// Revenue chart data (last 30 days)
$revenue_data = array('dates' => array(), 'values' => array());
for($i = 29; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $result = mysqli_query($conn, "SELECT SUM(amount) as total FROM transactions WHERE type IN ('fee', 'profit') AND DATE(date) = '$date' AND status = 'completed'");
    $row = mysqli_fetch_assoc($result);
    $revenue_data['dates'][] = date('M j', strtotime($date));
    $revenue_data['values'][] = $row['total'] ? floatval($row['total']) : 0;
}
$response['data']['revenue_chart'] = $revenue_data;

// Bot distribution
$bot_distribution = array('labels' => array(), 'values' => array());
$result = mysqli_query($conn, "
    SELECT bp.plan_name, COUNT(ubs.id) as count
    FROM trading_bot_plans bp
    LEFT JOIN user_bot_subscriptions ubs ON bp.id = ubs.bot_plan_id AND ubs.status = 'active'
    GROUP BY bp.id
    ORDER BY bp.sort_order
");
while($row = mysqli_fetch_assoc($result)) {
    $bot_distribution['labels'][] = $row['plan_name'];
    $bot_distribution['values'][] = intval($row['count']);
}
$response['data']['bot_distribution'] = $bot_distribution;

// Recent activity
$activity_html = '';
$result = mysqli_query($conn, "
    SELECT al.*, u.first_name, u.last_name 
    FROM activity_logs al 
    LEFT JOIN users u ON al.user_id = u.id 
    ORDER BY al.created_at DESC 
    LIMIT 6
");
while($row = mysqli_fetch_assoc($result)) {
    $time = date('H:i', strtotime($row['created_at']));
    $user = $row['first_name'] ? $row['first_name'] . ' ' . $row['last_name'] : 'System';
    $activity_html .= "
    <tr>
        <td class='text-fade'>$time</td>
        <td><span class='text-primary'>$user</span></td>
        <td><span class='badge badge-light'>{$row['action']}</span></td>
        <td class='text-truncate' style='max-width: 200px;' title='{$row['description']}'>{$row['description']}</td>
    </tr>";
}
$response['data']['recent_activity'] = $activity_html;

// Latest transactions
$transactions_html = '';
$result = mysqli_query($conn, "
    SELECT t.*, u.first_name, u.last_name 
    FROM transactions t
    LEFT JOIN users u ON t.user_id = u.id
    ORDER BY t.created_at DESC 
    LIMIT 6
");
while($row = mysqli_fetch_assoc($result)) {
    $badge_class = '';
    if($row['status'] == 'completed') $badge_class = 'badge-success';
    elseif($row['status'] == 'pending') $badge_class = 'badge-warning';
    elseif($row['status'] == 'failed') $badge_class = 'badge-danger';
    else $badge_class = 'badge-info';
    
    $type_class = '';
    if($row['type'] == 'deposit') $type_class = 'text-success';
    elseif($row['type'] == 'withdrawal') $type_class = 'text-danger';
    elseif($row['type'] == 'profit') $type_class = 'text-primary';
    
    $transactions_html .= "
    <tr>
        <td>#{$row['id']}</td>
        <td>{$row['first_name']} {$row['last_name']}</td>
        <td><span class='$type_class'>{$row['type']}</span></td>
        <td>\${$row['amount']}</td>
        <td><span class='badge $badge_class'>{$row['status']}</span></td>
        <td>" . date('Y-m-d H:i', strtotime($row['created_at'])) . "</td>
        <td>
            <button class='btn btn-xs btn-info' onclick='viewTransaction({$row['id']})'>
                <i class='fas fa-eye'></i>
            </button>
        </td>
    </tr>";
}
$response['data']['latest_transactions'] = $transactions_html;

$response['success'] = true;

header('Content-Type: application/json');
echo json_encode($response);
?>