<?php
session_start();
require_once 'config/config.php';
require_once 'classes/Database.php';
require_once 'classes/OTPManager.php';

$db = Database::getInstance();
$otpManager = new OTPManager($db);

$email = $_SESSION['registration_email'] ?? '';
$message = '';
$message_type = '';
$remainingTime = 0;

// Check if user is in registration process
if (empty($email) || !isset($_SESSION['registration_email'])) {
    header('Location: register.php');
    exit();
}

// Get remaining time for OTP
$remainingTime = $otpManager->getRemainingTime($email);

// Handle OTP verification
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'verify_otp') {
        $otp = preg_replace('/\D/', '', $_POST['otp'] ?? '');
        
        if (strlen($otp) !== 6) {
            $message = 'OTP must be 6 digits';
            $message_type = 'danger';
        } else {
            $result = $otpManager->verifyOTP($email, $otp);
            
            if ($result['success']) {
                // Mark email as verified
                $db->update('users',
                    ['email_verified' => 1, 'email_verified_at' => date('Y-m-d H:i:s')],
                    'email = ?',
                    ['email' => $email]
                );
                
                // Clear session and redirect to login
                unset($_SESSION['registration_email']);
                $message = 'Email verified successfully! Redirecting to login...';
                $message_type = 'success';
                echo '<script>
                    setTimeout(function(){
                        window.location.href = "login.php?verified=1";
                    }, 2000);
                </script>';
            } else {
                $message = $result['message'];
                $message_type = 'danger';
            }
        }
    } elseif ($action === 'resend_otp') {
        $result = $otpManager->resendOTP($email);
        $message = $result['message'];
        $message_type = $result['success'] ? 'success' : 'danger';
        $remainingTime = $otpManager->getRemainingTime($email);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify OTP - <?php echo APP_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        
        .otp-container {
            background: white;
            border-radius: 16px;
            padding: 40px;
            max-width: 450px;
            width: 100%;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
        }
        
        .otp-header {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .otp-icon {
            font-size: 3rem;
            margin-bottom: 15px;
        }
        
        .otp-header h2 {
            font-weight: 700;
            color: #1c1c1e;
            margin-bottom: 10px;
        }
        
        .otp-header p {
            color: #666;
            margin: 0;
        }
        
        .email-display {
            background: #f8f9fa;
            padding: 10px 15px;
            border-radius: 8px;
            text-align: center;
            color: #667eea;
            font-weight: 600;
            margin: 10px 0 20px;
        }
        
        .otp-input-group {
            display: flex;
            gap: 8px;
            justify-content: center;
            margin: 25px 0;
        }
        
        .otp-input {
            width: 50px;
            height: 50px;
            font-size: 24px;
            text-align: center;
            border: 2px solid #ddd;
            border-radius: 10px;
            transition: all 0.3s ease;
        }
        
        .otp-input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .timer {
            text-align: center;
            color: #666;
            font-size: 14px;
            margin: 15px 0;
        }
        
        .timer.expired {
            color: #ef4444;
        }
        
        .timer strong {
            color: #667eea;
            font-weight: 700;
        }
        
        .btn-verify {
            width: 100%;
            padding: 12px;
            font-weight: 600;
            border: none;
            border-radius: 10px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            transition: all 0.3s ease;
            margin-top: 15px;
        }
        
        .btn-verify:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
            color: white;
        }
        
        .btn-resend {
            width: 100%;
            padding: 10px;
            font-weight: 600;
            border: 2px solid #667eea;
            border-radius: 10px;
            background: white;
            color: #667eea;
            margin-top: 10px;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .btn-resend:hover {
            background: #f8f9ff;
        }
        
        .btn-resend:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .alert {
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .help-text {
            font-size: 13px;
            color: #999;
            text-align: center;
            margin-top: 15px;
        }
        
        @media (max-width: 576px) {
            .otp-container {
                padding: 25px 20px;
            }
            
            .otp-input {
                width: 40px;
                height: 40px;
                font-size: 18px;
            }
            
            .otp-header h2 {
                font-size: 1.5rem;
            }
        }
    </style>
</head>
<body>
    <div class="otp-container">
        <div class="otp-header">
            <div class="otp-icon">✉️</div>
            <h2>Verify Your Email</h2>
            <p>Enter the 6-digit code sent to your email</p>
        </div>
        
        <div class="email-display">
            📧 <?php echo htmlspecialchars($email); ?>
        </div>
        
        <?php if (!empty($message)): ?>
            <div class="alert alert-<?php echo $message_type; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>
        
        <form method="POST">
            <input type="hidden" name="action" value="verify_otp">
            
            <div class="otp-input-group" id="otpGroup">
                <input type="text" class="otp-input" maxlength="1" pattern="\d" inputmode="numeric" data-index="0">
                <input type="text" class="otp-input" maxlength="1" pattern="\d" inputmode="numeric" data-index="1">
                <input type="text" class="otp-input" maxlength="1" pattern="\d" inputmode="numeric" data-index="2">
                <input type="text" class="otp-input" maxlength="1" pattern="\d" inputmode="numeric" data-index="3">
                <input type="text" class="otp-input" maxlength="1" pattern="\d" inputmode="numeric" data-index="4">
                <input type="text" class="otp-input" maxlength="1" pattern="\d" inputmode="numeric" data-index="5">
            </div>
            
            <input type="hidden" name="otp" id="otpInput">
            
            <div class="timer" id="timerDisplay">
                <strong id="timerValue"><?php echo ceil($remainingTime); ?></strong> seconds remaining
            </div>
            
            <button type="submit" class="btn-verify" id="verifyBtn">Verify OTP</button>
        </form>
        
        <button type="button" class="btn-resend" onclick="resendOTP()" id="resendBtn">Didn't receive code? Resend</button>
        
        <div class="help-text">
            Never share your OTP with anyone
        </div>
    </div>
    
    <script>
        const otpInputs = document.querySelectorAll('.otp-input');
        const otpInput = document.getElementById('otpInput');
        const timerValue = document.getElementById('timerValue');
        const timerDisplay = document.getElementById('timerDisplay');
        const verifyBtn = document.getElementById('verifyBtn');
        const resendBtn = document.getElementById('resendBtn');
        
        let remainingTime = <?php echo $remainingTime; ?>;
        
        // OTP Input handling
        otpInputs.forEach((input, index) => {
            input.addEventListener('input', (e) => {
                if (!/\d/.test(e.target.value)) {
                    e.target.value = '';
                    return;
                }
                
                updateOTPInput();
                
                if (e.target.value && index < otpInputs.length - 1) {
                    otpInputs[index + 1].focus();
                }
            });
            
            input.addEventListener('keydown', (e) => {
                if (e.key === 'Backspace' && !input.value && index > 0) {
                    otpInputs[index - 1].focus();
                }
            });
            
            input.addEventListener('paste', (e) => {
                e.preventDefault();
                const pastedData = (e.clipboardData || window.clipboardData).getData('text');
                const digits = pastedData.replace(/\D/g, '').slice(0, 6);
                
                for (let i = 0; i < digits.length; i++) {
                    otpInputs[i].value = digits[i];
                }
                updateOTPInput();
                if (digits.length === 6) {
                    verifyBtn.focus();
                }
            });
        });
        
        function updateOTPInput() {
            const otp = Array.from(otpInputs).map(input => input.value).join('');
            otpInput.value = otp;
        }
        
        function resendOTP() {
            resendBtn.disabled = true;
            resendBtn.textContent = 'Resending...';
            
            const formData = new FormData();
            formData.append('action', 'resend_otp');
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                location.reload();
            });
        }
        
        // Timer countdown
        setInterval(() => {
            remainingTime--;
            timerValue.textContent = Math.max(0, remainingTime);
            
            if (remainingTime <= 0) {
                timerDisplay.classList.add('expired');
                timerDisplay.innerHTML = '<span style="color: #ef4444;">OTP Expired</span>';
                verifyBtn.disabled = true;
                resendBtn.textContent = 'Send New OTP';
            } else if (remainingTime <= 60) {
                timerValue.style.color = '#ef4444';
            }
        }, 1000);
        
        // Auto-focus first input
        otpInputs[0].focus();
    </script>
</body>
</html>
