<?php
session_start();
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.

// Redirect if already logged in
if (isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Include your database connection file
    include 'layouts/dbconn.php';

    // Get username and password from the login form
    $username = trim($_POST['username']);
    $password = $_POST['password'];

    // Validate input
    if (empty($username) || empty($password)) {
        $error_message = "Username and password are required";
    } else {
        // Get client IP address and user agent for logging
        $ip_address = $_SERVER['REMOTE_ADDR'];
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

        try {
            // Check if user exists and get all relevant data including role information
            $sql = "SELECT u.*, ur.role_name
                    FROM users u 
                    INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                    WHERE u.username = ? OR u.email = ?";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ss", $username, $username);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows > 0) {
                $user = $result->fetch_assoc();

                // Check if user account is active (exact ENUM values from schema: ACTIVE, INACTIVE, SUSPENDED)
                if ($user['status'] !== 'ACTIVE') {
                    $error_message = match($user['status']) {
                        'INACTIVE' => 'Your account is inactive. Please contact administrator.',
                        'SUSPENDED' => 'Your account has been suspended. Please contact administrator.',
                        default => 'Account status not valid. Please contact administrator.'
                    };
                } else {
                    // Check for maximum login attempts
                    $max_attempts = 5; // default
                    
                    // Check login attempts (if field exists)
                    $failed_attempts = $user['failed_attempts'] ?? 0;
                    if ($failed_attempts >= $max_attempts) {
                        $error_message = 'Account locked due to too many failed login attempts. Please contact administrator.';
                    } else {
                        // Verify the entered password with the hashed password from the database
                        if (password_verify($password, $user['password'])) {
                            // Password is correct - Reset failed attempts and update last login
                            $update_sql = "UPDATE users SET 
                                          failed_attempts = 0,
                                          last_login = CURRENT_TIMESTAMP 
                                          WHERE user_id = ?";
                            $update_stmt = $conn->prepare($update_sql);
                            $update_stmt->bind_param("i", $user['user_id']);
                            $update_stmt->execute();
                            $update_stmt->close();

                            // Set session variables for cargo management system
                            $_SESSION['user_id'] = $user['user_id'];
                            $_SESSION['username'] = $user['username'];
                            $_SESSION['email'] = $user['email'];
                            $_SESSION['full_name'] = $user['full_name'];
                            $_SESSION['phone'] = $user['phone'];
                            $_SESSION['role_id'] = $user['role_id'];
                            $_SESSION['role_name'] = $user['role_name'];
                            $_SESSION['login_time'] = time();
                            $_SESSION['session_token'] = bin2hex(random_bytes(32));

                            // Log successful login activity
                            $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, old_values, new_values, ip_address, user_agent, logged_at) 
                                       VALUES (?, 'LOGIN', 'users', ?, NULL, ?, ?, ?, NOW())";
                            $log_stmt = $conn->prepare($log_sql);
                            $login_data = json_encode(array(
                                'login_time' => date('Y-m-d H:i:s'),
                                'ip_address' => $ip_address,
                                'role' => $user['role_name'],
                                'session_id' => session_id()
                            ));
                            $log_stmt->bind_param("issss", $user['user_id'], $user['user_id'], $login_data, $ip_address, substr($user_agent, 0, 255));
                            $log_stmt->execute();
                            $log_stmt->close();

                            // Redirect based on role
                            $redirect_url = match($user['role_name']) {
                                'Administrator' => 'index.php',
                                'Operations Manager' => 'index.php',
                                'Finance Manager' => 'index.php',
                                'Customer Service' => 'index.php',
                                'Warehouse Staff' => 'warehouse_dashboard.php',
                                'Driver' => 'driver_dashboard.php',
                                'Customs Officer' => 'customs_dashboard.php',
                                default => 'index.php'
                            };
                            
                            header("Location: $redirect_url");
                            exit();
                        } else {
                            // Invalid password - increment failed attempts
                            $increment_sql = "UPDATE users SET failed_attempts = COALESCE(failed_attempts, 0) + 1, 
                                            last_attempt_time = CURRENT_TIMESTAMP WHERE user_id = ?";
                            $increment_stmt = $conn->prepare($increment_sql);
                            $increment_stmt->bind_param("i", $user['user_id']);
                            $increment_stmt->execute();
                            $increment_stmt->close();

                            // Log failed login attempt
                            $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, old_values, new_values, ip_address, user_agent, logged_at) 
                                       VALUES (?, 'FAILED_LOGIN', 'users', ?, NULL, ?, ?, ?, NOW())";
                            $log_stmt = $conn->prepare($log_sql);
                            $failed_data = json_encode(array(
                                'reason' => 'invalid_password',
                                'attempt_time' => date('Y-m-d H:i:s'),
                                'attempts_count' => $failed_attempts + 1
                            ));
                            $log_stmt->bind_param("issss", $user['user_id'], $user['user_id'], $failed_data, $ip_address, substr($user_agent, 0, 255));
                            $log_stmt->execute();
                            $log_stmt->close();

                            $remaining_attempts = $max_attempts - ($failed_attempts + 1);
                            $error_message = $remaining_attempts > 0 
                                ? "Invalid username or password. $remaining_attempts attempts remaining."
                                : "Invalid username or password. Account will be locked after next failed attempt.";
                        }
                    }
                }
            } else {
                // User not found - log the attempt
                $log_sql = "INSERT INTO activity_log (action, module, record_id, old_values, new_values, ip_address, user_agent, logged_at) 
                           VALUES ('FAILED_LOGIN', 'users', '0', NULL, ?, ?, ?, NOW())";
                $log_stmt = $conn->prepare($log_sql);
                $failed_data = json_encode(array(
                    'reason' => 'user_not_found',
                    'username_attempted' => $username,
                    'attempt_time' => date('Y-m-d H:i:s')
                ));
                $log_stmt->bind_param("sss", $failed_data, $ip_address, substr($user_agent, 0, 255));
                $log_stmt->execute();
                $log_stmt->close();

                $error_message = "Invalid username or password";
            }

            $stmt->close();

        } catch (Exception $e) {
            error_log("Login error: " . $e->getMessage());
            $error_message = "An error occurred during login. Please try again.";
        }

        $conn->close();
    }
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Sign In - Myne Travel Agency')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <style>
        :root {
            --primary-green: #2B8B3C;
            --light-green: #f8fdf9;
            --subtle-green: #f3f9f4;
            --accent-green: #4CAF50;
            --text-dark: #2C3E50;
            --text-light: #6C757D;
            --white: #FFFFFF;
            --border-light: #e8f5ea;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: linear-gradient(135deg, var(--light-green) 0%, var(--white) 50%, #f8fafc 100%);
            min-height: 100vh;
        }

        /* Subtle background pattern */
        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-image: 
                radial-gradient(circle at 20% 80%, rgba(43, 139, 60, 0.03) 0%, transparent 50%),
                radial-gradient(circle at 80% 20%, rgba(43, 139, 60, 0.02) 0%, transparent 50%);
            z-index: -1;
        }

        .auth-page-wrapper {
            padding: 2rem 0;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .main-card {
            border: none;
            border-radius: 24px;
            box-shadow: 
                0 20px 40px rgba(43, 139, 60, 0.04),
                0 10px 20px rgba(0, 0, 0, 0.02);
            overflow: hidden;
            background: var(--white);
            max-width: 1000px;
            width: 100%;
            border: 1px solid var(--border-light);
        }

        .left-panel {
            background: linear-gradient(135deg, var(--white) 0%, var(--subtle-green) 100%);
            position: relative;
            padding: 3rem;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            text-align: center;
            min-height: 600px;
            border-right: 1px solid var(--border-light);
        }

        .left-panel::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: 
                url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%232B8B3C' fill-opacity='0.03'%3E%3Cpath d='M30 0l15 26H15zM0 30l26-15v30zM30 60l-15-26h30zM60 30l-26 15V15z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
            z-index: 1;
        }

        .left-content {
            position: relative;
            z-index: 2;
        }

        .logo-container {
            margin-bottom: 2rem;
            position: relative;
        }

        .logo-bg {
            width: 140px;
            height: 140px;
            background: var(--white);
            border-radius: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 1.5rem;
            box-shadow: 
                0 10px 25px rgba(43, 139, 60, 0.08),
                0 5px 15px rgba(0, 0, 0, 0.04);
            border: 2px solid var(--border-light);
        }

        .company-logo {
            max-width: 110px;
            max-height: 110px;
            object-fit: contain;
        }

        .welcome-title {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.75rem;
            color: var(--text-dark);
            letter-spacing: -0.02em;
        }

        .welcome-subtitle {
            font-size: 1rem;
            color: var(--text-light);
            margin-bottom: 2rem;
            line-height: 1.6;
        }

        .feature-highlights {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
            margin-top: 1.5rem;
        }

        .feature-item {
            background: var(--white);
            padding: 1.25rem;
            border-radius: 16px;
            border: 1px solid var(--border-light);
            transition: all 0.3s ease;
            box-shadow: 0 2px 8px rgba(43, 139, 60, 0.04);
        }

        .feature-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(43, 139, 60, 0.1);
            border-color: var(--primary-green);
        }

        .feature-icon {
            font-size: 1.75rem;
            margin-bottom: 0.75rem;
            display: block;
            color: var(--primary-green);
        }

        .feature-text {
            font-size: 0.875rem;
            font-weight: 600;
            color: var(--text-dark);
        }

        .right-panel {
            padding: 3rem;
            display: flex;
            flex-direction: column;
            justify-content: center;
            background: var(--white);
        }

        .login-header {
            text-align: center;
            margin-bottom: 2.5rem;
        }

        .login-title {
            color: var(--text-dark);
            font-size: 1.75rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }

        .login-subtitle {
            color: var(--text-light);
            font-size: 1rem;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-label {
            color: var(--text-dark);
            font-weight: 600;
            margin-bottom: 0.5rem;
            font-size: 0.875rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .form-control {
            border: 2px solid #E9ECEF;
            border-radius: 12px;
            padding: 0.875rem 1rem;
            font-size: 1rem;
            transition: all 0.3s ease;
            background: var(--white);
        }

        .form-control:focus {
            border-color: var(--primary-green);
            box-shadow: 0 0 0 0.2rem rgba(43, 139, 60, 0.1);
            background: var(--white);
        }

        .input-group-text {
            background: var(--subtle-green);
            border: 2px solid #E9ECEF;
            border-right: none;
            color: var(--primary-green);
            border-radius: 12px 0 0 12px;
        }

        .input-group .form-control {
            border-left: none;
            border-radius: 0 12px 12px 0;
        }

        .input-group:focus-within .input-group-text {
            border-color: var(--primary-green);
        }

        .btn-primary-custom {
            background: linear-gradient(135deg, var(--primary-green) 0%, var(--accent-green) 100%);
            border: none;
            border-radius: 12px;
            padding: 1rem 2rem;
            font-weight: 600;
            font-size: 1rem;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .btn-primary-custom:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(43, 139, 60, 0.25);
        }

        .alert-danger {
            background: #FEF2F2;
            border: 1px solid #FECACA;
            color: #B91C1C;
            border-radius: 12px;
            padding: 1rem;
            margin-bottom: 1.5rem;
        }

        .info-cards {
            display: grid;
            gap: 1rem;
            margin-top: 2rem;
        }

        .info-card {
            background: var(--subtle-green);
            border: 1px solid var(--border-light);
            border-radius: 12px;
            padding: 1.25rem;
        }

        .info-card-title {
            color: var(--primary-green);
            font-weight: 700;
            font-size: 0.875rem;
            margin-bottom: 0.75rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .footer {
            margin-top: 2rem;
            text-align: center;
            padding: 1rem;
        }

        .brand-name {
            color: var(--primary-green);
            font-weight: 700;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .left-panel, .right-panel {
                padding: 2rem;
            }
            
            .logo-bg {
                width: 100px;
                height: 100px;
            }
            
            .company-logo {
                max-width: 80px;
                max-height: 80px;
            }
            
            .feature-highlights {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>

<body>
    <div class="auth-page-wrapper">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-12">
                    <div class="main-card">
                        <div class="row g-0">
                            <!-- Left Panel -->
                            <div class="col-lg-6">
                                <div class="left-panel">
                                    <div class="left-content">
                                        <div class="logo-container">
                                            <div class="logo-bg">
                                                <img src="assets/images/polakis.png" alt="Myne Travel Agency" class="company-logo">
                                            </div>
                                        </div>
                                        
                                        <h2 class="welcome-title">Welcome Back!</h2>
                                        <p class="welcome-subtitle">
                                            Your journey begins with Myne Travel Agency - 
                                            East Africa's premier travel and cargo management platform.
                                        </p>
                                        
                                        <div class="feature-highlights">
                                            <div class="feature-item">
                                                <i class="ri-plane-line feature-icon"></i>
                                                <div class="feature-text">Travel Booking</div>
                                            </div>
                                            <div class="feature-item">
                                                <i class="ri-truck-line feature-icon"></i>
                                                <div class="feature-text">Cargo Services</div>
                                            </div>
                                            <div class="feature-item">
                                                <i class="ri-global-line feature-icon"></i>
                                                <div class="feature-text">Global Network</div>
                                            </div>
                                            <div class="feature-item">
                                                <i class="ri-customer-service-2-line feature-icon"></i>
                                                <div class="feature-text">24/7 Support</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Right Panel -->
                            <div class="col-lg-6">
                                <div class="right-panel">
                                    <div class="login-header">
                                        <h1 class="login-title">Sign In</h1>
                                        <p class="login-subtitle">Access your travel and cargo management dashboard</p>
                                    </div>

                                    <!-- Error message display -->
                                    <?php if(isset($error_message)): ?>
                                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                            <i class="ri-error-warning-line me-2"></i>
                                            <?php echo htmlspecialchars($error_message); ?>
                                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                        </div>
                                    <?php endif; ?>

                                    <form id="login-form" method="POST" novalidate>
                                        <div class="form-group">
                                            <label for="username" class="form-label">Username or Email</label>
                                            <div class="input-group">
                                                <span class="input-group-text"><i class="ri-user-line"></i></span>
                                                <input type="text" class="form-control" id="username" name="username" 
                                                       placeholder="Enter username or email" 
                                                       value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>"
                                                       required>
                                            </div>
                                            <div class="invalid-feedback">Please enter your username or email.</div>
                                        </div>

                                        <div class="form-group">
                                            <div class="d-flex justify-content-between align-items-center mb-2">
                                                <label class="form-label mb-0" for="password">Password</label>
                                                <a href="forgot_password.php" class="text-muted text-decoration-none small">
                                                    <i class="ri-lock-unlock-line me-1"></i>Forgot password?
                                                </a>
                                            </div>
                                            <div class="input-group">
                                                <span class="input-group-text"><i class="ri-lock-line"></i></span>
                                                <input type="password" class="form-control" placeholder="Enter password" 
                                                       id="password" name="password" required>
                                                <button class="btn btn-outline-secondary" type="button" id="password-addon">
                                                    <i class="ri-eye-line"></i>
                                                </button>
                                            </div>
                                            <div class="invalid-feedback">Please enter your password.</div>
                                        </div>

                                        <div class="form-check mb-3">
                                            <input class="form-check-input" type="checkbox" id="auth-remember-check">
                                            <label class="form-check-label" for="auth-remember-check">
                                                Remember me on this device
                                            </label>
                                        </div>

                                        <div class="d-grid">
                                            <button class="btn btn-primary-custom" type="submit" id="login-btn">
                                                <i class="ri-login-circle-line me-2"></i>Sign In to Dashboard
                                            </button>
                                        </div>
                                    </form>

                                    <!-- Info Cards -->
                                    <div class="info-cards">
                                        <div class="info-card">
                                            <div class="info-card-title">
                                                <i class="ri-shield-check-line"></i>Secure Access
                                            </div>
                                            <div class="info-card-content">
                                                <small class="text-muted">
                                                    Enterprise-grade security with monitored login attempts for your safety.
                                                </small>
                                            </div>
                                        </div>
                                        
                                        <div class="info-card">
                                            <div class="info-card-title">
                                                <i class="ri-customer-service-line"></i>Need Help?
                                            </div>
                                            <div class="info-card-content">
                                                <small class="text-muted">
                                                    <strong>Support:</strong> support@mynetravel.com<br>
                                                    <strong>Phone:</strong> +254 700 123 456<br>
                                                    <strong>Hours:</strong> 24/7 Support Available
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="footer">
        <div class="container">
            <div class="row">
                <div class="col-12">
                    <div class="text-center">
                        <p class="text-muted mb-0">
                            &copy; <script>document.write(new Date().getFullYear())</script> 
                            <span class="brand-name">Myne Travel Agency Ltd</span> - 
                            Your trusted partner for travel and cargo solutions
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </footer>

    <?php include 'layouts/vendor-scripts.php'; ?>

    <script>
    // Password toggle
    document.getElementById('password-addon').addEventListener('click', function() {
        const passwordInput = document.getElementById('password');
        const icon = this.querySelector('i');
        
        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            icon.className = 'ri-eye-off-line';
        } else {
            passwordInput.type = 'password';
            icon.className = 'ri-eye-line';
        }
    });

    // Form validation and submission
    document.getElementById('login-form').addEventListener('submit', function(event) {
        const form = this;
        const username = document.getElementById('username');
        const password = document.getElementById('password');
        const loginBtn = document.getElementById('login-btn');
        
        form.classList.remove('was-validated');
        let isValid = true;
        
        if (!username.value.trim()) {
            username.classList.add('is-invalid');
            isValid = false;
        } else {
            username.classList.remove('is-invalid');
            username.classList.add('is-valid');
        }
        
        if (!password.value) {
            password.classList.add('is-invalid');
            isValid = false;
        } else {
            password.classList.remove('is-invalid');
            password.classList.add('is-valid');
        }
        
        if (!isValid) {
            event.preventDefault();
            form.classList.add('was-validated');
            return;
        }
        
        loginBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Signing in...';
        loginBtn.disabled = true;
    });

    // Auto-focus and entrance animations
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('username').focus();
    });

    // SweetAlert notifications
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('logout') === 'success') {
        Swal.fire({
            icon: 'success',
            title: 'Logged Out Successfully',
            text: 'You have been safely signed out.',
            timer: 3000,
            showConfirmButton: false,
            iconColor: '#2B8B3C'
        });
    }

    if (urlParams.get('welcome') === '1') {
        Swal.fire({
            icon: 'info',
            title: 'Welcome to Shiine Travel Agency',
            text: 'Please sign in with your credentials to access your dashboard.',
            confirmButtonText: 'Got it',
            confirmButtonColor: '#2B8B3C'
        });
    }

    if (urlParams.get('maintenance') === '1') {
        Swal.fire({
            icon: 'warning',
            title: 'System Maintenance Complete',
            text: 'You can now sign in normally.',
            confirmButtonText: 'Continue',
            confirmButtonColor: '#2B8B3C'
        });
    }

    // Auto-dismiss alerts after 8 seconds
    setTimeout(function() {
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(function(alert) {
            if (alert.querySelector('.btn-close')) {
                const alertInstance = new bootstrap.Alert(alert);
                alertInstance.close();
            }
        });
    }, 8000);

    // Enhanced security: Clear password field on page unload
    window.addEventListener('beforeunload', function() {
        document.getElementById('password').value = '';
    });

    // Prevent multiple form submissions
    let isSubmitting = false;
    document.getElementById('login-form').addEventListener('submit', function(e) {
        if (isSubmitting) {
            e.preventDefault();
            return false;
        }
        isSubmitting = true;
    });

    // Reset submitting flag if there's an error
    window.addEventListener('load', function() {
        isSubmitting = false;
        const loginBtn = document.getElementById('login-btn');
        if (loginBtn.innerHTML.includes('spinner')) {
            loginBtn.innerHTML = '<i class="ri-login-circle-line me-2"></i>Sign In to Dashboard';
            loginBtn.disabled = false;
        }
    });
    </script>
</body>
</html>