<?php
session_start();
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

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

$error_message = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    require_once 'layouts/dbconn.php';

    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    if (empty($username) || empty($password)) {
        $error_message = "Username and password are required";
    } else {
        $ip_address = $_SERVER['REMOTE_ADDR'];
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }

        try {
            $sql = "SELECT u.user_id, u.username, u.email, u.password_hash, u.first_name, u.last_name,
                           u.phone_number, u.role_id, u.status, u.failed_login_attempts, u.locked_until,
                           r.role_name
                    FROM users u 
                    INNER JOIN roles r ON u.role_id = r.role_id 
                    WHERE (u.username = ? OR u.email = ?) 
                    AND u.deleted_at IS NULL
                    AND r.is_active = 1";
            
            $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();

                if ($user['locked_until'] && strtotime($user['locked_until']) > time()) {
                    $error_message = "Account is locked. Please try again later or contact administrator.";
                } elseif ($user['status'] !== 'ACTIVE') {
                    $error_message = "Your account is not active. Please contact administrator.";
                } else {
                    if (password_verify($password, $user['password_hash'])) {
                        // Password is correct
                        $update_sql = "UPDATE users SET 
                                      failed_login_attempts = 0,
                                      locked_until = NULL,
                                      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();

                        // Get user permissions
                        $permissions_sql = "SELECT p.permission_name 
                                           FROM permissions p
                                           INNER JOIN role_permissions rp ON p.permission_id = rp.permission_id
                                           WHERE rp.role_id = ?";
                        $perm_stmt = $conn->prepare($permissions_sql);
                        $perm_stmt->bind_param("i", $user['role_id']);
                        $perm_stmt->execute();
                        $perm_result = $perm_stmt->get_result();
                        $user_permissions = [];
                        while ($perm_row = $perm_result->fetch_assoc()) {
                            $user_permissions[] = $perm_row['permission_name'];
                        }
                        $perm_stmt->close();

                        // Set session variables
                        $_SESSION['user_id'] = $user['user_id'];
                        $_SESSION['username'] = $user['username'];
                        $_SESSION['email'] = $user['email'];
                        $_SESSION['full_name'] = $user['first_name'] . ' ' . $user['last_name'];
                        $_SESSION['first_name'] = $user['first_name'];
                        $_SESSION['last_name'] = $user['last_name'];
                        $_SESSION['phone_number'] = $user['phone_number'];
                        $_SESSION['role_id'] = $user['role_id'];
                        $_SESSION['role_name'] = $user['role_name'];
                        $_SESSION['user_permissions'] = $user_permissions;
                        $_SESSION['login_time'] = time();
                        $_SESSION['last_activity'] = time();
                        $_SESSION['session_token'] = bin2hex(random_bytes(32));

                        // Log successful login
                        $log_sql = "INSERT INTO audit_logs (event_type, event_category, event_description, performed_by, ip_address) 
                                   VALUES (?, ?, ?, ?, ?)";
                        $log_stmt = $conn->prepare($log_sql);
                        $event_type = 'USER_LOGIN';
                        $event_category = 'SYSTEM';
                        $event_description = json_encode([
                            'login_time' => date('Y-m-d H:i:s'),
                            'ip_address' => $ip_address,
                            'role' => $user['role_name'],
                            'session_id' => session_id()
                        ]);
                        $performed_by = $user['username'];
                        $log_stmt->bind_param("sssss", $event_type, $event_category, $event_description, $performed_by, $ip_address);
                        $log_stmt->execute();
                        $log_stmt->close();

                        // Role-based redirects
                        $redirect_url = match(strtoupper($user['role_name'])) {
                            'SYSTEM ADMINISTRATOR' => 'index.php',
                            'TRUSTEE' => 'trustee_dashboard.php',
                            'EMPLOYER HR' => 'employer_dashboard.php',
                            'MEMBER' => 'member_portal.php',
                            'INSURANCE OFFICER' => 'insurance_dashboard.php',
                            'FINANCE OFFICER' => 'finance_dashboard.php',
                            'AGENT' => 'agent_dashboard.php',
                            default => 'index.php'
                        };
                        
                        header("Location: $redirect_url");
                        exit();
                    } else {
                        // Invalid password
                        $failed_attempts = ($user['failed_login_attempts'] ?? 0) + 1;
                        $max_attempts = 5;
                        
                        $locked_until = null;
                        if ($failed_attempts >= $max_attempts) {
                            $locked_until = date('Y-m-d H:i:s', time() + (30 * 60));
                        }
                        
                        $increment_sql = "UPDATE users SET 
                                        failed_login_attempts = ?,
                                        locked_until = ?
                                        WHERE user_id = ?";
                        $increment_stmt = $conn->prepare($increment_sql);
                        $increment_stmt->bind_param("isi", $failed_attempts, $locked_until, $user['user_id']);
                        $increment_stmt->execute();
                        $increment_stmt->close();

                        // Log failed login
                        $log_sql = "INSERT INTO audit_logs (event_type, event_category, event_description, performed_by, ip_address) 
                                   VALUES (?, ?, ?, ?, ?)";
                        $log_stmt = $conn->prepare($log_sql);
                        $event_type = 'FAILED_LOGIN';
                        $event_category = 'SYSTEM';
                        $event_description = json_encode([
                            'reason' => 'invalid_password',
                            'attempt_time' => date('Y-m-d H:i:s'),
                            'attempts_count' => $failed_attempts,
                            'username_attempted' => $username
                        ]);
                        $performed_by = $user['username'] ?? 'UNKNOWN';
                        $log_stmt->bind_param("sssss", $event_type, $event_category, $event_description, $performed_by, $ip_address);
                        $log_stmt->execute();
                        $log_stmt->close();

                        $remaining_attempts = $max_attempts - $failed_attempts;
                        if ($failed_attempts >= $max_attempts) {
                            $error_message = "Account locked due to too many failed login attempts. Please try again in 30 minutes.";
                        } else {
                            $error_message = "Invalid username or password. " . $remaining_attempts . " attempts remaining.";
                        }
                    }
                }
            } else {
                // User not found
                $log_sql = "INSERT INTO audit_logs (event_type, event_category, event_description, performed_by, ip_address) 
                           VALUES (?, ?, ?, ?, ?)";
                $log_stmt = $conn->prepare($log_sql);
                $event_type = 'FAILED_LOGIN';
                $event_category = 'SYSTEM';
                $event_description = json_encode([
                    'reason' => 'user_not_found',
                    'username_attempted' => $username,
                    'attempt_time' => date('Y-m-d H:i:s')
                ]);
                $performed_by = 'UNKNOWN';
                $log_stmt->bind_param("sssss", $event_type, $event_category, $event_description, $performed_by, $ip_address);
                $log_stmt->execute();
                $log_stmt->close();

                $error_message = "Invalid username or password";
            }

            $stmt->close();
            $conn->close();

        } catch (Exception $e) {
            error_log("Login error: " . $e->getMessage());
            $error_message = "An error occurred during login. Please try again.";
            if (isset($conn)) {
                $conn->close();
            }
        }
    }
}
?>
<?php include 'layouts/public.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Sign In - Kenyan Pension & Life Insurance System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <style>
        :root {
            --primary-care: #2563eb;
            --primary-care-light: #3b82f6;
            --primary-care-dark: #1e40af;
            --accent-care: #60a5fa;
            --success-care: #10b981;
            --light-blue: #eff6ff;
            --very-light-blue: #f0f9ff;
            --medical-purple: #8b5cf6;
            --medical-purple-light: #a78bfa;
            --text-dark: #1f2937;
            --text-muted: #6b7280;
            --white: #ffffff;
            --light-gray: #f9fafb;
            --border-color: #e5e7eb;
        }

        body {
            background: linear-gradient(135deg, var(--very-light-blue) 0%, var(--light-blue) 100%);
            min-height: 100vh;
        }

        .auth-page-wrapper {
            background: linear-gradient(135deg, var(--very-light-blue) 0%, var(--light-blue) 100%);
        }

        .card {
            border: none;
            box-shadow: 0 10px 30px rgba(37, 99, 235, 0.1);
            border-radius: 16px;
            overflow: hidden;
        }

        .bg-primary {
            background: linear-gradient(135deg, #ffffff 0%, #f8faff 30%, #eff6ff 100%) !important;
            border-right: 4px solid var(--primary-care);
        }

        .form-control {
            border: 2px solid var(--border-color);
            border-radius: 8px;
            padding: 12px 16px;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .form-control:focus {
            border-color: var(--primary-care);
            box-shadow: 0 0 0 0.2rem rgba(37, 99, 235, 0.25);
        }

        .input-group-text {
            background-color: var(--light-blue);
            border: 2px solid var(--border-color);
            border-right: none;
            color: var(--primary-care);
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary-care) 0%, var(--primary-care-light) 100%);
            border: none;
            border-radius: 8px;
            padding: 12px 24px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            background: linear-gradient(135deg, var(--primary-care-dark) 0%, var(--primary-care) 100%);
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(37, 99, 235, 0.3);
        }

        .btn-outline-secondary:hover {
            background-color: var(--light-blue);
            border-color: var(--primary-care);
            color: var(--primary-care);
        }

        .alert-danger {
            background-color: #fef2f2;
            border-color: #fecaca;
            color: #dc2626;
            border-left: 4px solid #ef4444;
        }

        a {
            color: var(--primary-care);
            text-decoration: none;
        }

        a:hover {
            color: var(--primary-care-dark);
            text-decoration: underline;
        }

        .text-primary {
            color: var(--primary-care) !important;
        }

        .form-check-input:checked {
            background-color: var(--primary-care);
            border-color: var(--primary-care);
        }

        .form-check-input:focus {
            box-shadow: 0 0 0 0.2rem rgba(37, 99, 235, 0.25);
        }

        .logo-accent {
            position: absolute;
            top: -10px;
            left: -10px;
            right: -10px;
            bottom: -10px;
            background: linear-gradient(135deg, var(--light-blue), var(--very-light-blue));
            border-radius: 50%;
            z-index: -1;
            opacity: 0.3;
        }

        .card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, var(--primary-care) 0%, var(--medical-purple) 100%);
            z-index: 1;
        }

        @media (max-width: 768px) {
            .card {
                margin: 15px;
            }
            .p-lg-5 {
                padding: 2rem !important;
            }
        }
    </style>
