<?php
/**
 * Admin Protection & Permission Check
 * Include this file at the top of EVERY admin page (after side.php)
 * 
 * Usage: require_once 'admin_protect.php';
 */

// Make sure admin is logged in
if (!isset($_SESSION['admin_id']) || !isset($_SESSION['admin_role'])) {
    setFlash('error', 'Please login to access admin panel!');
    redirect('login.php');
    exit;
}

// Make sure admin account is still active
$conn = getConnection();
$adminCheckStmt = $conn->prepare("SELECT status FROM admins WHERE id = ?");
$adminCheckStmt->bind_param("i", $_SESSION['admin_id']);
$adminCheckStmt->execute();
$adminCheck = $adminCheckStmt->get_result()->fetch_assoc();

if (!$adminCheck || $adminCheck['status'] !== 'active') {
    // Admin is inactive - logout
    session_destroy();
    setFlash('error', 'Your admin account has been deactivated!');
    redirect('login.php');
    exit;
}

/**
 * Enhanced permission check function
 * Super admins bypass all checks automatically
 */
if (!function_exists('hasPermission')) {
    function hasPermission($permission) {
        // Super admins have ALL permissions
        if ($_SESSION['admin_role'] === 'super_admin') {
            return true;
        }
        
        // Check if permission is in session
        if (isset($_SESSION['admin_permissions']) && is_array($_SESSION['admin_permissions'])) {
            return in_array($permission, $_SESSION['admin_permissions']);
        }
        
        // Fallback: Check database
        global $conn;
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM admin_permissions WHERE admin_id = ? AND permission = ?");
        $stmt->bind_param("is", $_SESSION['admin_id'], $permission);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        
        return $result['count'] > 0;
    }
}

/**
 * Require specific permission or redirect
 */
if (!function_exists('requirePermission')) {
    function requirePermission($permission, $redirectTo = 'dashboard.php', $message = null) {
        if (!hasPermission($permission)) {
            if ($message === null) {
                $message = "You do not have permission to access this page!";
            }
            setFlash('error', $message);
            redirect($redirectTo);
            exit;
        }
    }
}

/**
 * Require super admin or redirect
 */
if (!function_exists('requireSuperAdmin')) {
    function requireSuperAdmin($redirectTo = 'dashboard.php') {
        if ($_SESSION['admin_role'] !== 'super_admin') {
            setFlash('error', 'Only super admins can access this page!');
            redirect($redirectTo);
            exit;
        }
    }
}

/**
 * Log admin action for audit trail
 */
if (!function_exists('logAdminAction')) {
    function logAdminAction($action, $details = '', $targetId = null) {
        global $conn;
        
        if (!isset($_SESSION['admin_id'])) {
            return;
        }
        
        $adminId = $_SESSION['admin_id'];
        $ipAddress = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
        
        try {
            // Create admin_logs table if it doesn't exist
            $conn->query("
                CREATE TABLE IF NOT EXISTS admin_logs (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    admin_id INT NOT NULL,
                    action VARCHAR(100) NOT NULL,
                    details TEXT,
                    target_id INT,
                    ip_address VARCHAR(45),
                    user_agent VARCHAR(255),
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    INDEX idx_admin_id (admin_id),
                    INDEX idx_action (action),
                    INDEX idx_created_at (created_at)
                )
            ");
            
            $stmt = $conn->prepare("INSERT INTO admin_logs (admin_id, action, details, target_id, ip_address) VALUES (?, ?, ?, ?, ?)");
            if ($stmt) {
                $stmt->bind_param("issis", $adminId, $action, $details, $targetId, $ipAddress);
                $stmt->execute();
            }
        } catch (Exception $e) {
            // Log failed but don't break the application
            error_log("Admin action logging failed: " . $e->getMessage());
        }
    }
}
if (!function_exists('canDeleteUser')) {
    function canDeleteUser($user) {
        // Super admins can delete anyone
        if (hasPermission('delete_users')) {
            return true;
        }
        
        // Admins with delete_inactive_only can only delete inactive users
        if (hasPermission('delete_inactive_only') && isset($user['status']) && $user['status'] === 'inactive') {
            return true;
        }
        
        return false;
    }
}

// Refresh permissions from database if needed (every 5 minutes)
if (!isset($_SESSION['perms_last_check']) || (time() - $_SESSION['perms_last_check']) > 300) {
    if ($_SESSION['admin_role'] !== 'super_admin') {
        $permStmt = $conn->prepare("SELECT permission FROM admin_permissions WHERE admin_id = ?");
        $permStmt->bind_param("i", $_SESSION['admin_id']);
        $permStmt->execute();
        $permResult = $permStmt->get_result();
        
        $permissions = [];
        while ($perm = $permResult->fetch_assoc()) {
            $permissions[] = $perm['permission'];
        }
        $_SESSION['admin_permissions'] = $permissions;
    }
    $_SESSION['perms_last_check'] = time();
}
?>