<?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
$admin_level = $_SESSION['admin_level'] ?? 0;
if ($admin_level < 8) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

// Get admin ID from request
$admin_id = $_GET['id'] ?? '';

if (empty($admin_id)) {
    echo json_encode(['success' => false, 'message' => 'Admin ID is required']);
    exit();
}

try {
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Get admin details
    $stmt = $conn->prepare("
        SELECT 
            id, name, email, role, admin_level, last_login, status, 
            photo_url, created_at, updated_at
        FROM admins
        WHERE id = ?
    ");
    $stmt->execute([$admin_id]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$admin) {
        echo json_encode(['success' => false, 'message' => 'Admin not found']);
        exit();
    }
    
    // Get admin permissions
    $stmt = $conn->prepare("
        SELECT permission_key, is_granted
        FROM admin_permissions
        WHERE admin_id = ?
    ");
    $stmt->execute([$admin_id]);
    $permissionsData = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format permissions
    $permissions = [];
    foreach ($permissionsData as $perm) {
        $permissions[$perm['permission_key']] = (bool)$perm['is_granted'];
    }
    
    // Get recent activity
    $stmt = $conn->prepare("
        SELECT action, details, created_at
        FROM admin_logs
        WHERE admin_id = ?
        ORDER BY created_at DESC
        LIMIT 10
    ");
    $stmt->execute([$admin_id]);
    $activity = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Add additional data to the response
    $admin['permissions'] = $permissions;
    $admin['recent_activity'] = $activity;
    
    // Calculate account age and last active time
    $createdDate = new DateTime($admin['created_at']);
    $now = new DateTime();
    $accountAge = $createdDate->diff($now);
    
    $lastLogin = new DateTime($admin['last_login'] ?? $admin['created_at']);
    $lastActive = $lastLogin->diff($now);
    
    $admin['account_age'] = [
        'years' => $accountAge->y,
        'months' => $accountAge->m,
        'days' => $accountAge->d,
    ];
    
    $admin['last_active'] = [
        'days' => $lastActive->d,
        'hours' => $lastActive->h,
        'minutes' => $lastActive->i,
    ];
    
    echo json_encode([
        'success' => true,
        'admin' => $admin
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
