<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
require '../config/conn.php';
require '../vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Initialize error messages
$errors = [
    'email' => '',
    'password' => ''
];

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

// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $remember_me = isset($_POST['remember_me']) ? 1 : 0;

    // Basic validation
    if (empty($email)) {
        $errors['email'] = "Email is required";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = "Invalid email format";
    }

    if (empty($password)) {
        $errors['password'] = "Password is required";
    }

    // Only proceed with database check if no validation errors
    if (empty($errors['email']) && empty($errors['password'])) {
        // Check if vendor exists
        $stmt = $conn->prepare("SELECT id, vendor_id, business_name, email, password, is_verified, is_approved FROM vendors WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 1) {
            $vendor = $result->fetch_assoc();

            // Verify password
            if (password_verify($password, $vendor['password'])) {
                // Check if account is verified
                if (!$vendor['is_verified']) {
                    $errors['email'] = "Account not verified. Please check your email.";
                    $_SESSION['pending_verification_email'] = $email;
                } 
                // Check if account is approved
                elseif (!$vendor['is_approved']) {
                    $errors['email'] = "Your account is pending approval. Please contact support.";
                }
                else {
                    // Generate a 6-digit verification code
                    $verification_code = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
                    $expires_at = date('Y-m-d H:i:s', strtotime('+10 minutes'));
                    
                    // Store the code in the database
                    $stmt = $conn->prepare("INSERT INTO verification_codes (user_id, code, expires_at, user_type) VALUES (?, ?, ?, 'vendor')");
                    $stmt->bind_param("iss", $vendor['id'], $verification_code, $expires_at);
                    $stmt->execute();
                    
                    // Send the verification code via email
                    $mail = new PHPMailer(true);
                    try {
                        // Server settings
                        $mail->isSMTP();
                        $mail->Host       = 'smtp.gmail.com';
                        $mail->SMTPAuth   = true;
                        $mail->Username   = 'holuwaseunisrael@gmail.com';
                        $mail->Password   = 'ceae tepn tfyx oxjn';
                        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                        $mail->Port       = 465;
                        
                        // Recipients
                        $mail->setFrom('noreply@Athenian.com', 'Athenian University');
                        $mail->addAddress($email, $vendor['business_name']);
                        
                        // Content
                        $mail->isHTML(true);
                        $mail->Subject = 'Your Vendor Login Verification Code';
                        
                        $mail->Body = "
                        <div style='max-width: 600px; margin: 0 auto; border: 1px solid #e0e0e0; border-radius: 8px; overflow: hidden;'>
                            <div style='background-color: #FBBB01; padding: 25px; text-align: center;'>
                                <h1 style='color: white; margin: 0; font-size: 24px;'>Login Verification</h1>
                            </div>
                            
                            <div style='padding: 25px;'>
                                <h2 style='color: #FBBB01; margin-top: 0;'>Hello {$vendor['business_name']},</h2>
                                
                                <p style='font-size: 16px;'>Your vendor login verification code is:</p>
                                
                                <div style='text-align: center; margin: 25px 0;'>
                                    <div style='display: inline-block; padding: 15px 30px; background-color: #f5f5f5; border: 2px dashed #FBBB01; border-radius: 5px; font-size: 24px; font-weight: bold; letter-spacing: 5px;'>
                                        $verification_code
                                    </div>
                                </div>
                                
                                <p style='font-size: 14px; color: #666;'>This code will expire in 10 minutes. Please do not share this code with anyone.</p>
                                
                                <div style='background-color: #f5f5f5; padding: 15px; border-radius: 5px; margin-top: 20px;'>
                                    <p style='margin: 0; font-size: 13px; color: #666;'>If you didn't request this code, please secure your account immediately.</p>
                                </div>
                            </div>
                            
                            <div style='background-color: #f5f5f5; padding: 15px; text-align: center; font-size: 12px; color: #666;'>
                                <p>© " . date('Y') . " Athenian University. All rights reserved.</p>
                            </div>
                        </div>
                        ";
                        
                        $mail->AltBody = "Hello {$vendor['business_name']},\n\n"
                            . "Your vendor login verification code is: $verification_code\n\n"
                            . "This code will expire in 10 minutes. Please do not share this code with anyone.\n\n"
                            . "If you didn't request this code, please secure your account immediately.\n\n"
                            . "Best regards,\n"
                            . "Athenian University";
                        
                        $mail->send();
                        
                        // Store vendor ID in session for verification
                        $_SESSION['2fa_vendor_id'] = $vendor['id'];
                        $_SESSION['2fa_remember_me'] = $remember_me;
                        
                        // Redirect to verification page
                        header("Location: vendor_verify_code.php");
                        exit();
                        
                    } catch (Exception $e) {
                        $errors['email'] = "Failed to send verification code. Please try again later.";
                    }
                }
            } else {
                $errors['password'] = "Incorrect password";
            }
        } else {
            $errors['email'] = "Email not registered";
        }
    }
}

