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

$adminAuth = new AdminAuth($conn);

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

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

// Get parameters
$page = intval($_GET['page'] ?? 1);
$limit = intval($_GET['limit'] ?? 10);
$search = trim($_GET['search'] ?? '');

// Validate parameters
if ($page < 1) $page = 1;
if ($limit < 1 || $limit > 100) $limit = 10;

// Get today's date for filtering
$today = date('Y-m-d');

try {
    // Build WHERE clause for search
    $whereConditions = [];
    $params = [];
    $paramTypes = '';

    if (!empty($search)) {
        $whereConditions[] = "a.username LIKE ?";
        $searchParam = "%$search%";
        $params[] = $searchParam;
        $paramTypes .= 's';
    }

    $whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';

    // Get total count
    $countSql = "
        SELECT COUNT(DISTINCT a.id) as total 
        FROM agents a
        LEFT JOIN agent_orders ao ON a.id = ao.agent_id
        $whereClause
    ";
    $countStmt = $conn->prepare($countSql);
    if (!empty($params)) {
        $countStmt->bind_param($paramTypes, ...$params);
    }
    $countStmt->execute();
    $totalCount = $countStmt->get_result()->fetch_assoc()['total'];
    $countStmt->close();

    // Calculate pagination
    $totalPages = ceil($totalCount / $limit);
    $offset = ($page - 1) * $limit;

    // Get agent performance data for current page
    $sql = "
        SELECT 
            a.id,
            a.username,
            a.role,
            COUNT(ao.id) as total_orders,
            COUNT(CASE WHEN DATE(ao.created_at) = ? 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
        $whereClause
        GROUP BY a.id, a.username, a.role
        ORDER BY total_orders DESC
        LIMIT ? OFFSET ?
    ";

    // Add today parameter and pagination parameters
    $params[] = $today;
    $params[] = $limit;
    $params[] = $offset;
    $paramTypes .= 'sii';

    $stmt = $conn->prepare($sql);
    $stmt->bind_param($paramTypes, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();

    $agents = [];
    while ($agent = $result->fetch_assoc()) {
        // Format the data for frontend
        $agents[] = [
            'id' => $agent['id'],
            'username' => $agent['username'],
            'role' => $agent['role'],
            'total_orders' => intval($agent['total_orders']),
            'today_orders' => intval($agent['today_orders']),
            'last_order_time' => $agent['last_order_time'],
            'total_revenue' => floatval($agent['total_revenue'])
        ];
    }
    $stmt->close();

    // Calculate showing range
    $showingStart = $totalCount > 0 ? $offset + 1 : 0;
    $showingEnd = min($offset + $limit, $totalCount);

    echo json_encode([
        'success' => true,
        'data' => [
            'agents' => $agents,
            'pagination' => [
                'current_page' => $page,
                'total_pages' => $totalPages,
                'total_count' => $totalCount,
                'limit' => $limit,
                'showing_start' => $showingStart,
                'showing_end' => $showingEnd
            ]
        ]
    ]);

} catch (Exception $e) {
    error_log("Get agent performance error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching agent performance: ' . $e->getMessage()
    ]);
}
?>
