<?php
session_start();
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';

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

// Redirect if already logged in
if (isset($_SESSION['user_id'])) {
    // Redirect based on user role
    if (isset($_SESSION['is_admin']) && $_SESSION['is_admin'] == 1) {
        header('Location: admin/dashboard.php');
    } else {
        header('Location: user/dashboard.php');
    }
    exit();
}

$error = '';
$success = '';
$email = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = sanitizeInput($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

    if (empty($email) || empty($password)) {
        $error = 'Please enter both email and password';
    } else {
        try {
            // Get user details including admin status
            $stmt = $pdo->prepare("SELECT user_id, full_name, email, password_hash, status, is_admin, is_active FROM users WHERE email = ?");
            $stmt->execute([$email]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user && password_verify($password, $user['password_hash'])) {
                // Check account status
                if ($user['status'] === 'pending') {
                    $error = 'Your account is pending approval. Please wait for admin verification.';
                } elseif ($user['status'] === 'rejected') {
                    $error = 'Your account application has been rejected. Please contact support for assistance.';
                } elseif ($user['status'] === 'approved' && $user['is_active'] == 1) {
                    // Login successful
                    $_SESSION['user_id'] = $user['user_id'];
                    $_SESSION['user_name'] = $user['full_name'];
                    $_SESSION['user_email'] = $user['email'];
                    $_SESSION['user_status'] = $user['status'];
                    $_SESSION['is_admin'] = $user['is_admin'];

                    // Update login attempts (reset on successful login)
                    $updateStmt = $pdo->prepare("UPDATE users SET login_attempts = 0, blocked_until = NULL WHERE user_id = ?");
                    $updateStmt->execute([$user['user_id']]);

                    // Redirect based on user role
                    if ($user['is_admin'] == 1) {
                        header('Location: admin/dashboard.php');
                    } else {
                        header('Location: user/dashboard.php');
                    }
                    exit();
                } else {
                    $error = 'Your account is not active. Please contact support.';
                }
            } else {
                // Increment login attempts for failed login
                try {
                    $updateStmt = $pdo->prepare("UPDATE users SET login_attempts = login_attempts + 1 WHERE email = ?");
                    $updateStmt->execute([$email]);
                } catch (Exception $e) {
                    // Handle error silently
                }
                $error = 'Invalid email or password';
            }
        } catch (PDOException $e) {
            error_log("Login error details: " . $e->getMessage());
            $error = 'System error. Please try again later.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description"
        content="Secure login to your Oakshire Finance account - Access your finances anytime, anywhere." />
    <title>Sign In | Oakshire Finance</title>
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
        href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700&display=swap"
        rel="stylesheet" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --primary-navy: #0a2540;
            --primary-dark: #0a1c2f;
            --primary-blue: #1a4d8c;
            --accent-blue: #2c7da0;
            --success-green: #2e7d32;
            --error-red: #dc3545;
            --warning-orange: #f39c12;
            --gray-50: #f8f9fc;
            --gray-100: #f1f3f9;
            --gray-200: #e9ecef;
            --gray-300: #dee2e6;
            --gray-400: #ced4da;
            --gray-500: #adb5bd;
            --gray-600: #6c757d;
            --gray-700: #495057;
            --gray-800: #343a40;
            --gray-900: #212529;
            --white: #ffffff;
            --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.08);
            --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.05);
            --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.08);
            --shadow-hover: 0 12px 28px rgba(0, 0, 0, 0.12);
            --transition: all 0.3s ease;
        }

        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            background: linear-gradient(135deg, var(--gray-50) 0%, var(--gray-100) 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 24px;
            position: relative;
            overflow-x: hidden;
        }

        /* Animated background */
        body::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" opacity="0.03"><path fill="%230a2540" d="M10,50 L90,50 M50,10 L50,90 M30,30 L70,70 M30,70 L70,30"/></svg>') repeat;
            pointer-events: none;
            animation: drift 60s linear infinite;
        }

        @keyframes drift {
            0% {
                background-position: 0 0;
            }

            100% {
                background-position: 1000px 1000px;
            }
        }

        .login-container {
            width: 100%;
            max-width: 480px;
            position: relative;
            z-index: 2;
        }

        /* Logo Section */
        .logo-section {
            text-align: center;
            margin-bottom: 32px;
            animation: fadeInUp 0.6s ease forwards;
        }

        .logo {
            display: inline-flex;
            align-items: center;
            gap: 10px;
            text-decoration: none;
            margin-bottom: 16px;
        }

        .logo-icon {
            width: 48px;
            height: 48px;
            background: var(--primary-navy);
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: var(--transition);
            animation: pulse 2s ease-in-out infinite;
        }

        @keyframes pulse {

            0%,
            100% {
                box-shadow: 0 0 0 0 rgba(10, 37, 64, 0.4);
            }

            50% {
                box-shadow: 0 0 0 8px rgba(10, 37, 64, 0);
            }
        }

        .logo-icon i {
            font-size: 24px;
            color: white;
        }

        .logo-text {
            font-size: 28px;
            font-weight: 700;
            color: var(--primary-navy);
            letter-spacing: -0.5px;
        }

        .logo-tagline {
            font-size: 14px;
            color: var(--gray-600);
            margin-top: 8px;
        }

        /* Card */
        .login-card {
            background: var(--white);
            border-radius: 24px;
            padding: 40px;
            box-shadow: var(--shadow-lg);
            animation: fadeInUp 0.6s ease 0.1s forwards;
            opacity: 0;
            transform: translateY(20px);
            animation: fadeInUp 0.6s ease 0.1s forwards;
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .login-header {
            text-align: center;
            margin-bottom: 32px;
        }

        .login-header h1 {
            font-size: 28px;
            font-weight: 700;
            color: var(--gray-900);
            margin-bottom: 8px;
        }

        .login-header p {
            font-size: 15px;
            color: var(--gray-600);
        }

        /* Alerts */
        .alert {
            padding: 14px 16px;
            border-radius: 12px;
            margin-bottom: 24px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 12px;
            animation: slideIn 0.4s ease;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateX(-10px);
            }

            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        .alert i {
            font-size: 18px;
        }

        .alert-danger {
            background: rgba(220, 53, 69, 0.1);
            border-left: 3px solid var(--error-red);
            color: var(--error-red);
        }

        .alert-warning {
            background: rgba(243, 156, 18, 0.1);
            border-left: 3px solid var(--warning-orange);
            color: var(--warning-orange);
        }

        .alert-success {
            background: rgba(46, 125, 50, 0.1);
            border-left: 3px solid var(--success-green);
            color: var(--success-green);
        }

        /* Form */
        .form-group {
            margin-bottom: 24px;
        }

        .input-wrapper {
            position: relative;
        }

        .input-icon {
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--gray-500);
            font-size: 18px;
            transition: var(--transition);
            pointer-events: none;
        }

        .input-wrapper input {
            width: 100%;
            padding: 14px 16px 14px 48px;
            font-size: 15px;
            font-family: 'Inter', sans-serif;
            border: 1.5px solid var(--gray-200);
            border-radius: 12px;
            background: var(--white);
            transition: var(--transition);
            outline: none;
            color: var(--gray-800);
        }

        .input-wrapper input:focus {
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 3px rgba(26, 77, 140, 0.1);
        }

        .input-wrapper input:focus+.input-icon {
            color: var(--primary-blue);
        }

        /* Password Toggle */
        .password-toggle {
            position: absolute;
            right: 16px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: var(--gray-500);
            cursor: pointer;
            font-size: 18px;
            transition: var(--transition);
        }

        .password-toggle:hover {
            color: var(--primary-blue);
        }

        /* Form Options */
        .form-options {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
            font-size: 14px;
        }

        .checkbox-label {
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
            color: var(--gray-700);
        }

        .checkbox-label input[type="checkbox"] {
            width: 16px;
            height: 16px;
            cursor: pointer;
            accent-color: var(--primary-blue);
        }

        .forgot-link {
            color: var(--primary-blue);
            text-decoration: none;
            font-weight: 500;
            transition: var(--transition);
        }

        .forgot-link:hover {
            color: var(--primary-navy);
            text-decoration: underline;
        }

        /* Button */
        .btn-login {
            width: 100%;
            padding: 14px;
            background: var(--primary-navy);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
            position: relative;
            overflow: hidden;
        }

        .btn-login::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.5s ease;
        }

        .btn-login:hover::before {
            left: 100%;
        }

        .btn-login:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        .btn-login:active {
            transform: translateY(0);
        }

        /* Register Link */
        .register-link {
            text-align: center;
            margin-top: 24px;
            padding-top: 24px;
            border-top: 1px solid var(--gray-200);
            font-size: 14px;
            color: var(--gray-600);
        }

        .register-link a {
            color: var(--primary-blue);
            text-decoration: none;
            font-weight: 600;
            transition: var(--transition);
        }

        .register-link a:hover {
            color: var(--primary-navy);
            text-decoration: underline;
        }

        /* Security Badge */
        .security-badge {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
            margin-top: 24px;
            padding: 16px;
            background: var(--gray-50);
            border-radius: 12px;
            font-size: 12px;
            color: var(--gray-600);
            text-align: center;
            animation: fadeInUp 0.6s ease 0.2s forwards;
            opacity: 0;
            transform: translateY(20px);
            animation: fadeInUp 0.6s ease 0.2s forwards;
        }

        .security-badge i {
            font-size: 16px;
            color: var(--success-green);
        }

        /* Responsive */
        @media (max-width: 560px) {
            body {
                padding: 16px;
            }

            .login-card {
                padding: 28px 24px;
            }

            .login-header h1 {
                font-size: 24px;
            }

            .logo-text {
                font-size: 24px;
            }

            .logo-icon {
                width: 40px;
                height: 40px;
            }

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

            .form-options {
                flex-direction: column;
                gap: 12px;
                align-items: flex-start;
            }
        }

        /* Loading state */
        .btn-login.loading {
            opacity: 0.7;
            cursor: not-allowed;
        }

        .btn-login.loading::after {
            content: '';
            position: absolute;
            width: 20px;
            height: 20px;
            top: 50%;
            left: 50%;
            margin-left: -10px;
            margin-top: -10px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-top-color: white;
            border-radius: 50%;
            animation: spin 0.6s linear infinite;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        /* Shake animation for error */
        @keyframes shake {

            0%,
            100% {
                transform: translateX(0);
            }

            25% {
                transform: translateX(-5px);
            }

            75% {
                transform: translateX(5px);
            }
        }

        .shake {
            animation: shake 0.3s ease;
        }
    </style>
    <link rel="stylesheet" href="assets/css/nexus-theme.css" />
</head>

<body>
    <div class="login-container">
        <div class="logo-section">
            <a href="index.php" class="logo">
                <div class="logo-icon">
                    <i class="fas fa-building-columns"></i>
                </div>
                <span class="logo-text">Oakshire Finance</span>
            </a>
            <div class="logo-tagline">Secure Banking • Trusted Since 2019</div>
        </div>

        <div class="login-card">
            <div class="login-header">
                <h1>Welcome back</h1>
                <p>Sign in to access your account</p>
            </div>

            <?php if ($error): ?>
                <div class="alert alert-danger" id="errorAlert">
                    <i class="fas fa-exclamation-circle"></i>
                    <span><?= htmlspecialchars($error) ?></span>
                </div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i>
                    <span><?= htmlspecialchars($success) ?></span>
                </div>
            <?php endif; ?>

            <form method="POST" id="loginForm">
                <div class="form-group">
                    <div class="input-wrapper">
                        <i class="fas fa-envelope input-icon"></i>
                        <input type="email" name="email" id="email" placeholder="Email address"
                            value="<?= htmlspecialchars($email) ?>" required autofocus>
                    </div>
                </div>

                <div class="form-group">
                    <div class="input-wrapper">
                        <i class="fas fa-lock input-icon"></i>
                        <input type="password" name="password" id="password" placeholder="Password" required>
                        <button type="button" class="password-toggle" id="togglePassword">
                            <i class="fas fa-eye-slash"></i>
                        </button>
                    </div>
                </div>

                <div class="form-options">
                    <label class="checkbox-label">
                        <input type="checkbox" name="remember" id="remember">
                        <span>Remember me</span>
                    </label>
                    <a href="forgot-password.php" class="forgot-link">Forgot password?</a>
                </div>

                <button type="submit" class="btn-login" id="loginBtn">
                    <i class="fas fa-arrow-right-to-bracket" style="margin-right: 8px;"></i>
                    Sign In
                </button>
            </form>

            <div class="register-link">
                Don't have an account? <a href="register.php">Open an account</a>
            </div>
        </div>

        <div class="security-badge">
            <i class="fas fa-shield-alt"></i>
            <span>256-bit SSL encryption • Your data is protected</span>
            <i class="fas fa-lock"></i>
        </div>
    </div>

    <script>
        // Password visibility toggle
        const togglePassword = document.getElementById('togglePassword');
        const passwordInput = document.getElementById('password');

        if (togglePassword && passwordInput) {
            togglePassword.addEventListener('click', function () {
                const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
                passwordInput.setAttribute('type', type);
                this.querySelector('i').classList.toggle('fa-eye');
                this.querySelector('i').classList.toggle('fa-eye-slash');
            });
        }

        // Form submission with loading state
        const loginForm = document.getElementById('loginForm');
        const loginBtn = document.getElementById('loginBtn');

        if (loginForm) {
            loginForm.addEventListener('submit', function (e) {
                const email = document.getElementById('email').value.trim();
                const password = document.getElementById('password').value;

                if (!email || !password) {
                    e.preventDefault();
                    showError('Please enter both email and password');
                    return;
                }

                if (!isValidEmail(email)) {
                    e.preventDefault();
                    showError('Please enter a valid email address');
                    return;
                }

                loginBtn.classList.add('loading');
                loginBtn.disabled = true;
            });
        }

        function isValidEmail(email) {
            const re = /^[^\s@]+@([^\s@]+\.)+[^\s@]+$/;
            return re.test(email);
        }

        function showError(message) {
            const existingAlert = document.querySelector('.alert-danger');
            if (existingAlert) {
                existingAlert.remove();
            }

            const alertDiv = document.createElement('div');
            alertDiv.className = 'alert alert-danger shake';
            alertDiv.innerHTML = `
                <i class="fas fa-exclamation-circle"></i>
                <span>${message}</span>
            `;

            const formHeader = document.querySelector('.login-header');
            formHeader.insertAdjacentElement('afterend', alertDiv);

            setTimeout(() => {
                alertDiv.classList.remove('shake');
            }, 300);

            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.style.opacity = '0';
                    setTimeout(() => alertDiv.remove(), 300);
                }
            }, 5000);
        }

        // Auto-dismiss success/error messages
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            setTimeout(() => {
                alert.style.transition = 'opacity 0.3s ease';
                alert.style.opacity = '0';
                setTimeout(() => alert.remove(), 300);
            }, 5000);
        });

        // Remember me functionality
        const rememberCheckbox = document.getElementById('remember');
        const emailInput = document.getElementById('email');

        if (localStorage.getItem('rememberedEmail') && rememberCheckbox) {
            emailInput.value = localStorage.getItem('rememberedEmail');
            rememberCheckbox.checked = true;
        }

        if (rememberCheckbox) {
            rememberCheckbox.addEventListener('change', function () {
                if (this.checked) {
                    localStorage.setItem('rememberedEmail', emailInput.value);
                } else {
                    localStorage.removeItem('rememberedEmail');
                }
            });
        }

        // Save email when typing if remember is checked
        if (emailInput && rememberCheckbox) {
            emailInput.addEventListener('input', function () {
                if (rememberCheckbox.checked) {
                    localStorage.setItem('rememberedEmail', this.value);
                }
            });
        }
    </script>
</body>

</html>