<?php
session_start();
require_once '../connection.php';
require_once '../site-details.php';

// Initialize variables
$error = '';
$success = '';

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

// Process form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Store form data
    $username_email = $_POST['username_email'] ?? '';
    $password = $_POST['password'] ?? '';
    
    // Validate fields
    if (empty($username_email) || empty($password)) {
        $error = 'Please enter both username/email and password!';
    } else {
        // Check if user exists
        $stmt = $conn->prepare("SELECT id, username, email, password, email_verified, account_status FROM users WHERE username = ? OR email = ?");
        $stmt->bind_param("ss", $username_email, $username_email);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $user = $result->fetch_assoc();
            
            // Verify password
            if (password_verify($password, $user['password'])) {
                // Check if email is verified
                if ($user['email_verified'] == 0) {
                    $error = 'Please verify your email address before logging in. Check your email for the verification link.';
                } 
                // Check account status
                elseif ($user['account_status'] == 'suspended') {
                    $error = 'Your account has been suspended. Please contact support.';
                }
                elseif ($user['account_status'] == 'blocked') {
                    $error = 'Your account has been blocked. Please contact support.';
                }
                else {
                    // Login successful
                    
                    // Update last login
                    $update = $conn->prepare("UPDATE users SET last_login = NOW(), login_attempts = 0 WHERE id = ?");
                    $update->bind_param("i", $user['id']);
                    $update->execute();
                    $update->close();
                    
                    // Set session variables
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['username'] = $user['username'];
                    $_SESSION['email'] = $user['email'];
                    $_SESSION['verified'] = ($user['email_verified'] == 1);
                    
                    // Set welcome back message
                    $_SESSION['success_message'] = "Welcome back, " . $user['username'] . "!";
                    
                    // Redirect to account dashboard
                    header("Location: index.php");
                    exit();
                }
            } else {
                // Increment login attempts
                $update = $conn->prepare("UPDATE users SET login_attempts = login_attempts + 1 WHERE id = ?");
                $update->bind_param("i", $user['id']);
                $update->execute();
                $update->close();
                
                $error = 'Invalid username/email or password!';
            }
        } else {
            $error = 'Invalid username/email or password!';
        }
        $stmt->close();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mexes Trade - Login</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #0a0f1c;
        }
        /* Custom scrollbar for dark theme */
        ::-webkit-scrollbar {
            width: 8px;
        }
        ::-webkit-scrollbar-track {
            background: #0a0f1c;
        }
        ::-webkit-scrollbar-thumb {
            background: #1f2937;
            border-radius: 10px;
        }
        .alert-success {
            background-color: #10b981;
            border-color: #059669;
        }
        .alert-error {
            background-color: #ef4444;
            border-color: #dc2626;
        }
    </style>