</head>

<body>
    <div class="auth-page-wrapper py-5 d-flex justify-content-center align-items-center min-vh-100">
        <div class="auth-page-content overflow-hidden pt-lg-5">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card overflow-hidden border-0 shadow-lg">
                            <div class="row g-0">
                                <div class="col-lg-6">
                                    <div class="p-lg-5 p-4 h-100 bg-primary bg-gradient">
                                        <div class="position-relative h-100 d-flex flex-column align-items-center justify-content-center text-center">
                                            <div class="mb-4">
                                                <a href="index.php" class="d-block position-relative">
                                                    <div class="logo-accent"></div>
                                                    <img src="assets/images/logo/CWUA.png" alt="Kenyan Pension & Life Insurance System" height="80" class="mb-3 position-relative">
                                                </a>
                                                <h4 class="text-dark mb-3">Pension & Life Insurance Management</h4>
                                                <p class="text-muted mb-4">Comprehensive retirement benefits and life insurance administration platform for Kenya.</p>
                                            </div>
                                            
                                            <div class="row text-center">
                                                <div class="col-12 mb-3">
                                                    <i class="ri-shield-check-line text-primary h4 mb-2 d-block"></i>
                                                    <small class="text-muted">RBA Compliant</small>
                                                </div>
                                                <div class="col-12 mb-3">
                                                    <i class="ri-file-list-3-line text-primary h4 mb-2 d-block"></i>
                                                    <small class="text-muted">Pension Schemes Management</small>
                                                </div>
                                                <div class="col-12 mb-3">
                                                    <i class="ri-heart-pulse-line text-primary h4 mb-2 d-block"></i>
                                                    <small class="text-muted">Life Insurance Policies</small>
                                                </div>
                                                <div class="col-12">
                                                    <i class="ri-secure-payment-line text-primary h4 mb-2 d-block"></i>
                                                    <small class="text-muted">Secure Financial Transactions</small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-lg-6">
                                    <div class="p-lg-5 p-4">
                                        <div class="text-center mb-4">
                                            <h5 class="text-primary mb-2">Welcome Back!</h5>
                                            <p class="text-muted">Sign in to continue to Pension & Life Insurance System</p>
                                        </div>

                                        <div class="mt-4">
                                            <?php if(!empty($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" aria-label="Close"></button>
                                                </div>
                                            <?php endif; ?>

                                            <form id="login-form" method="POST" novalidate>
                                                <div class="mb-3">
                                                    <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="mb-3">
                                                    <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-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" value="" id="auth-remember-check">
                                                    <label class="form-check-label" for="auth-remember-check">
                                                        Remember me on this device
                                                    </label>
                                                </div>

                                                <div class="mt-4">
                                                    <button class="btn btn-primary w-100" type="submit" id="login-btn">
                                                        <i class="ri-login-box-line me-2"></i>Sign In
                                                    </button>
                                                </div>

                                                <div class="mt-4 p-3 bg-light rounded">
                                                    <h6 class="text-muted mb-2">
                                                        <i class="ri-information-line me-2"></i>User Access Levels
                                                    </h6>
                                                    <small class="text-muted">
                                                        <strong>Members:</strong> View pension accounts, statements<br>
                                                        <strong>Employers:</strong> Manage contributions, schedules<br>
                                                        <strong>Trustees:</strong> Scheme administration, approvals<br>
                                                        <strong>Insurance Officers:</strong> Policy management, claims
                                                    </small>
                                                </div>

                                                <div class="mt-3 p-3 bg-info bg-opacity-10 rounded">
                                                    <h6 class="text-info mb-2">
                                                        <i class="ri-headphone-line me-2"></i>Need Help?
                                                    </h6>
                                                    <small class="text-muted">
                                                        Contact support for technical assistance.<br>
                                                        <strong>Email:</strong> support@pensionlife.co.ke<br>
                                                        <strong>Phone:</strong> +254-700-000-000<br>
                                                        <strong>Hours:</strong> Mon-Fri 8:00 AM - 5:00 PM EAT
                                                    </small>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <footer class="footer">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="text-center">
                            <p class="mb-0 text-muted">
                                &copy; <script>document.write(new Date().getFullYear())</script> 
                                <span class="text-primary fw-semibold">Kenyan Pension & Life Insurance Management System</span> - 
                                RBA Compliant Platform
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </footer>
    </div>

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

    <script>
    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';
        }
    });

    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" role="status" aria-hidden="true"></span>Signing in...';
        loginBtn.disabled = true;
    });

    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('username').focus();
    });

    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('logout') === 'success') {
        Swal.fire({
            icon: 'success',
            title: 'Logged Out',
            text: 'You have been successfully logged out.',
            timer: 2000,
            showConfirmButton: false
        });
    }

    setTimeout(function() {
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(function(alert) {
            if (alert.querySelector('.btn-close')) {
                alert.querySelector('.btn-close').click();
            }
        });
    }, 10000);

    window.addEventListener('beforeunload', function() {
        document.getElementById('password').value = '';
    });

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

    window.addEventListener('load', function() {
        isSubmitting = false;
        const loginBtn = document.getElementById('login-btn');
        loginBtn.innerHTML = '<i class="ri-login-box-line me-2"></i>Sign In';
        loginBtn.disabled = false;
    });
    </script>
</body>
</html>