<?php
/**
 * Session Helper - Unified Session Check
 * Digunakan untuk validasi session di semua halaman child
 * 
 * Usage: require_once __DIR__ . '/path/to/session_helper.php';
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Define base path dynamically
if (!defined('BASE_PATH')) {
    define('BASE_PATH', '/inventoryACF');
}

/**
 * Check if user is logged in
 * If not, display elegant error page
 */
function checkSession() {
    if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
        displaySessionExpiredPage();
        exit;
    }
}

/**
 * Display session expired page
 */
function displaySessionExpiredPage() {
    $loginUrl = BASE_PATH . '/index.html';
    
    echo '<!DOCTYPE html>
    <html lang="id">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Session Expired</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            body {
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
                display: flex;
                align-items: center;
                justify-content: center;
                min-height: 100vh;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                padding: 20px;
            }
            .error-container {
                background: white;
                padding: 48px 40px;
                border-radius: 20px;
                box-shadow: 0 20px 60px rgba(0,0,0,0.3);
                text-align: center;
                max-width: 440px;
                width: 100%;
                animation: slideIn 0.4s ease-out;
            }
            @keyframes slideIn {
                from {
                    opacity: 0;
                    transform: translateY(-20px);
                }
                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }
            .error-icon {
                font-size: 80px;
                color: #ef4444;
                margin-bottom: 24px;
                animation: pulse 2s infinite;
            }
            @keyframes pulse {
                0%, 100% { transform: scale(1); }
                50% { transform: scale(1.05); }
            }
            h1 {
                font-size: 28px;
                color: #1f2937;
                margin-bottom: 12px;
                font-weight: 700;
            }
            p {
                color: #6b7280;
                margin-bottom: 32px;
                line-height: 1.6;
                font-size: 15px;
            }
            .btn {
                display: inline-block;
                padding: 14px 36px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                text-decoration: none;
                border-radius: 10px;
                font-weight: 600;
                font-size: 15px;
                transition: all 0.3s ease;
                box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
                cursor: pointer;
                border: none;
            }
            .btn:hover {
                transform: translateY(-2px);
                box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
            }
            .btn:active {
                transform: translateY(0);
            }
            .countdown {
                margin-top: 20px;
                color: #9ca3af;
                font-size: 13px;
            }
            .countdown strong {
                color: #667eea;
            }
        </style>
    </head>
    <body>
        <div class="error-container">
            <i class="fas fa-exclamation-triangle error-icon"></i>
            <h1>Sesi Telah Berakhir</h1>
            <p>Sesi Anda telah berakhir karena tidak ada aktivitas atau Anda telah logout dari perangkat lain. Silakan login kembali untuk melanjutkan.</p>
            <button onclick="redirectToLogin()" class="btn">
                <i class="fas fa-sign-in-alt"></i> Login Kembali
            </button>
            <div class="countdown" id="countdown"></div>
        </div>
        
        <script>
            const loginUrl = "' . $loginUrl . '";
            
            // Function to redirect to login
            function redirectToLogin() {
                // Check if we\'re in an iframe
                if (window.top && window.top !== window) {
                    // Redirect parent window
                    window.top.location.href = loginUrl;
                } else {
                    // Redirect current window
                    window.location.href = loginUrl;
                }
            }
            
            // Auto-redirect countdown (optional - can be removed)
            let countdown = 10;
            const countdownElement = document.getElementById("countdown");
            
            function updateCountdown() {
                if (countdown > 0) {
                    countdownElement.innerHTML = `Akan otomatis redirect dalam <strong>${countdown}</strong> detik...`;
                    countdown--;
                    setTimeout(updateCountdown, 1000);
                } else {
                    redirectToLogin();
                }
            }
            
            // Start countdown
            updateCountdown();
        </script>
    </body>
    </html>';
}

/**
 * Validate user role
 * 
 * @param array $allowedRoles - Array of allowed roles (e.g., ['A', 'DH', 'M'])
 * @return bool
 */
function checkRole($allowedRoles = []) {
    if (empty($allowedRoles)) {
        return true;
    }
    
    $userRole = strtoupper(trim($_SESSION['role'] ?? ''));
    
    // Role mapping for normalization
    $roleMap = [
        'A' => 'admin',
        'D' => 'director',
        'DH' => 'dept_head',
        'M' => 'manager',
        'S' => 'staff'
    ];
    
    $normalizedRole = $roleMap[$userRole] ?? strtolower($userRole);
    
    // Check if role is allowed
    foreach ($allowedRoles as $allowed) {
        $allowed = strtoupper(trim($allowed));
        $normalizedAllowed = $roleMap[$allowed] ?? strtolower($allowed);
        
        if ($normalizedRole === $normalizedAllowed) {
            return true;
        }
    }
    
    return false;
}

/**
 * Redirect if role not allowed
 * 
 * @param array $allowedRoles
 * @param string $redirectUrl
 */
function requireRole($allowedRoles, $redirectUrl = null) {
    if (!checkRole($allowedRoles)) {
        if ($redirectUrl === null) {
            $redirectUrl = BASE_PATH . '/dashboard.php';
        }
        
        // Use JavaScript redirect for iframe compatibility
        echo "<script>";
        echo "if (parent && parent.document.getElementById('contentFrame')) {";
        echo "    parent.location.href = '{$redirectUrl}';";
        echo "} else {";
        echo "    window.location.href = '{$redirectUrl}';";
        echo "}";
        echo "</script>";
        exit;
    }
}

/**
 * Generate CSRF Token
 * 
 * @return string
 */
function generateCsrfToken() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

/**
 * Validate CSRF Token
 * 
 * @param string $token
 * @return bool
 */
function validateCsrfToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// Auto-check session when this file is included
checkSession();