<?php
/**
 * NIS Asset Management System
 * Front Controller - Handles ALL requests
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/logs/php_errors.log');


// Define base path
define('BASE_PATH', __DIR__);
define('APP_START', microtime(true));

// Simple autoloader for core classes
spl_autoload_register(function ($class) {
    // Core classes
    $coreFile = BASE_PATH . '/core/' . $class . '.php';
    if (file_exists($coreFile)) {
        require_once $coreFile;
        return true;
    }
    
    // Controllers
    $controllerFile = BASE_PATH . '/controllers/' . $class . '.php';
    if (file_exists($controllerFile)) {
        require_once $controllerFile;
        return true;
    }
    
    // Models
    $modelFile = BASE_PATH . '/models/' . $class . '.php';
    if (file_exists($modelFile)) {
        require_once $modelFile;
        return true;
    }
    
    return false;
});

// Include configuration
require_once BASE_PATH . '/config/config.php';

// Initialize session
initSession();

// Get the requested URL
$request = $_SERVER['REQUEST_URI'];
$base = '/nis_ams';

// Remove base path from request
if (strpos($request, $base) === 0) {
    $request = substr($request, strlen($base));
}

// Remove query string
if (strpos($request, '?') !== false) {
    $request = substr($request, 0, strpos($request, '?'));
}

// Clean up request
$request = trim($request, '/');

// If this is the login page (no specific route)
if ($request === '' || $request === 'index.php') {
    // Redirect to dashboard if already logged in
    if (isLoggedIn()) {
        header('Location: ' . BASE_URL . '/dashboard');
        exit;
    }
    
    // Show login page
    showLoginPage();
    exit;
}

// For all other routes, load the router
require_once BASE_PATH . '/core/Router.php';
require_once BASE_PATH . '/config/routes.php';

// Dispatch the request
Router::dispatch($_SERVER['REQUEST_URI']);
exit;



/**
 * Show login page
 */
