<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Login Page - FIXED REDIRECT VERSION
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging (remove in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Define base path if not defined
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(__DIR__));
}

// Load core files with error checking
$required_files = [
    '/config/config.php',
    '/config/database.php',
    '/config/auth.php'
];

foreach ($required_files as $file) {
    $full_path = BASE_PATH . $file;
    if (file_exists($full_path)) {
        require_once $full_path;
    } else {
        die("Critical error: Required file not found: " . $full_path);
    }
}

// Check if constants.php exists (optional)
if (file_exists(BASE_PATH . '/config/constants.php')) {
    require_once BASE_PATH . '/config/constants.php';
}

// Check if helpers.php exists (optional)
if (file_exists(BASE_PATH . '/config/helpers.php')) {
    require_once BASE_PATH . '/config/helpers.php';
}

// Check if csrf.php exists (optional)
if (file_exists(BASE_PATH . '/config/csrf.php')) {
    require_once BASE_PATH . '/config/csrf.php';
}

// Ensure session is started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Determine the correct base URL for redirects
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$script_name = $_SERVER['SCRIPT_NAME'] ?? '';
$current_dir = dirname($script_name);

// Check if we're in public directory
$in_public = (strpos($current_dir, '/public') !== false);

// Define the correct dashboard path
if ($in_public) {
    $dashboard_path = 'dashboard.php';
    $login_path = 'login.php';
} else {
    $dashboard_path = 'public/dashboard.php';
    $login_path = 'public/login.php';
}

// Redirect if already logged in
if (function_exists('is_logged_in') && is_logged_in()) {
    header('Location: ' . $dashboard_path);
    exit;
}

// Handle login form submission
$error = '';
$username = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token if function exists
    $csrf_valid = true;
    if (function_exists('verify_csrf_token')) {
        $token = $_POST[defined('CSRF_TOKEN_NAME') ? CSRF_TOKEN_NAME : 'csrf_token'] ?? '';
        if (!verify_csrf_token($token)) {
            $csrf_valid = false;
            $error = 'Invalid security token. Please try again.';
        }
    }
    
    if ($csrf_valid) {
        $username = isset($_POST['username']) ? trim($_POST['username']) : '';
        $password = $_POST['password'] ?? '';
        $remember = isset($_POST['remember']);
        
        if (empty($username) || empty($password)) {
            $error = 'Please enter both username and password';
        } else {
            // Sanitize username if function exists
            if (function_exists('sanitize_input')) {
                $username = sanitize_input($username);
            }
            
            if (function_exists('authenticate_user')) {
                $result = authenticate_user($username, $password, $remember);
                
                if (is_array($result) && isset($result['error'])) {
                    switch ($result['error']) {
                        case 'too_many_attempts':
                            $error = 'Too many failed login attempts. Please try again in 15 minutes.';
                            break;
                        case 'invalid_credentials':
                            $error = 'Invalid username or password';
                            break;
                        default:
                            $error = 'Login failed. Please try again.';
                    }
                    
                    // Log the error
                    if (function_exists('log_message')) {
                        log_message("Login failed for user: $username - " . $result['error'], 'WARNING');
                    }
                } else {
                    // SUCCESS! User is logged in
                    
                    // Log successful login
                    if (function_exists('log_message')) {
                        log_message("Successful login for user: " . ($result['username'] ?? $username), 'INFO');
                    }
                    
                    // Set flash message if function exists
                    if (function_exists('set_flash_message')) {
                        set_flash_message('success', 'Welcome back, ' . ($result['first_name'] ?? $username) . '!');
                    }
                    
                    // Determine redirect URL
                    $redirect = isset($_GET['redirect']) && !empty($_GET['redirect']) ? $_GET['redirect'] : '';
                    
                    if (empty($redirect)) {
                        $redirect = $dashboard_path;
                    } else {
                        // Make sure redirect path doesn't have duplicate public
                        if (strpos($redirect, 'public/') === 0 && !$in_public) {
                            // Keep as is
                        } elseif (strpos($redirect, 'public/') !== 0 && $in_public) {
                            // Remove public/ from path if we're already in public
                            $redirect = str_replace('public/', '', $redirect);
                        }
                    }
                    
                    // Perform redirect
                    header('Location: ' . $redirect);
                    exit;
                }
            } else {
                $error = 'Authentication system not available. Please contact administrator.';
                error_log("CRITICAL: authenticate_user() function not found");
            }
        }
    }
}

// Get remaining attempts for display
$remaining_attempts = defined('MAX_LOGIN_ATTEMPTS') ? MAX_LOGIN_ATTEMPTS : 5;
if (function_exists('get_remaining_login_attempts') && !empty($username)) {
    $remaining_attempts = get_remaining_login_attempts($username);
}
$show_captcha = $remaining_attempts <= 2;

