<?php
ob_start();
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';

if (!isset($_SESSION['2fa_vendor_id'])) {
    header("Location: vendor_login.php");
    exit();
}

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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify code submission
    if (isset($_POST['verify'])) {
        $code = trim($_POST['code'] ?? '');
        
        if (empty($code)) {
            $error = "Verification code is required";
        } elseif (!preg_match('/^\d{6}$/', $code)) {
            $error = "Invalid code format. Please enter a 6-digit number.";
        } else {
            $stmt = $conn->prepare("SELECT vc.*, v.* 
                                   FROM verification_codes vc
                                   JOIN vendors v ON vc.user_id = v.id
                                   WHERE vc.user_id = ? AND vc.code = ? AND vc.expires_at > NOW() AND vc.used = 0
                                   ORDER BY vc.created_at DESC LIMIT 1");
            $stmt->bind_param("is", $_SESSION['2fa_vendor_id'], $code);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows === 1) {
                $row = $result->fetch_assoc();
                
                // Mark code as used
                $update_stmt = $conn->prepare("UPDATE verification_codes SET used = 1 WHERE id = ?");
                $update_stmt->bind_param("i", $row['id']);
                if ($update_stmt->execute()) {
                    // Regenerate session ID
                    session_regenerate_id(true);
                    
                    // Set session variables
                    $_SESSION['vendor_id'] = $row['id'];
                    $_SESSION['vendor_vendor_id'] = $row['vendor_id'];
                    $_SESSION['business_name'] = $row['business_name'];
                    $_SESSION['vendor_email'] = $row['email'];
                    $_SESSION['vendor_logged_in'] = true;
                    $_SESSION['vendor_last_activity'] = time();

                    // Remember me functionality
                    if (isset($_SESSION['2fa_remember_me']) && $_SESSION['2fa_remember_me']) {
                        $token = bin2hex(random_bytes(32));
                        $expiry = date('Y-m-d H:i:s', strtotime('+30 days'));
                        
                        $stmt = $conn->prepare("INSERT INTO remember_tokens (user_id, token, expires_at) VALUES (?, ?, ?)");
                        $stmt->bind_param("iss", $row['id'], $token, $expiry);
                        $stmt->execute();
                        
                        setcookie('vendor_remember_token', $token, time() + (30 * 24 * 60 * 60), '/', '', true, true);
                    }

                    // Record login history
                    $ip_address = $_SERVER['REMOTE_ADDR'];
                    $device_info = $_SERVER['HTTP_USER_AGENT'];
                    
                    $login_stmt = $conn->prepare("INSERT INTO login_history (user_id, ip_address, device_info) VALUES (?, ?, ?)");
                    $login_stmt->bind_param("iss", $row['id'], $ip_address, $device_info);
                    $login_stmt->execute();
                    
                    // Update last login
                    $update_stmt = $conn->prepare("UPDATE vendors SET last_login = NOW() WHERE id = ?");
                    $update_stmt->bind_param("i", $row['id']);
                    $update_stmt->execute();

                    // Clear 2FA session
                    unset($_SESSION['2fa_vendor_id']);
                    unset($_SESSION['2fa_remember_me']);
                    
                    // Ensure no output before header
                    ob_end_clean();
                    header("Location: index.php");
                    exit();
                } else {
                    $error = "System error during verification. Please try again.";
                }
            } else {
                $error = "Invalid verification code or code has expired";
            }
        }
    }
    
    // Resend code functionality
    if (isset($_POST['resend'])) {
        // Generate a new 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 new code in the database
        $stmt = $conn->prepare("INSERT INTO verification_codes (user_id, code, expires_at) VALUES (?, ?, ?)");
        $stmt->bind_param("iss", $_SESSION['2fa_vendor_id'], $verification_code, $expires_at);
        $stmt->execute();
        
        // Get vendor details
        $vendor_stmt = $conn->prepare("SELECT business_name, email FROM vendors WHERE id = ?");
        $vendor_stmt->bind_param("i", $_SESSION['2fa_vendor_id']);
        $vendor_stmt->execute();
        $vendor_result = $vendor_stmt->get_result();
        $vendor = $vendor_result->fetch_assoc();
        
        // Send the new verification code via email
        $mail = new PHPMailer\PHPMailer\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\PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port       = 465;
            
            // Recipients
            $mail->setFrom('noreply@Athenian.com', 'Athenian University');
            $mail->addAddress($vendor['email'], $vendor['business_name']);
            
            // Content
            $mail->isHTML(true);
            $mail->Subject = 'Your New 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;'>New Verification Code</h1>
                </div>
                
                <div style='padding: 25px;'>
                    <h2 style='color: #FBBB01; margin-top: 0;'>Hello {$vendor['business_name']},</h2>
                    
                    <p style='font-size: 16px;'>Your new 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>
                
                <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 new 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"
                . "Best regards,\n"
                . "Athenian University";
            
            $mail->send();
            
            $success = "A new verification code has been sent to your email.";
        } catch (Exception $e) {
            $error = "Failed to send new verification code. Please try again later.";
        }
        
        // Redirect to avoid form resubmission
        header("Location: vendor_verify_code.php");
        exit();
    }
}

