<?php
/**
 * D-Bundles Stores Agent Statistics API
 * Returns JSON data for agent and super agent statistics
 */

session_start();
require_once '../config.php';
require_once '../app/classes/AdminAuth.php';

// Check if admin is authenticated
$adminAuth = new AdminAuth($conn);
if (!$adminAuth->isAuthenticated()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

// Set content type to JSON
header('Content-Type: application/json');

try {
    $today = date('Y-m-d');
    $agent_stats = [];
    
    // Total agents by role
    $result = mysqli_query($conn, "SELECT role, COUNT(*) as count FROM agents GROUP BY role");
    while ($row = mysqli_fetch_assoc($result)) {
        $agent_stats['total_' . $row['role']] = $row['count'];
    }
    
    // Total orders by agent role (from agent_orders table)
    $result = mysqli_query($conn, "
        SELECT a.role, COUNT(ao.id) as total_orders
        FROM agents a
        LEFT JOIN agent_orders ao ON a.id = ao.agent_id
        GROUP BY a.role
    ");
    while ($row = mysqli_fetch_assoc($result)) {
        $agent_stats['total_orders_' . $row['role']] = $row['total_orders'];
    }
    
    // Today's orders by agent role
    $result = mysqli_query($conn, "
        SELECT a.role, COUNT(ao.id) as today_orders
        FROM agents a
        LEFT JOIN agent_orders ao ON a.id = ao.agent_id AND DATE(ao.created_at) = '$today'
        GROUP BY a.role
    ");
    while ($row = mysqli_fetch_assoc($result)) {
        $agent_stats['today_orders_' . $row['role']] = $row['today_orders'];
    }
    
    // Last order timestamp by agent role
    $result = mysqli_query($conn, "
        SELECT a.role, MAX(ao.created_at) as last_order_time
        FROM agents a
        LEFT JOIN agent_orders ao ON a.id = ao.agent_id
        GROUP BY a.role
    ");
    while ($row = mysqli_fetch_assoc($result)) {
        $agent_stats['last_order_' . $row['role']] = $row['last_order_time'];
    }
    
    // Individual agent statistics
    $individual_agent_stats = [];
    $result = mysqli_query($conn, "
        SELECT 
            a.id,
            a.username,
            a.role,
            COUNT(ao.id) as total_orders,
            COUNT(CASE WHEN DATE(ao.created_at) = '$today' THEN 1 END) as today_orders,
            MAX(ao.created_at) as last_order_time,
            SUM(CASE WHEN ao.status = 'delivered' THEN ao.amount ELSE 0 END) as total_revenue
        FROM agents a
        LEFT JOIN agent_orders ao ON a.id = ao.agent_id
        GROUP BY a.id, a.username, a.role
        ORDER BY total_orders DESC
    ");
    while ($row = mysqli_fetch_assoc($result)) {
        $individual_agent_stats[] = $row;
    }
    
    // Calculate last order activity status
    $last_order_time = max(
        $agent_stats['last_order_agent'] ?? '1970-01-01',
        $agent_stats['last_order_super_agent'] ?? '1970-01-01',
        $agent_stats['last_order_dealer'] ?? '1970-01-01'
    );
    
    $last_order_activity = [
        'timestamp' => $last_order_time,
        'formatted' => $last_order_time && $last_order_time !== '1970-01-01' ? date('M j, g:i A', strtotime($last_order_time)) : 'No orders yet',
        'time_ago' => 'No activity'
    ];
    
    if ($last_order_time && $last_order_time !== '1970-01-01') {
        $time_diff = time() - strtotime($last_order_time);
        if ($time_diff < 3600) {
            $last_order_activity['time_ago'] = 'Active now';
        } elseif ($time_diff < 86400) {
            $last_order_activity['time_ago'] = round($time_diff / 3600) . ' hours ago';
        } else {
            $last_order_activity['time_ago'] = round($time_diff / 86400) . ' days ago';
        }
    }
    
    // Return success response
    echo json_encode([
        'success' => true,
        'data' => [
            'agent_stats' => $agent_stats,
            'individual_agent_stats' => $individual_agent_stats,
            'last_order_activity' => $last_order_activity,
            'last_updated' => date('Y-m-d H:i:s')
        ]
    ]);
    
} catch (Exception $e) {
    error_log("Error getting agent statistics: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error retrieving agent statistics',
        'error' => $e->getMessage()
    ]);
}
?>
