<?php
session_start();
include_once 'config/database.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ocean Bank Cooperation - Secure Login</title>
    
    <!-- CSS Dependencies -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/boxicons@2.0.7/css/boxicons.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap" rel="stylesheet">

    <style>
        :root {
            --primary-color: #2563eb;
            --secondary-color: #1e40af;
            --success-color: #059669;
            --danger-color: #dc2626;
            --warning-color: #ea580c;
            --info-color: #0284c7;
            --background-color: #f0f2f5;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: var(--background-color);
            min-height: 100vh;
            display: flex;
            align-items: center;
        }

        .login-container {
            min-height: 100vh;
            width: 100%;
            background: linear-gradient(135deg, #2563eb, #1e40af);
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 2rem;
        }

        .login-wrapper {
            width: 100%;
            max-width: 1200px;
            display: flex;
            background: white;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
        }

        .login-left {
            flex: 1;
            background: linear-gradient(135deg, rgba(37, 99, 235, 0.9), rgba(30, 64, 175, 0.9));
            padding: 40px;
            position: relative;
            display: none;
        }

        @media (min-width: 992px) {
            .login-left {
                display: block;
            }
        }

        .login-left-content {
            position: relative;
            z-index: 1;
            color: white;
        }

        .login-right {
            flex: 1;
            padding: 40px;
            background: white;
        }

        .brand-logo {
            text-align: center;
            margin-bottom: 2rem;
        }

        .brand-logo img {
            height: 60px;
        }

        .login-form {
            max-width: 400px;
            margin: 0 auto;
        }

        .form-control {
            padding: 0.75rem 1rem;
            border-radius: 10px;
            border: 2px solid #e2e8f0;
            font-size: 0.95rem;
        }

        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: none;
        }

        .form-label {
            font-weight: 500;
            color: #4b5563;
        }

        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: var(--primary-color);
            border: none;
        }

        .btn-primary:hover {
            background: var(--secondary-color);
            transform: translateY(-2px);
        }

        .security-tips-section {
            margin-top: 2rem;
            padding: 1.5rem;
            background: #f8fafc;
            border-radius: 15px;
            border: 1px solid #e2e8f0;
        }

        .security-tip-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px;
            margin-bottom: 10px;
            background: white;
            border-radius: 10px;
            transform: translateY(20px);
            opacity: 0;
            transition: all 0.5s ease;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }

        .security-tip-item.show {
            transform: translateY(0);
            opacity: 1;
        }

        .security-tip-icon {
            width: 40px;
            height: 40px;
            background: #e8f0fe;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }

        .security-tip-icon i {
            font-size: 20px;
        }

        .security-tip-content {
            flex: 1;
        }

        .security-tip-title {
            font-weight: 500;
            margin-bottom: 2px;
            color: #1a1a1a;
        }

        .security-tip-description {
            font-size: 0.85rem;
            color: #64748b;
            margin: 0;
        }

        .auth-links {
            margin-top: 2rem;
            text-align: center;
        }

        .auth-links a {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 500;
            transition: color 0.3s ease;
        }

        .auth-links a:hover {
            color: var(--secondary-color);
        }

        /* Custom alert styles */
        .alert-success {
            background-color: #d1fae5;
            border-color: #a7f3d0;
            color: #065f46;
        }

        .alert-info {
            background-color: #dbeafe;
            border-color: #93c5fd;
            color: #1e40af;
        }
    </style>
</head>
<body>

<div class="login-container">
    <div class="login-wrapper">
        <!-- Left Side -->
        <div class="login-left">
            <div class="login-left-content">
                <h2 class="mb-4">Welcome to Ocean Bank Cooperation</h2>
                <p class="mb-4">Experience secure and convenient banking at your fingertips.</p>
                <ul class="list-unstyled">
                    <li class="mb-3">
                        <i class='bx bx-check-circle me-2'></i>
                        24/7 Secure Access
                    </li>
                    <li class="mb-3">
                        <i class='bx bx-check-circle me-2'></i>
                        Fast & Easy Transactions
                    </li>
                    <li class="mb-3">
                        <i class='bx bx-check-circle me-2'></i>
                        Advanced Security Features
                    </li>
                </ul>
            </div>
        </div>

        <!-- Right Side -->
        <div class="login-right">
            <div class="brand-logo">
                <img src="logo.png" alt="Ocean Bank Cooperation">
            </div>

            <div class="login-form">
                <h4 class="text-center mb-4">Login to Your Account</h4>

                <?php if (isset($_SESSION['success'])): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class='bx bx-check-circle me-2'></i>
                        <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <?php if (isset($_SESSION['info'])): ?>
                    <div class="alert alert-info alert-dismissible fade show" role="alert">
                        <i class='bx bx-info-circle me-2'></i>
                        <?php echo $_SESSION['info']; unset($_SESSION['info']); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <?php if (isset($_SESSION['error'])): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class='bx bx-error-circle me-2'></i>
                        <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <form id="loginForm" onsubmit="return handleLogin(event)">
                    <div class="mb-3">
                        <label class="form-label">Username</label>
                        <input type="text" class="form-control" name="username" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Password</label>
                        <div class="input-group">
                            <input type="password" class="form-control" name="password" required>
                            <button class="btn btn-outline-secondary" type="button" onclick="togglePassword()">
                                <i class='bx bx-show'></i>
                            </button>
                        </div>
                    </div>

                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="remember" name="remember" value="1">
                        <label class="form-check-label" for="remember">Remember me</label>
                    </div>

                    <button type="submit" class="btn btn-primary w-100">Login Securely</button>

                    <div class="auth-links mt-3">
                        <a href="forgot-password.php">Forgot Password?</a>
                        <div class="mt-2">
                            Don't have an account? <a href="register.php">Create Account</a>
                        </div>
                    </div>
                </form>

                <div class="security-tips-section">
                    <h5 class="mb-3">Security Tips</h5>
                    <div id="securityTipsList">
                        <!-- Tips will be added here dynamically -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    // Security Tips
    const securityTips = [
        {
            icon: 'bx-shield-quarter',
            title: 'Verify Website Security',
            text: 'Check for the padlock icon and verify our official URL before logging in',
            color: '#2563eb'
        },
        {
            icon: 'bx-lock-alt',
            title: 'Protect Your Credentials',
            text: 'Never share your login details, PIN, or OTP with anyone',
            color: '#dc2626'
        },
        {
            icon: 'bx-check-shield',
            title: 'Strong Password',
            text: 'Use a unique password with letters, numbers, and special characters',
            color: '#059669'
        }
    ];

    function createSecurityTips() {
        const container = document.getElementById('securityTipsList');
        if (!container) return;

        container.innerHTML = '';

        securityTips.forEach((tip, index) => {
            const tipElement = document.createElement('div');
            tipElement.className = 'security-tip-item';
            tipElement.innerHTML = `
                <div class="security-tip-icon">
                    <i class='bx ${tip.icon}' style="color: ${tip.color}"></i>
                </div>
                <div class="security-tip-content">
                    <div class="security-tip-title">${tip.title}</div>
                    <p class="security-tip-description">${tip.text}</p>
                </div>
            `;
            container.appendChild(tipElement);

            setTimeout(() => {
                tipElement.classList.add('show');
            }, index * 200);
        });
    }

    document.addEventListener('DOMContentLoaded', function() {
        createSecurityTips();
        
        // Check for URL parameters and show appropriate messages
        const urlParams = new URLSearchParams(window.location.search);
        
        if (urlParams.get('registered') === 'true') {
            Swal.fire({
                icon: 'success',
                title: 'Registration Successful!',
                html: `
                    <p>Your account has been created successfully.</p>
                    <p><strong>Please check your email</strong> for verification instructions.</p>
                    <p>You can now login with your credentials.</p>
                `,
                confirmButtonText: 'Got it!',
                confirmButtonColor: '#059669'
            });
        }
        
        if (urlParams.get('verified') === 'true') {
            Swal.fire({
                icon: 'success',
                title: 'Email Verified!',
                text: 'Your email has been verified successfully. You can now login.',
                confirmButtonText: 'Login Now',
                confirmButtonColor: '#059669'
            });
        }
        
        if (urlParams.get('reset') === 'true') {
            Swal.fire({
                icon: 'info',
                title: 'Password Reset',
                text: 'Your password has been reset successfully. Please login with your new password.',
                confirmButtonText: 'Login Now',
                confirmButtonColor: '#0284c7'
            });
        }
    });

    setInterval(() => {
        const tips = document.querySelectorAll('.security-tip-item');
        tips.forEach((tip, index) => {
            tip.classList.remove('show');
            setTimeout(() => {
                tip.classList.add('show');
            }, index * 200);
        });
    }, 30000);

    // Handle Login
    async function handleLogin(event) {
        event.preventDefault();

        const form = event.target;
        const formData = new FormData(form);

        Swal.fire({
            title: 'Authenticating',
            text: 'Please wait while we verify your credentials...',
            allowOutsideClick: false,
            showConfirmButton: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        try {
            const response = await fetch('verify_login.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username: formData.get('username'),
                    password: formData.get('password'),
                    remember: formData.get('remember') ? 1 : 0
                })
            });

            // Check if response is JSON
            const contentType = response.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                const text = await response.text();
                console.error('Non-JSON response:', text);
                throw new Error(`Server returned unexpected response: ${text.substring(0, 100)}`);
            }

            const data = await response.json();
            console.log('Login response:', data);

            if (!response.ok) {
                throw new Error(data.message || response.statusText);
            }

            if (data.success) {
                // Show success message before redirect
                await Swal.fire({
                    icon: 'success',
                    title: 'Login Successful!',
                    text: 'Welcome back! Redirecting to your dashboard...',
                    timer: 2000,
                    showConfirmButton: false,
                    allowOutsideClick: false
                });
                
                console.log('Redirecting to:', data.redirect);
                window.location.href = data.redirect || 'dashboard.php';
            } else {
                throw new Error(data.message || 'Login failed');
            }
        } catch (error) {
            console.error('Login error:', error);
            Swal.fire({
                icon: 'error',
                title: 'Login Failed',
                text: error.message || 'An error occurred during login. Please try again.',
                confirmButtonText: 'Try Again',
                confirmButtonColor: '#dc2626'
            });
        }
    }

    function togglePassword() {
        const passwordInput = document.querySelector('input[name="password"]');
        const icon = document.querySelector('.bx-show, .bx-hide');
        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            icon.classList.replace('bx-show', 'bx-hide');
        } else {
            passwordInput.type = 'password';
            icon.classList.replace('bx-hide', 'bx-show');
        }
    }
</script>
</body>
</html>
