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

// Get filter parameters
$filter_type = isset($_GET['type']) ? $_GET['type'] : '';
$filter_status = isset($_GET['status']) ? $_GET['status'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$search = isset($_GET['search']) ? $_GET['search'] : '';

// Build stats query
$stats_sql = "SELECT 
                COUNT(*) as total_count,
                SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END) as completed_amount,
                SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END) as pending_amount,
                SUM(CASE WHEN type = 'profit' AND status = 'completed' THEN amount ELSE 0 END) as total_profit
              FROM transactions WHERE 1=1";

// Apply filters
if ($filter_type) {
    $stats_sql .= " AND type = '$filter_type'";
}

if ($filter_status) {
    $stats_sql .= " AND status = '$filter_status'";
}

if ($date_from) {
    $stats_sql .= " AND DATE(date) >= '$date_from'";
}

if ($date_to) {
    $stats_sql .= " AND DATE(date) <= '$date_to'";
}

if ($search) {
    $stats_sql .= " AND (user_id IN (SELECT id FROM users WHERE username LIKE '%$search%' OR email LIKE '%$search%') OR description LIKE '%$search%' OR reference_id LIKE '%$search%')";
}

$stats_result = mysqli_query($conn, $stats_sql);
$stats = mysqli_fetch_assoc($stats_result);

echo json_encode(array(
    'success' => true,
    'total_count' => $stats['total_count'] ?: 0,
    'completed_amount' => $stats['completed_amount'] ?: 0,
    'pending_amount' => $stats['pending_amount'] ?: 0,
    'total_profit' => $stats['total_profit'] ?: 0
));
?>