function showLoginPage() {
    // Get error/success messages
    $error = isset($_GET['error']) ? $_GET['error'] : '';
    $success = isset($_GET['success']) ? $_GET['success'] : '';
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Login | NIS Asset Management System</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }

            :root {
                --primary-color: #2c3e50;
                --primary-light: #27ae60;
                --secondary-color: #27ae60;
            }

            body {
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-light) 100%);
                min-height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .login-page {
                width: 100%;
                min-height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
                padding: 15px;
                background: url('assets/images/tech_building.png') center/cover no-repeat fixed;
                position: relative;
            }
            
            .login-page::before {
                content: '';
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.4);
                backdrop-filter: blur(3px);
            }
            
            .login-container {
                width: 100%;
                max-width: 380px;
                padding: 2rem;
                background: rgba(255, 255, 255, 0.98);
                border-radius: 12px;
                box-shadow: 0 15px 35px rgba(0,0,0,0.3);
                position: relative;
                z-index: 2;
                border: 1px solid rgba(255, 255, 255, 0.3);
                animation: slideIn 0.5s ease-out;
            }

            @keyframes slideIn {
                from {
                    transform: translateY(-20px);
                    opacity: 0;
                }
                to {
                    transform: translateY(0);
                    opacity: 1;
                }
            }
            
            .login-container::before {
                content: '';
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 4px;
                background: linear-gradient(90deg, var(--primary-color), var(--primary-light));
            }
            
            .login-header {
                text-align: center;
                margin-bottom: 1.5rem;
            }
            
            .logo-img {
                max-width: 60px;
                height: auto;
                margin-bottom: 0.5rem;
            }
            
            .login-header h2 {
                color: var(--primary-color);
                font-size: 1.3rem;
                font-weight: 600;
                margin-bottom: 0.25rem;
            }
            
            .login-header h3 {
                color: var(--primary-light);
                font-size: 1rem;
                font-weight: 500;
            }
            
            .login-header p {
                color: #666;
                font-size: 0.8rem;
                margin-top: 0.25rem;
            }
            
            .form-group {
                margin-bottom: 1.25rem;
            }
            
            .form-group label {
                display: block;
                margin-bottom: 0.4rem;
                font-weight: 500;
                color: #444;
                font-size: 0.9rem;
                display: flex;
                align-items: center;
                gap: 6px;
            }
            
            .input-with-icon {
                position: relative;
                display: flex;
                align-items: center;
            }
            
            .input-with-icon i {
                position: absolute;
                left: 12px;
                color: #777;
                font-size: 0.9rem;
                z-index: 1;
            }
            
            .input-with-icon input {
                width: 100%;
                padding: 0.7rem 0.7rem 0.7rem 38px;
                border: 1px solid #ddd;
                border-radius: 6px;
                font-size: 0.9rem;
                transition: all 0.3s;
                background: rgba(255, 255, 255, 0.9);
            }
            
            .input-with-icon input:focus {
                border-color: var(--primary-light);
                outline: none;
                box-shadow: 0 0 0 2px rgba(39, 174, 96, 0.1);
                background: white;
            }
            
            .btn-login {
                width: 100%;
                padding: 0.7rem;
                background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-light) 100%);
                color: white;
                border: none;
                border-radius: 6px;
                font-size: 0.95rem;
                cursor: pointer;
                transition: all 0.3s;
                font-weight: 600;
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 8px;
                margin-top: 0.5rem;
            }
            
            .btn-login:hover {
                transform: translateY(-2px);
                box-shadow: 0 5px 15px rgba(39, 174, 96, 0.3);
            }
            
            .alert {
                padding: 0.6rem 0.8rem;
                margin-bottom: 1.25rem;
                border-radius: 6px;
                font-size: 0.85rem;
                display: flex;
                align-items: center;
                gap: 8px;
            }
            
            .alert-error {
                background-color: #f8d7da;
                color: #721c24;
                border: 1px solid #f5c6cb;
            }
            
            .alert-success {
                background-color: #d4edda;
                color: #155724;
                border: 1px solid #c3e6cb;
            }
            
            .system-info {
                text-align: center;
                margin-top: 1rem;
                padding-top: 0.8rem;
                border-top: 1px solid #eee;
                color: #777;
                font-size: 0.8rem;
            }
            
            .system-info i {
                color: var(--primary-light);
                margin-right: 4px;
            }
            
            @media (max-width: 480px) {
                .login-container {
                    padding: 1.5rem;
                    max-width: 320px;
                }
                
                .login-header h2 {
                    font-size: 1.1rem;
                }
                
                .login-header h3 {
                    font-size: 0.9rem;
                }
                
                .btn-login {
                    padding: 0.6rem;
                    font-size: 0.9rem;
                }
            }
        </style>
    </head>
    <body>
        <div class="login-page">
            <div class="login-container">
                <div class="login-header">
                    <img src="assets/images/nis-logo-white.png" alt="NIS Logo" class="logo-img" onerror="this.style.display='none'">
                    <h2>Nigeria Immigration Service</h2>
                    <h3>Asset Management System</h3>
                    <p>Works & Logistics Directorate</p>
                </div>
                
                <?php if ($error): ?>
                    <div class="alert alert-error">
                        <i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error); ?>
                    </div>
                <?php endif; ?>
                
                <?php if ($success): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success); ?>
                    </div>
                <?php endif; ?>
                
                <form action="login_process.php" method="POST">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                    
                    <div class="form-group">
                        <label for="username">
                            <i class="fas fa-user"></i> Username / Email
                        </label>
                        <div class="input-with-icon">
                            <i class="fas fa-user"></i>
                            <input type="text" id="username" name="username" required placeholder="Enter username">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="password">
                            <i class="fas fa-lock"></i> Password
                        </label>
                        <div class="input-with-icon">
                            <i class="fas fa-lock"></i>
                            <input type="password" id="password" name="password" required placeholder="Enter password">
                        </div>
                    </div>
                    
                    <button type="submit" class="btn-login">
                        <i class="fas fa-sign-in-alt"></i> Login
                    </button>
                </form>
                
                <div class="system-info">
                    <p style="margin-top: 0.25rem;">&copy; <?php echo date('Y'); ?> Nigeria Immigration Service</p>
                </div>
            </div>
        </div>

        <script>
            document.querySelector('form').addEventListener('submit', function(e) {
                const username = document.getElementById('username').value.trim();
                const password = document.getElementById('password').value.trim();
                
                if (!username || !password) {
                    e.preventDefault();
                    alert('Please fill in all required fields');
                    return false;
                }
            });
            
            const inputs = document.querySelectorAll('input');
            inputs.forEach(input => {
                input.addEventListener('focus', function() {
                    this.parentElement.style.transform = 'scale(1.01)';
                });
                
                input.addEventListener('blur', function() {
                    this.parentElement.style.transform = 'scale(1)';
                });
            });
            
            window.addEventListener('load', function() {
                const loginPage = document.querySelector('.login-page');
                const bgImage = new Image();
                bgImage.src = 'assets/images/tech_building.png';
                bgImage.onerror = function() {
                    loginPage.style.background = 'linear-gradient(135deg, var(--primary-color) 0%, var(--primary-light) 100%)';
                };
            });
            
            document.querySelector('form').addEventListener('submit', function() {
                const btn = document.querySelector('.btn-login');
                btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Logging in...';
                btn.disabled = true;
            });
        </script>
    </body>
    </html>
    <?php
}
?>