// Display verification messages
if (isset($_SESSION['verification_success'])) {
    $verification_success = $_SESSION['verification_success'];
    unset($_SESSION['verification_success']);
}

if (isset($_SESSION['verification_error'])) {
    $verification_error = $_SESSION['verification_error'];
    $pending_verification_email = $_SESSION['pending_verification_email'] ?? null;
    unset($_SESSION['verification_error']);
    unset($_SESSION['pending_verification_email']);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vendor Portal - Login</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        @layer components {
            .btn-primary {
                background-color: #fbbb01;
            }
            .btn-primary:hover {
                background-color: #e0a800;
            }
            .input-focus:focus {
                border-color: #fbbb01;
                ring-color: #fbbb01;
            }
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center p-5 font-['Poppins']">
    <div class="w-full max-w-[1200px] flex flex-col items-center">
        <!-- School Logo - Replace with your actual logo -->
        <div class="mb-8">
            <img src="path/to/your/logo.png" alt="School Logo" class="h-20 mx-auto">
        </div>

        <div class="text-center mb-8">
            <h1 class="text-4xl font-bold mb-2 bg-gradient-to-r from-[#fbbb01] to-[#ffcc33] bg-clip-text text-transparent">Vendor Portal</h1>
            <p class="text-gray-600 text-lg">Sign in to access your vendor dashboard</p>
        </div>

        <!-- Display verification messages -->
        <?php if (isset($verification_success)): ?>
            <div class="bg-green-50 border-l-4 border-green-500 p-5 rounded-lg mb-8 w-full max-w-md">
                <h3 class="text-green-700 font-bold mb-2"><i class="fas fa-check-circle mr-2"></i> Verification Successful</h3>
                <p class="text-green-700 mb-3"><?php echo htmlspecialchars($verification_success); ?></p>
                <a href="vendor_login.php" class="inline-block bg-green-600 text-white px-4 py-2 rounded font-medium hover:bg-green-700">Proceed to Login</a>
            </div>
        <?php endif; ?>
        
        <?php if (isset($verification_error)): ?>
            <div class="bg-red-50 border-l-4 border-red-500 p-4 rounded-lg mb-6 w-full max-w-md text-red-700">
                <?php echo htmlspecialchars($verification_error); ?>
                <?php if (isset($pending_verification_email)): ?>
                    <div class="mt-3">
                        <button type="button" id="showResendModal" class="text-[#fbbb01] underline hover:text-[#e0a800] text-sm">Resend verification code</button>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>
        
        <!-- Error message from login attempt -->
        <?php if (!empty($errors['email']) && strpos($errors['email'], 'Account not verified') !== false && isset($_SESSION['pending_verification_email'])): ?>
            <div class="bg-red-50 border-l-4 border-red-500 p-4 rounded-lg mb-6 w-full max-w-md text-red-700">
                <?php echo htmlspecialchars($errors['email']); ?>
                <div class="mt-3">
                    <button type="button" id="showResendModal" class="text-[#fbbb01] underline hover:text-[#e0a800] text-sm">Resend verification code</button>
                </div>
            </div>
        <?php endif; ?>
        
        <div class="flex border-b-2 border-gray-300 mb-8 w-full max-w-md">
            <div class="flex-1 text-center py-4 font-medium text-[#fbbb01] border-b-2 border-[#fbbb01]">Login</div>
            <a href="vendor_registration.php" class="flex-1 text-center py-4 font-medium text-gray-500 hover:text-gray-700">Register</a>
        </div>

        <div class="w-full max-w-md">
            <form class="bg-white rounded-lg shadow-md p-8" method="POST">
                <div class="mb-6">
                    <label for="loginEmail" class="block text-gray-700 font-medium mb-2">Email Address</label>
                    <div class="relative">
                        <i class="fas fa-envelope absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                        <input type="email" id="loginEmail" name="email" class="w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#fbbb01] focus:border-[#fbbb01] input-focus"
                               value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>" required>
                    </div>
                    <?php if (!empty($errors['email']) && strpos($errors['email'], 'Account not verified') === false && strpos($errors['email'], 'pending approval') === false): ?>
                        <small class="text-red-600 text-sm mt-1 block"><?php echo htmlspecialchars($errors['email']); ?></small>
                    <?php endif; ?>
                </div>
                
                <div class="mb-6">
                    <label for="loginPassword" class="block text-gray-700 font-medium mb-2">Password</label>
                    <div class="relative">
                        <i class="fas fa-lock absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                        <input type="password" id="loginPassword" name="password" class="w-full pl-10 pr-10 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#fbbb01] focus:border-[#fbbb01] input-focus" required>
                        <i class="fas fa-eye absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 cursor-pointer" onclick="togglePasswordVisibility()"></i>
                    </div>
                    <?php if (!empty($errors['password'])): ?>
                        <small class="text-red-600 text-sm mt-1 block"><?php echo htmlspecialchars($errors['password']); ?></small>
                    <?php endif; ?>
                </div>
                
                <div class="flex justify-between items-center mb-6 text-sm">
                    <div class="flex items-center">
                        <input type="checkbox" id="rememberMe" name="remember_me" value="1" class="mr-2">
                        <label for="rememberMe" class="text-gray-600">Remember me</label>
                    </div>
                    <a href="vendor_forgot_password.php" class="text-[#fbbb01] hover:text-[#e0a800] hover:underline">Forgot password?</a>
                </div>
                
                <button type="submit" class="w-full py-3 px-4 bg-[#fbbb01] text-white font-medium rounded-lg hover:bg-[#e0a800] transition duration-200" name="login">
                    Sign In
                </button>
            </form>
        </div>
    </div>

    <!-- Resend Verification Modal -->
    <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden" id="resendModal">
        <div class="bg-white rounded-lg p-6 w-full max-w-md relative">
            <span class="absolute top-4 right-4 text-gray-500 cursor-pointer text-2xl" id="closeModal">&times;</span>
            <h3 class="text-xl font-bold text-gray-800 mb-4">Resend Verification Code</h3>
            <p class="text-gray-600 mb-6">A new verification code will be sent to your email address. Do you want to proceed?</p>
            <form id="resendVerificationForm" method="post" action="vendor_resend_verification.php">
                <input type="hidden" name="email" value="<?php echo isset($_SESSION['pending_verification_email']) ? htmlspecialchars($_SESSION['pending_verification_email']) : (isset($pending_verification_email) ? htmlspecialchars($pending_verification_email) : ''); ?>">
                <div class="flex justify-end space-x-3">
                    <button type="button" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50" id="cancelResend">Cancel</button>
                    <button type="submit" class="px-4 py-2 bg-[#fbbb01] text-white rounded-lg hover:bg-[#e0a800]" name="resend_verification">Resend</button>
                </div>
            </form>
        </div>
    </div>

    <script>
    // Password visibility toggle
    function togglePasswordVisibility() {
        const passwordInput = document.getElementById('loginPassword');
        const icon = document.querySelector('#loginPassword + .fa-eye');
        
        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        } else {
            passwordInput.type = 'password';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        }
    }
    
    // Modal handling
    document.addEventListener('DOMContentLoaded', function() {
        const modal = document.getElementById('resendModal');
        const showModalBtn = document.getElementById('showResendModal');
        const closeModalBtn = document.getElementById('closeModal');
        const cancelBtn = document.getElementById('cancelResend');
        const resendForm = document.getElementById('resendVerificationForm');
        
        if (showModalBtn) {
            showModalBtn.addEventListener('click', function() {
                modal.classList.remove('hidden');
            });
        }
        
        if (closeModalBtn) {
            closeModalBtn.addEventListener('click', function() {
                modal.classList.add('hidden');
            });
        }
        
        if (cancelBtn) {
            cancelBtn.addEventListener('click', function() {
                modal.classList.add('hidden');
            });
        }
        
        // Close modal when clicking outside
        window.addEventListener('click', function(event) {
            if (event.target === modal) {
                modal.classList.add('hidden');
            }
        });
    });
    </script>
</body>3
</html>w3