ob_end_flush();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify Your Identity | Athenian University</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>
        .btn-primary {
            background-color: #fbbb01;
        }
        .btn-primary:hover {
            background-color: #e0a800;
        }
        .input-focus:focus {
            border-color: #fbbb01;
            ring-color: #fbbb01;
        }
        body {
            font-family: 'Poppins', sans-serif;
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center p-5">
    <div class="w-full max-w-md">
        <div class="bg-white rounded-lg shadow-md p-8">
            <div class="text-center mb-6">
                <h1 class="text-2xl font-bold text-gray-800 mb-2">Verify Your Identity</h1>
                <p class="text-gray-600">We've sent a 6-digit code to your email address</p>
            </div>
            
            <?php if ($error): ?>
                <div class="bg-red-50 border-l-4 border-red-500 p-4 rounded-lg mb-6 text-red-700">
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>
            
            <?php if ($success): ?>
                <div class="bg-green-50 border-l-4 border-green-500 p-4 rounded-lg mb-6 text-green-700">
                    <?php echo htmlspecialchars($success); ?>
                </div>
            <?php endif; ?>
            
            <form method="POST" action="vendor_verify_code.php">
                <div class="mb-6">
                    <label for="code" class="block text-gray-700 font-medium mb-2">Verification Code</label>
                    <input type="text" id="code" name="code" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#fbbb01] focus:border-[#fbbb01] input-focus"
                           maxlength="6" pattern="\d{6}" title="Please enter a 6-digit code" required autofocus>
                    <small class="text-gray-500 text-sm mt-1 block">Enter the 6-digit code sent to your email</small>
                </div>
                
                <button type="submit" name="verify" class="w-full py-3 px-4 bg-[#fbbb01] text-white font-medium rounded-lg hover:bg-[#e0a800] transition duration-200 mb-4">
                    Verify & Continue
                </button>
                
                <div class="text-center text-sm text-gray-600">
                    <p>Didn't receive a code? 
                        <button type="submit" name="resend" class="text-[#fbbb01] hover:text-[#e0a800] hover:underline focus:outline-none">
                            Resend Code
                        </button>
                    </p>
                </div>
            </form>
        </div>
        
        <div class="text-center mt-6">
            <a href="vendor_login.php" class="text-[#fbbb01] hover:text-[#e0a800] hover:underline">Back to Login</a>
        </div>
    </div>
    
    <script>
    document.getElementById('code').addEventListener('input', function(e) {
        this.value = this.value.replace(/[^0-9]/g, '').substring(0, 6);
    });
    </script>
</body>
</html>