<?php
require_once '../../config/database.php';
require_once '../../config/auth_enhanced.php';

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

// Check authentication
if (!isAuthenticated()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

try {
    $database = new Database();
    $conn = $database->getConnection();
    
    // Get filter parameters
    $status = isset($_GET['status']) ? $_GET['status'] : 'active';
    $role = isset($_GET['role']) ? $_GET['role'] : '';
    
    // Build the query
    $query = "SELECT id, kso_id, first_name, last_name, email, role, status, last_login FROM admins WHERE 1=1";
    $params = [];
    
    // Add status filter
    if (!empty($status)) {
        $query .= " AND status = ?";
        $params[] = $status;
    }
    
    // Add role filter
    if (!empty($role)) {
        $query .= " AND role = ?";
        $params[] = $role;
    }
    
    // Order by role level (higher level first) and then by first_name
    $query .= " ORDER BY CASE role
                WHEN 'President' THEN 1
                WHEN 'Vice President' THEN 2
                WHEN 'General Secretary' THEN 3
                WHEN 'Finance Secretary' THEN 4
                WHEN 'Assistant General Secretary' THEN 5
                ELSE 6
                END, first_name ASC";
    
    // Prepare and execute the query
    $stmt = $conn->prepare($query);
    
    if (!empty($params)) {
        $stmt->execute($params);
    } else {
        $stmt->execute();
    }
    
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $results,
        'message' => 'Admins fetched successfully'
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
