<?php

function validateAdminToken($token) {
    try {
        // First, validate the token format and signature
        $payload = validateToken($token);
        
        if (!$payload) {
            return false;
        }

        // Check if the user has admin role
        if (!isset($payload->role) || $payload->role !== 'admin') {
            return false;
        }

        return $payload;
    } catch (Exception $e) {
        return false;
    }
}

function ensureAdminAccess($token) {
    $payload = validateAdminToken($token);
    
    if (!$payload) {
        http_response_code(403);
        echo json_encode(['error' => 'Unauthorized access']);
        exit;
    }
    
    return $payload;
}

function logAdminAction($conn, $adminId, $action, $details = null) {
    try {
        $stmt = $conn->prepare("
            INSERT INTO admin_logs (admin_id, action, details)
            VALUES (?, ?, ?)
        ");
        
        $jsonDetails = $details ? json_encode($details) : null;
        $stmt->bind_param("sss", $adminId, $action, $jsonDetails);
        $stmt->execute();
        
        return true;
    } catch (Exception $e) {
        error_log("Failed to log admin action: " . $e->getMessage());
        return false;
    }
}

function sendNotification($conn, $userId, $title, $message, $type = 'system') {
    try {
        $stmt = $conn->prepare("
            INSERT INTO notifications (user_id, title, message, type)
            VALUES (?, ?, ?, ?)
        ");
        
        $stmt->bind_param("ssss", $userId, $title, $message, $type);
        return $stmt->execute();
    } catch (Exception $e) {
        error_log("Failed to send notification: " . $e->getMessage());
        return false;
    }
}

?>