<?php
// Ensure no output before session_start
if (ob_get_level()) { ob_end_clean(); }
ob_start();
session_start();
require_once 'config.php';

$error_message = '';
$success_message = '';

// Check if user has a valid reset session
if (!isset($_SESSION['password_reset_token']) || !isset($_SESSION['password_reset_email']) || !isset($_SESSION['password_reset_user_id'])) {
    header('Location: forgot_password.php');
    exit();
}

$email = $_SESSION['password_reset_email'];
$user_id = $_SESSION['password_reset_user_id'];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $otp_code = isset($_POST['otp_code']) ? trim($_POST['otp_code']) : '';
    
    if (empty($otp_code)) {
        $error_message = "Please enter the OTP code.";
    } elseif (!preg_match('/^\d{6}$/', $otp_code)) {
        $error_message = "Please enter a valid 6-digit OTP code.";
    } else {
        // Verify OTP
        $stmt = $conn->prepare("
            SELECT id, otp_code, attempts, max_attempts, expires_at, used_at 
            FROM password_reset_tokens 
            WHERE user_id = ? AND email = ? AND expires_at > NOW() AND used_at IS NULL
            ORDER BY created_at DESC 
            LIMIT 1
        ");
        $stmt->bind_param("is", $user_id, $email);
        $stmt->execute();
        $result = $stmt->get_result();
        $token_data = $result->fetch_assoc();
        $stmt->close();
        
        if ($token_data) {
            // Check if max attempts reached
            if ($token_data['attempts'] >= $token_data['max_attempts']) {
                $error_message = "Maximum attempts reached. Please request a new OTP.";
                
                // Clean up this token
                $cleanup_stmt = $conn->prepare("DELETE FROM password_reset_tokens WHERE id = ?");
                $cleanup_stmt->bind_param("i", $token_data['id']);
                $cleanup_stmt->execute();
                $cleanup_stmt->close();
                
                // Clear session
                unset($_SESSION['password_reset_token']);
                unset($_SESSION['password_reset_email']);
                unset($_SESSION['password_reset_user_id']);
            } else {
                // Check if OTP matches
                if ($token_data['otp_code'] === $otp_code) {
                    // Mark token as used
                    $update_stmt = $conn->prepare("UPDATE password_reset_tokens SET used_at = NOW() WHERE id = ?");
                    $update_stmt->bind_param("i", $token_data['id']);
                    $update_stmt->execute();
                    $update_stmt->close();
                    
                    // Redirect to password reset form
                    header('Location: reset_password.php');
                    exit();
                } else {
                    // Increment attempts
                    $attempt_stmt = $conn->prepare("UPDATE password_reset_tokens SET attempts = attempts + 1 WHERE id = ?");
                    $attempt_stmt->bind_param("i", $token_data['id']);
                    $attempt_stmt->execute();
                    $attempt_stmt->close();
                    
                    $remaining_attempts = $token_data['max_attempts'] - ($token_data['attempts'] + 1);
                    if ($remaining_attempts > 0) {
                        $error_message = "Invalid OTP code. You have " . $remaining_attempts . " attempts remaining.";
                    } else {
                        $error_message = "Invalid OTP code. Maximum attempts reached. Please request a new OTP.";
                        
                        // Clean up this token
                        $cleanup_stmt = $conn->prepare("DELETE FROM password_reset_tokens WHERE id = ?");
                        $cleanup_stmt->bind_param("i", $token_data['id']);
                        $cleanup_stmt->execute();
                        $cleanup_stmt->close();
                        
                        // Clear session
                        unset($_SESSION['password_reset_token']);
                        unset($_SESSION['password_reset_email']);
                        unset($_SESSION['password_reset_user_id']);
                    }
                }
            }
        } else {
            $error_message = "Invalid or expired OTP. Please request a new one.";
            
            // Clear session
            unset($_SESSION['password_reset_token']);
            unset($_SESSION['password_reset_email']);
            unset($_SESSION['password_reset_user_id']);
        }
    }
}