</head>
<body class="text-white antialiased">

    <div class="min-h-screen flex flex-col items-center justify-center p-4 md:p-10">
        
        <div class="text-center mb-10">
            <div class="flex flex-col items-center mb-4">
                <div class="flex items-center gap-1">
                    <a href="../index.php">
                   <img src="../<?php echo $LOGO_PATH; ?>" class="img-fluid">
                   </a>
                </div>
               
            </div>
            
           
            <p class="text-gray-400 text-lg">Sign in to continue your trading journey</p>
        </div>

        <?php if ($error): ?>
            <div class="w-full max-w-md mb-6">
                <div class="alert-error border rounded-2xl p-4 text-center">
                    <i class="fas fa-exclamation-circle mr-2"></i> <?php echo htmlspecialchars($error); ?>
                </div>
            </div>
        <?php endif; ?>
        
        <?php if ($success): ?>
            <div class="w-full max-w-md mb-6">
                <div class="alert-success border rounded-2xl p-4 text-center">
                    <i class="fas fa-check-circle mr-2"></i> <?php echo htmlspecialchars($success); ?>
                </div>
            </div>
        <?php endif; ?>

        <div class="w-full max-w-md bg-[#111827] border border-gray-800 rounded-[2.5rem] p-8 md:p-10 shadow-2xl">
            
            <div class="inline-flex items-center bg-[#1e293b] rounded-2xl px-5 py-3 mb-8 border border-gray-700/50">
                <div class="text-blue-400 bg-blue-400/10 p-2 rounded-lg mr-4">
                    <i class="fas fa-sign-in-alt text-lg"></i>
                </div>
                <div>
                    <div class="text-blue-400 font-bold text-sm leading-tight">Secure Login</div>
                    <div class="text-gray-400 text-xs">Protected by 256-bit encryption</div>
                </div>
            </div>

            <form action="" method="POST" class="space-y-8">
                
                <!-- Login Credentials -->
                <div class="space-y-6">
                    <div class="space-y-2">
                        <label class="block text-sm font-semibold text-gray-300 ml-1">
                            Username or Email <span class="text-red-500">*</span>
                        </label>
                        <div class="relative group">
                            <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                <i class="far fa-user text-gray-500 group-focus-within:text-blue-400 transition-colors"></i>
                            </div>
                            <input type="text" name="username_email" placeholder="Enter username or email" 
                                class="w-full bg-[#0a0f1c] border border-gray-700 rounded-2xl py-4 pl-12 pr-4 focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 focus:outline-none transition-all placeholder:text-gray-600"
                                value="<?php echo htmlspecialchars($_POST['username_email'] ?? ''); ?>" required>
                        </div>
                    </div>

                    <div class="space-y-2">
                        <label class="block text-sm font-semibold text-gray-300 ml-1">
                            Password <span class="text-red-500">*</span>
                        </label>
                        <div class="relative group">
                            <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                <i class="fas fa-lock text-gray-500 group-focus-within:text-blue-400 transition-colors"></i>
                            </div>
                            <input type="password" name="password" placeholder="Enter your password" 
                                class="w-full bg-[#0a0f1c] border border-gray-700 rounded-2xl py-4 pl-12 pr-4 focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 focus:outline-none transition-all placeholder:text-gray-600" required>
                            <div class="absolute inset-y-0 right-0 pr-4 flex items-center">
                                <button type="button" class="text-gray-500 hover:text-gray-300 toggle-password" data-target="password">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="flex items-center justify-between">
                        <div class="flex items-center">
                            <input type="checkbox" name="remember" id="remember" 
                                class="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500 focus:ring-2">
                            <label for="remember" class="ml-2 text-sm text-gray-300">
                                Remember me
                            </label>
                        </div>
                        <!--
                        <a href="forgot-password.php" class="text-blue-400 hover:text-blue-300 text-sm font-medium">
                            Forgot Password?
                        </a>
                        -->
                    </div>
                </div>

                <div class="pt-4">
                    <hr class="border-gray-800">
                </div>

                <div class="space-y-4">
                    <button type="submit" 
                        class="w-full bg-green-600 hover:bg-green-500 text-white font-bold py-4 px-6 rounded-2xl flex items-center justify-center gap-3 transition-all transform active:scale-95 shadow-xl shadow-green-600/20">
                        Sign In 
                        <i class="fas fa-sign-in-alt text-sm"></i>
                    </button>

                    <div class="relative flex items-center justify-center">
                        <hr class="w-full border-gray-800">
                        <span class="absolute bg-[#111827] px-4 text-gray-500 text-sm">or continue with</span>
                    </div>

                    <a href="register.php" 
                        class="w-full bg-[#1e293b] hover:bg-[#2d3748] text-white font-bold py-3 px-6 rounded-2xl flex items-center justify-center gap-3 transition-all border border-gray-700/50">
                        <i class="fas fa-user-plus text-blue-400"></i>
                        Create New Account
                    </a>
                </div>
            </form>

<!--
            <div class="mt-8 text-center">
                <span class="text-gray-400 text-sm">By signing in, you agree to our </span>
                <a href="#" class="text-blue-400 hover:text-blue-300 underline">Terms & Conditions</a>
                <span class="text-gray-400 text-sm"> and </span>
                <a href="#" class="text-blue-400 hover:text-blue-300 underline">Privacy Policy</a>
            </div>
            -->
        </div>

        <footer class="mt-12 w-full max-w-md text-center">
            <div class="flex flex-wrap justify-center gap-6 md:gap-10 mb-8">
                <div class="flex items-center gap-2 text-[11px] font-bold text-gray-500 uppercase tracking-widest">
                    <i class="fas fa-shield-halved text-gray-600"></i>
                    SSL Secured
                </div>
                <div class="flex items-center gap-2 text-[11px] font-bold text-gray-500 uppercase tracking-widest">
                    <i class="fas fa-lock text-gray-600"></i>
                    256-bit Encryption
                </div>
                <div class="flex items-center gap-2 text-[11px] font-bold text-gray-500 uppercase tracking-widest">
                    <i class="fas fa-circle-check text-gray-600"></i>
                    Regulated Platform
                </div>
            </div>
            
            <div class="text-[11px] text-gray-600 leading-relaxed">
                © 2026 Remedy. All rights reserved. | Licensed and regulated trading platform.
            </div>
        </footer>

    </div>

    <script>
        // Toggle password visibility
        document.querySelectorAll('.toggle-password').forEach(button => {
            button.addEventListener('click', function() {
                const target = this.getAttribute('data-target');
                const input = document.querySelector(`input[name="${target}"]`);
                const icon = this.querySelector('i');
                
                if (input.type === 'password') {
                    input.type = 'text';
                    icon.classList.remove('fa-eye');
                    icon.classList.add('fa-eye-slash');
                } else {
                    input.type = 'password';
                    icon.classList.remove('fa-eye-slash');
                    icon.classList.add('fa-eye');
                }
            });
        });

        // Prevent form resubmission on page refresh
        if (window.history.replaceState) {
            window.history.replaceState(null, null, window.location.href);
        }

        // Focus on first invalid field when there's an error
        <?php if ($error): ?>
            setTimeout(function() {
                const form = document.querySelector('form');
                const firstInvalid = form.querySelector('input:invalid');
                if (firstInvalid) {
                    firstInvalid.focus();
                }
            }, 100);
        <?php endif; ?>

        // Auto-focus on username/email field
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelector('input[name="username_email"]').focus();
        });
    </script>
 
</body>
</html>