<?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'] ?? '');
$typeFilter = trim($_GET['type'] ?? '');
$roleFilter = trim($_GET['role'] ?? '');
$sortBy = trim($_GET['sort'] ?? 'id_desc');

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

// Build WHERE clause
$whereConditions = [];
$params = [];
$paramTypes = '';

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

if (!empty($typeFilter)) {
    if ($typeFilter === 'store_owner') {
        $whereConditions[] = "a.is_store_owner = 1";
    } elseif ($typeFilter === 'sub_agent') {
        $whereConditions[] = "a.is_store_owner = 0";
    }
    // No params needed for this filter
}

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

// Build ORDER BY clause
$orderBy = 'ORDER BY ';
switch ($sortBy) {
    case 'id_asc':
        $orderBy .= 'a.id ASC';
        break;
    case 'username_asc':
        $orderBy .= 'a.username ASC';
        break;
    case 'username_desc':
        $orderBy .= 'a.username DESC';
        break;
    case 'balance_asc':
        $orderBy .= 'a.balance ASC';
        break;
    case 'balance_desc':
        $orderBy .= 'a.balance DESC';
        break;
    case 'id_desc':
    default:
        $orderBy .= 'a.id DESC';
        break;
}

try {
    // Get total count
    $countSql = "SELECT COUNT(*) as total FROM agents a $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 agents for current page with store owner information
    $sql = "SELECT a.*, 
            COALESCE(s.store_name, 'N/A') as store_name,
            CASE 
                WHEN a.is_store_owner = 1 THEN 'Store Owner'
                ELSE 'Sub-Agent'
            END as user_type
            FROM agents a
            LEFT JOIN stores s ON a.id = s.owner_id AND a.is_store_owner = 1
            $whereClause $orderBy LIMIT ? OFFSET ?";
    $params[] = $limit;
    $params[] = $offset;
    $paramTypes .= 'ii';

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

    $agents = [];
    while ($agent = $result->fetch_assoc()) {
        $agents[] = $agent;
    }
    $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 agents error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching agents: ' . $e->getMessage()
    ]);
}
?>