// Get contact configuration
require_once 'app/classes/ContactConfig.php';
$contactConfig = new ContactConfig($conn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
    <title>Verify OTP | D-Bundles Stores</title>
    <meta name="description" content="Verify your OTP code to reset your D-Bundles Stores agent account password.">
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&family=Space+Grotesk:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        'poppins': ['Poppins', 'sans-serif'],
                        'space': ['Space Grotesk', 'sans-serif'],
                    },
                    colors: {
                        primary: {
                            50: '#f0f9ff',
                            100: '#e0f2fe',
                            200: '#bae6fd',
                            300: '#7dd3fc',
                            400: '#38bdf8',
                            500: '#0ea5e9',
                            600: '#0284c7',
                            700: '#0369a1',
                            800: '#075985',
                            900: '#0c4a6e',
                        },
                        accent: {
                            50: '#fdf4ff',
                            100: '#fae8ff',
                            200: '#f5d0fe',
                            300: '#f0abfc',
                            400: '#e879f9',
                            500: '#d946ef',
                            600: '#c026d3',
                            700: '#a21caf',
                            800: '#86198f',
                            900: '#701a75',
                        },
                        dark: {
                            50: '#f8fafc',
                            100: '#f1f5f9',
                            200: '#e2e8f0',
                            300: '#cbd5e1',
                            400: '#94a3b8',
                            500: '#64748b',
                            600: '#475569',
                            700: '#334155',
                            800: '#1e293b',
                            900: '#0f172a',
                        }
                    },
                    animation: {
                        'float': 'float 6s ease-in-out infinite',
                        'glow': 'glow 2s ease-in-out infinite alternate',
                        'pulse': 'pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite',
                    },
                    keyframes: {
                        float: {
                            '0%, 100%': { transform: 'translateY(0px)' },
                            '50%': { transform: 'translateY(-20px)' },
                        },
                        glow: {
                            '0%': { boxShadow: '0 0 20px rgba(217, 70, 239, 0.3)' },
                            '100%': { boxShadow: '0 0 30px rgba(217, 70, 239, 0.6)' },
                        }
                    }
                }
            }
        }
    </script>
</head>