// Set page title
$page_title = 'Login';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login | <?php echo defined('APP_NAME') ? APP_NAME : 'Ruhondo Beach Resort'; ?></title>
    
    <!-- CSRF Meta Tags -->
    <?php if (function_exists('csrf_meta_tags')) echo csrf_meta_tags(); ?>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome 6 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Custom CSS -->
    <?php if (function_exists('assets_url')): ?>
    <link rel="stylesheet" href="<?php echo assets_url('css/style.css'); ?>?v=<?php echo defined('APP_VERSION') ? APP_VERSION : '1.0'; ?>">
    <?php endif; ?>
    
    <style>
        :root {
            --primary-color: #007bff;
            --success-color: #28a745;
            --danger-color: #dc3545;
        }
        
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            margin: 0;
            padding: 20px;
        }
        
        .login-container {
            width: 100%;
            max-width: 450px;
            animation: fadeIn 0.5s ease;
        }
        
        .login-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
            overflow: hidden;
            transition: transform 0.3s ease;
        }
        
        .login-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
        }
        
        .login-header {
            background: linear-gradient(135deg, var(--primary-color), #0056b3);
            color: white;
            padding: 2rem;
            text-align: center;
        }
        
        .login-header h1 {
            margin: 0;
            font-size: 2rem;
            font-weight: 600;
        }
        
        .login-header p {
            margin: 0.5rem 0 0;
            opacity: 0.9;
            font-size: 0.9rem;
        }
        
        .login-body {
            padding: 2rem;
        }
        
        .resort-logo {
            width: 100px;
            height: 100px;
            background: white;
            border-radius: 50%;
            margin: -70px auto 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        
        .resort-logo img {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
            position: relative;
        }
        
        .form-group i {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--primary-color);
            font-size: 1.1rem;
            z-index: 10;
        }
        
        .toggle-password {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #6c757d;
            z-index: 20;
        }
        
        .toggle-password:hover {
            color: var(--primary-color);
        }
        
        .form-control {
            padding: 0.75rem 1rem 0.75rem 2.5rem;
            border: 2px solid #e0e0e0;
            border-radius: 50px;
            font-size: 1rem;
            transition: all 0.3s ease;
            height: auto;
            width: 100%;
        }
        
        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
            outline: none;
        }
        
        .form-control.is-invalid {
            border-color: var(--danger-color);
        }
        
        .invalid-feedback {
            display: block;
            margin-top: 0.5rem;
            padding-left: 1rem;
            color: var(--danger-color);
            font-size: 0.875rem;
        }
        
        .btn-login {
            background: linear-gradient(135deg, var(--primary-color), #0056b3);
            border: none;
            border-radius: 50px;
            padding: 0.75rem;
            font-size: 1.1rem;
            font-weight: 600;
            color: white;
            width: 100%;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .btn-login:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 123, 255, 0.4);
        }
        
        .btn-login:disabled {
            opacity: 0.7;
            cursor: not-allowed;
        }
        
        .btn-login .spinner-border {
            width: 1.2rem;
            height: 1.2rem;
            margin-right: 0.5rem;
        }
        
        .remember-forgot {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            font-size: 0.9rem;
        }
        
        .remember-me {
            display: flex;
            align-items: center;
        }
        
        .remember-me input {
            margin-right: 0.5rem;
        }
        
        .forgot-password {
            color: var(--primary-color);
            text-decoration: none;
            transition: color 0.3s ease;
        }
        
        .forgot-password:hover {
            color: #0056b3;
            text-decoration: underline;
        }
        
        .alert {
            border-radius: 50px;
            padding: 0.75rem 1.5rem;
            margin-bottom: 1.5rem;
            border: none;
            animation: slideIn 0.3s ease;
        }
        
        .alert-danger {
            background: #f8d7da;
            color: #721c24;
        }
        
        .alert-warning {
            background: #fff3cd;
            color: #856404;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
        }
        
        .alert-info {
            background: #d1ecf1;
            color: #0c5460;
        }
        
        .attempts-warning {
            margin-top: 1rem;
            text-align: center;
            font-size: 0.85rem;
        }
        
        .login-footer {
            margin-top: 2rem;
            text-align: center;
            color: white;
            font-size: 0.9rem;
        }
        
        .login-footer a {
            color: white;
            text-decoration: none;
            font-weight: 600;
        }
        
        .login-footer a:hover {
            text-decoration: underline;
        }
        
        .captcha-container {
            margin-bottom: 1.5rem;
        }
        
        .developer-credit {
            margin-top: 2rem;
            font-size: 0.85rem;
            color: rgba(255,255,255,0.7);
        }
        
        .demo-credentials {
            margin-top: 1.5rem;
            padding-top: 1.5rem;
            border-top: 1px solid #dee2e6;
        }
        
        .demo-login-btn {
            transition: all 0.2s ease;
            margin-bottom: 0.5rem;
        }
        
        .demo-login-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateX(-20px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }
        
        @media (max-width: 480px) {
            body {
                padding: 10px;
            }
            
            .login-header {
                padding: 1.5rem;
            }
            
            .login-header h1 {
                font-size: 1.5rem;
            }
            
            .login-body {
                padding: 1.5rem;
            }
            
            .resort-logo {
                width: 80px;
                height: 80px;
                margin-top: -60px;
            }
            
            .resort-logo img {
                width: 60px;
                height: 60px;
            }
            
            .form-control {
                padding: 0.6rem 1rem 0.6rem 2.2rem;
                font-size: 0.95rem;
            }
            
            .btn-login {
                padding: 0.6rem;
                font-size: 1rem;
            }
            
            .remember-forgot {
                flex-direction: column;
                gap: 10px;
                align-items: flex-start;
            }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            <div class="login-header">
                <h1><?php echo defined('APP_NAME') ? APP_NAME : 'Ruhondo Beach Resort'; ?></h1>
                <p>Hotel Management & POS System</p>
            </div>
            
            <div class="login-body">
                <!-- Resort Logo -->
                <div class="resort-logo">
                    <img src="<?php echo (function_exists('assets_url') ? assets_url('img/logo.png') : 'https://via.placeholder.com/80?text=RB'); ?>" 
                         alt="Ruhondo Beach Resort" 
                         onerror="this.src='https://via.placeholder.com/80?text=RB'">
                </div>
                
                <!-- Error Alert -->
                <?php if (!empty($error)): ?>
                    <div class="alert alert-danger" role="alert">
                        <i class="fas fa-exclamation-circle me-2"></i>
                        <?php echo htmlspecialchars($error); ?>
                    </div>
                <?php endif; ?>
                
                <!-- Debug Info (remove in production) -->
                <?php if (isset($_GET['debug'])): ?>
                    <div class="alert alert-info">
                        <strong>Debug Info:</strong><br>
                        Session: <?php echo session_status() === PHP_SESSION_ACTIVE ? 'Active' : 'Inactive'; ?><br>
                        Session ID: <?php echo session_id(); ?><br>
                        Auth Function: <?php echo function_exists('authenticate_user') ? 'Available' : 'Missing'; ?><br>
                        Base Path: <?php echo defined('BASE_PATH') ? BASE_PATH : 'Not defined'; ?><br>
                        In Public: <?php echo $in_public ? 'Yes' : 'No'; ?><br>
                        Dashboard Path: <?php echo $dashboard_path; ?>
                    </div>
                <?php endif; ?>
                
                <!-- Login Form -->
                <form method="POST" action="" id="loginForm">
                    <?php if (function_exists('csrf_field')): ?>
                        <?php echo csrf_field(); ?>
                    <?php else: ?>
                        <input type="hidden" name="csrf_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
                    <?php endif; ?>
                    
                    <div class="form-group">
                        <i class="fas fa-user"></i>
                        <input type="text" 
                               class="form-control <?php echo !empty($error) ? 'is-invalid' : ''; ?>" 
                               id="username" 
                               name="username" 
                               placeholder="Username or Email"
                               value="<?php echo htmlspecialchars($username); ?>" 
                               required 
                               autofocus>
                    </div>
                    
                    <div class="form-group">
                        <i class="fas fa-lock"></i>
                        <input type="password" 
                               class="form-control <?php echo !empty($error) ? 'is-invalid' : ''; ?>" 
                               id="password" 
                               name="password" 
                               placeholder="Password"
                               required>
                        <i class="fas fa-eye toggle-password" id="togglePassword"></i>
                    </div>
                    
                    <?php if ($show_captcha && defined('ENABLE_CAPTCHA') && ENABLE_CAPTCHA): ?>
                    <div class="captcha-container">
                        <div class="g-recaptcha" data-sitekey="<?php echo defined('RECAPTCHA_SITE_KEY') ? RECAPTCHA_SITE_KEY : ''; ?>"></div>
                    </div>
                    <?php endif; ?>
                    
                    <div class="remember-forgot">
                        <label class="remember-me">
                            <input type="checkbox" name="remember" <?php echo isset($_POST['remember']) ? 'checked' : ''; ?>>
                            <span>Remember me</span>
                        </label>
                        <a href="<?php echo $login_path; ?>" class="forgot-password">
                            Forgot Password?
                        </a>
                    </div>
                    
                    <button type="submit" class="btn-login" id="loginBtn">
                        <span class="normal-state">
                            <i class="fas fa-sign-in-alt me-2"></i> Login
                        </span>
                        <span class="loading-state d-none">
                            <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                            Logging in...
                        </span>
                    </button>
                </form>
                
                <!-- Demo Credentials (remove in production) -->
                <div class="demo-credentials">
                    <p class="text-center text-muted small mb-3">
                        <i class="fas fa-info-circle me-1"></i>Credentials
                    </p>
                    <div class="row g-2">
                        <div class="col-6">
                            <button type="button" class="btn btn-outline-primary btn-sm w-100 demo-login-btn" onclick="fillLogin('admin', 'Admin@123')">
                                <i class="fas fa-user-shield me-1"></i> Admin
                            </button>
                        </div>
                        <div class="col-6">
                            <button type="button" class="btn btn-outline-success btn-sm w-100 demo-login-btn" onclick="fillLogin('cashier1', 'Admin@123')">
                                <i class="fas fa-cash-register me-1"></i> Cashier
                            </button>
                        </div>
                        <div class="col-6 mt-2">
                            <button type="button" class="btn btn-outline-info btn-sm w-100 demo-login-btn" onclick="fillLogin('fdmanager', 'Admin@123')">
                                <i class="fas fa-concierge-bell me-1"></i> Front Desk
                            </button>
                        </div>
                        <div class="col-6 mt-2">
                            <button type="button" class="btn btn-outline-warning btn-sm w-100 demo-login-btn" onclick="fillLogin('invmanager', 'Admin@123')">
                                <i class="fas fa-broom me-1"></i> Inventory manager
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Attempts Warning -->
                <?php if ($remaining_attempts < (defined('MAX_LOGIN_ATTEMPTS') ? MAX_LOGIN_ATTEMPTS : 5)): ?>
                <div class="attempts-warning">
                    <small class="text-warning">
                        <i class="fas fa-exclamation-triangle me-1"></i>
                        <?php echo $remaining_attempts; ?> login attempt<?php echo $remaining_attempts != 1 ? 's' : ''; ?> remaining
                    </small>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Footer -->
        <div class="login-footer">
            <p>&copy; <?php echo date('Y'); ?> <?php echo defined('APP_NAME') ? APP_NAME : 'Ruhondo Beach Resort'; ?>. All rights reserved.</p>
            <div class="developer-credit">
                Developed by <?php echo defined('APP_COMPANY') ? APP_COMPANY : 'JOACHIM\'S INNOTECH'; ?>
            </div>
        </div>
    </div>
    
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    
    <!-- Bootstrap JS Bundle -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- Google reCAPTCHA -->
    <?php if ($show_captcha && defined('ENABLE_CAPTCHA') && ENABLE_CAPTCHA): ?>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    <?php endif; ?>
    
    <!-- Custom JS -->
    <script>
        $(document).ready(function() {
            const $form = $('#loginForm');
            const $loginBtn = $('#loginBtn');
            const $normalState = $loginBtn.find('.normal-state');
            const $loadingState = $loginBtn.find('.loading-state');
            let submitted = false;
            
            // Form submission
            $form.on('submit', function(e) {
                if (submitted) {
                    e.preventDefault();
                    return false;
                }
                
                // Show loading state
                $loginBtn.prop('disabled', true);
                $normalState.addClass('d-none');
                $loadingState.removeClass('d-none');
                
                submitted = true;
                return true;
            });
            
            // Remove is-invalid class on input
            $('#username, #password').on('input', function() {
                $(this).removeClass('is-invalid');
            });
            
            // Toggle password visibility
            $('#togglePassword').on('click', function() {
                const $password = $('#password');
                const type = $password.attr('type') === 'password' ? 'text' : 'password';
                $password.attr('type', type);
                $(this).toggleClass('fa-eye fa-eye-slash');
            });
            
            // Prevent double submission on page refresh
            if (window.history.replaceState) {
                window.history.replaceState(null, null, window.location.href);
            }
        });
        
        // Fill login form with demo credentials
        function fillLogin(username, password) {
            document.getElementById('username').value = username;
            document.getElementById('password').value = password;
            
            // Optional: auto-submit after a short delay
            // setTimeout(function() {
            //     document.getElementById('loginForm').submit();
            // }, 500);
        }
        
        // Quick fill from URL hash
        if (window.location.hash === '#admin') {
            fillLogin('admin', 'Admin@123');
        } else if (window.location.hash === '#cashier') {
            fillLogin('cashier', 'Admin@123');
        } else if (window.location.hash === '#frontdesk') {
            fillLogin('frontdesk', 'Admin@123');
        } else if (window.location.hash === '#housekeeping') {
            fillLogin('housekeeping', 'Admin@123');
        }
    </script>
</body>
</html>