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

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

if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Check if the user has sufficient permissions (assuming admin level 8-9 are super admins)
$admin_level = $_SESSION['admin_level'] ?? 0;
if ($admin_level < 8) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

// Pagination parameters
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$offset = ($page - 1) * $limit;

// Search parameter
$search = isset($_GET['search']) ? $_GET['search'] : '';

try {
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Build the query with search
    $whereClause = '';
    $params = [];
    
    if (!empty($search)) {
        $whereClause = "WHERE name LIKE ? OR email LIKE ? OR role LIKE ?";
        $params = ["%$search%", "%$search%", "%$search%"];
    }
    
    // Count total records
    $countQuery = "SELECT COUNT(*) FROM admins $whereClause";
    $stmt = $conn->prepare($countQuery);
    $stmt->execute($params);
    $total = $stmt->fetchColumn();
    
    // Get admins with pagination
    $query = "
        SELECT 
            id, name, email, role, admin_level, last_login, status, 
            photo_url, created_at, updated_at
        FROM admins
        $whereClause
        ORDER BY admin_level DESC, name ASC
        LIMIT ? OFFSET ?
    ";
    
    $stmt = $conn->prepare($query);
    
    foreach ($params as $param) {
        $stmt->bindValue(count($stmt->bindValues()) + 1, $param, PDO::PARAM_STR);
    }
    
    $stmt->bindValue(count($stmt->bindValues()) + 1, $limit, PDO::PARAM_INT);
    $stmt->bindValue(count($stmt->bindValues()) + 1, $offset, PDO::PARAM_INT);
    
    $stmt->execute();
    $admins = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Remove sensitive data from the response
    foreach ($admins as &$admin) {
        unset($admin['password']);
        
        // Add activity status (online within last 15 minutes)
        $lastLogin = strtotime($admin['last_login']);
        $admin['is_online'] = (time() - $lastLogin < 900); // 15 minutes = 900 seconds
    }
    
    echo json_encode([
        'success' => true,
        'admins' => $admins,
        'pagination' => [
            'total' => $total,
            'per_page' => $limit,
            'current_page' => $page,
            'last_page' => ceil($total / $limit)
        ]
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