<body class="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-purple-50 font-poppins">
    <!-- Background Pattern -->
    <div class="fixed inset-0 opacity-5">
        <div class="absolute inset-0" style="background-image: radial-gradient(circle at 25% 25%, #3b82f6 0%, transparent 50%), radial-gradient(circle at 75% 75%, #d946ef 0%, transparent 50%);"></div>
    </div>
    
    <div class="relative min-h-screen flex">
        <!-- Left Column - Information -->
        <div class="hidden lg:flex lg:w-1/2 relative overflow-hidden">
            <!-- Animated Background -->
            <div class="absolute inset-0 bg-gradient-to-br from-primary-600 via-accent-600 to-primary-800">
                <div class="absolute inset-0 bg-black bg-opacity-20"></div>
                <!-- Floating Elements -->
                <div class="absolute top-20 left-20 w-32 h-32 bg-white bg-opacity-10 rounded-full animate-float"></div>
                <div class="absolute top-40 right-32 w-24 h-24 bg-white bg-opacity-5 rounded-full animate-float" style="animation-delay: -2s;"></div>
                <div class="absolute bottom-32 left-16 w-20 h-20 bg-white bg-opacity-10 rounded-full animate-float" style="animation-delay: -4s;"></div>
                <div class="absolute bottom-20 right-20 w-28 h-28 bg-white bg-opacity-5 rounded-full animate-float" style="animation-delay: -1s;"></div>
            </div>
            
            <div class="relative z-10 flex flex-col justify-center px-12 py-12 w-full text-white">
                <!-- Logo and Branding -->
                <div class="mb-8">
                    <div class="flex items-center mb-6">
                        <div class="w-16 h-16 bg-white bg-opacity-20 backdrop-blur-sm rounded-2xl flex items-center justify-center mr-4 animate-glow">
                            <i class="fas fa-shield-check text-white text-2xl"></i>
                        </div>
                        <div>
                            <h1 class="text-3xl font-bold font-space">D-Bundles Stores</h1>
                            <p class="text-white text-opacity-80 text-sm font-medium">OTP Verification</p>
                        </div>
                    </div>
                    <h2 class="text-4xl font-bold font-space mb-3">Verify Your Identity</h2>
                    <p class="text-lg text-white text-opacity-90 leading-relaxed">
                        Enter the 6-digit OTP code sent to your email to continue with password reset.
                    </p>
                </div>

                <!-- OTP Instructions -->
                <div class="mb-8">
                    <div class="bg-white bg-opacity-10 backdrop-blur-sm rounded-xl p-6 border border-white border-opacity-20">
                        <h3 class="font-semibold text-lg mb-4 flex items-center">
                            <i class="fas fa-info-circle mr-2"></i>
                            OTP Instructions
                        </h3>
                        <ul class="space-y-2 text-sm text-white text-opacity-90">
                            <li class="flex items-start">
                                <i class="fas fa-check mr-2 mt-1 text-green-400"></i>
                                Check your email inbox for the 6-digit code
                            </li>
                            <li class="flex items-start">
                                <i class="fas fa-check mr-2 mt-1 text-green-400"></i>
                                Enter the code exactly as shown
                            </li>
                            <li class="flex items-start">
                                <i class="fas fa-check mr-2 mt-1 text-green-400"></i>
                                Code expires in 15 minutes
                            </li>
                            <li class="flex items-start">
                                <i class="fas fa-check mr-2 mt-1 text-green-400"></i>
                                You have 3 attempts to enter correctly
                            </li>
                        </ul>
                    </div>
                </div>

                <!-- Security Notice -->
                <div class="bg-yellow-500 bg-opacity-20 backdrop-blur-sm rounded-xl p-4 border border-yellow-400 border-opacity-30">
                    <div class="flex items-start">
                        <i class="fas fa-exclamation-triangle mr-3 mt-1 text-yellow-300"></i>
                        <div>
                            <h4 class="font-semibold text-sm text-yellow-200 mb-1">Security Notice</h4>
                            <p class="text-xs text-yellow-100 text-opacity-90">
                                Never share your OTP code with anyone. D-Bundles Stores will never ask for your OTP code via phone or other means.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Right Column - OTP Verification Form -->
        <div class="w-full lg:w-1/2 flex items-center justify-center px-4 sm:px-6 lg:px-12 py-8">
            <div class="w-full max-w-md">
                <!-- Mobile Logo -->
                <div class="lg:hidden text-center mb-8">
                    <div class="flex items-center justify-center mb-4">
                        <div class="w-16 h-16 bg-gradient-to-br from-primary-600 to-accent-600 rounded-2xl flex items-center justify-center mr-3 animate-glow">
                            <i class="fas fa-shield-check text-white text-2xl"></i>
                        </div>
                        <div class="text-left">
                            <h1 class="text-2xl font-bold text-gray-900 font-space">D-Bundles Stores</h1>
                            <p class="text-gray-600 text-sm font-medium">OTP Verification</p>
                        </div>
                    </div>
                </div>

                <!-- OTP Verification Form -->
                <div class="bg-white/80 backdrop-blur-sm rounded-3xl shadow-2xl p-8 border border-white/20 relative overflow-hidden">
                    <!-- Decorative Elements -->
                    <div class="absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-primary-100 to-accent-100 rounded-full -translate-y-16 translate-x-16 opacity-50"></div>
                    <div class="absolute bottom-0 left-0 w-24 h-24 bg-gradient-to-tr from-accent-100 to-primary-100 rounded-full translate-y-12 -translate-x-12 opacity-50"></div>
                    
                    <div class="relative z-10">
                        <div class="text-center mb-8">
                            <div class="w-16 h-16 bg-gradient-to-br from-primary-600 to-accent-600 rounded-2xl flex items-center justify-center mx-auto mb-4 animate-glow">
                                <i class="fas fa-shield-check text-white text-2xl"></i>
                            </div>
                            <h2 class="text-3xl font-bold text-gray-900 font-space mb-2">Verify OTP</h2>
                            <p class="text-gray-600 font-medium">Enter the 6-digit code sent to</p>
                            <p class="text-primary-600 font-semibold"><?= htmlspecialchars($email) ?></p>
                        </div>

                        <form method="POST" class="space-y-5">
                            <!-- Error/Success Messages -->
                            <?php if (!empty($error_message)): ?>
                            <div class="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-xl flex items-start backdrop-blur-sm">
                                <i class="fas fa-exclamation-triangle mr-3 mt-0.5 text-red-500"></i>
                                <div>
                                    <span class="text-sm font-medium"><?php echo htmlspecialchars($error_message); ?></span>
                                    <?php if (strpos($error_message, 'Maximum attempts') !== false || strpos($error_message, 'Invalid or expired') !== false): ?>
                                    <div class="mt-3">
                                        <a href="forgot_password.php" class="inline-flex items-center px-4 py-2 bg-primary-600 text-white text-sm font-medium rounded-lg hover:bg-primary-700 transition-colors">
                                            <i class="fas fa-arrow-left mr-2"></i>
                                            Request New OTP
                                        </a>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php endif; ?>

                            <!-- OTP Input Field -->
                            <div>
                                <label for="otp_code" class="block text-sm font-semibold text-gray-700 mb-2">
                                    Enter 6-Digit OTP Code
                                </label>
                                <div class="relative">
                                    <input 
                                        id="otp_code" 
                                        name="otp_code" 
                                        type="text" 
                                        maxlength="6"
                                        required 
                                        class="w-full px-4 py-3.5 pl-12 bg-white/70 backdrop-blur-sm border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 transition-all duration-200 placeholder-gray-400 text-center text-2xl font-mono tracking-widest"
                                        placeholder="000000"
                                        autocomplete="one-time-code"
                                        pattern="[0-9]{6}"
                                        inputmode="numeric"
                                    >
                                    <div class="absolute inset-y-0 left-0 flex items-center pl-4">
                                        <i class="fas fa-key text-gray-400"></i>
                                    </div>
                                </div>
                                <p class="text-xs text-gray-500 mt-2 text-center">
                                    <i class="fas fa-clock mr-1"></i>
                                    Code expires in 15 minutes
                                </p>
                            </div>

                            <!-- Submit Button -->
                            <button 
                                type="submit" 
                                class="w-full bg-gradient-to-r from-primary-600 to-accent-600 text-white py-3.5 px-4 rounded-xl font-bold hover:from-primary-700 hover:to-accent-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 transition-all duration-200 transform hover:scale-[1.02] shadow-lg"
                            >
                                <i class="fas fa-check mr-2"></i>
                                Verify OTP
                            </button>
                        </form>

                        <!-- Resend OTP -->
                        <div class="mt-6 text-center">
                            <p class="text-sm text-gray-600 mb-3">Didn't receive the code?</p>
                            <a href="forgot_password.php" class="text-primary-600 hover:text-primary-500 font-medium text-sm transition-colors">
                                <i class="fas fa-redo mr-2"></i>
                                Resend OTP
                            </a>
                        </div>

                        <!-- Back to Login -->
                        <div class="mt-4 text-center">
                            <a href="login.php" class="text-gray-500 hover:text-gray-600 font-medium text-sm transition-colors">
                                <i class="fas fa-arrow-left mr-2"></i>
                                Back to Login
                            </a>
                        </div>

                        <!-- Security Notice -->
                        <div class="mt-6 text-center">
                            <div class="flex justify-center items-center space-x-6 text-xs text-gray-500">
                                <div class="flex items-center">
                                    <i class="fas fa-shield-check mr-1 text-green-500"></i>
                                    <span class="font-medium">Secure</span>
                                </div>
                                <div class="flex items-center">
                                    <i class="fas fa-lock mr-1 text-green-500"></i>
                                    <span class="font-medium">Encrypted</span>
                                </div>
                                <div class="flex items-center">
                                    <i class="fas fa-user-shield mr-1 text-green-500"></i>
                                    <span class="font-medium">Protected</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Auto-focus on OTP input
        document.addEventListener('DOMContentLoaded', function() {
            const otpInput = document.getElementById('otp_code');
            otpInput.focus();
            
            // Auto-format OTP input
            otpInput.addEventListener('input', function(e) {
                // Remove non-numeric characters
                this.value = this.value.replace(/[^0-9]/g, '');
                
                // Limit to 6 digits
                if (this.value.length > 6) {
                    this.value = this.value.slice(0, 6);
                }
                
                // Auto-submit when 6 digits are entered
                if (this.value.length === 6) {
                    setTimeout(() => {
                        this.form.submit();
                    }, 500);
                }
            });
            
            // Add focus effects
            otpInput.addEventListener('focus', function() {
                this.parentElement.classList.add('ring-2', 'ring-primary-500');
            });
            
            otpInput.addEventListener('blur', function() {
                this.parentElement.classList.remove('ring-2', 'ring-primary-500');
            });

            // Add loading state to submit button
            const form = document.querySelector('form');
            const submitBtn = document.querySelector('button[type="submit"]');
            
            form.addEventListener('submit', function() {
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Verifying...';
                submitBtn.disabled = true;
            });
        });
    </script>
</body>
</html>
