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

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

$message = '';
$message_type = '';
$testOTP = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'send_otp') {
        $email = trim($_POST['email'] ?? '');
        
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $message = 'Invalid email';
            $message_type = 'danger';
        } else {
            $result = $otpManager->generateAndSendOTP($email, 'Test');
            
            if ($result['success']) {
                $otpRecord = $db->fetch('SELECT otp FROM email_otps WHERE email = ? ORDER BY created_at DESC LIMIT 1', [$email]);
                $testOTP = $otpRecord['otp'] ?? '';
                $message = 'OTP sent! Test code: ' . $testOTP;
                $message_type = 'success';
            } else {
                $message = $result['message'];
                $message_type = 'danger';
            }
        }
    } elseif ($action === 'verify_otp') {
        $email = trim($_POST['email'] ?? '');
        $otp = trim($_POST['otp'] ?? '');
        
        $result = $otpManager->verifyOTP($email, $otp);
        
        if ($result['success']) {
            $message = 'OTP verified successfully!';
            $message_type = 'success';
        } else {
            $message = $result['message'];
            $message_type = 'danger';
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>OTP Test & Verify</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, #764ba2); min-height: 100vh; display: flex; align-items: center; padding: 20px; }
        .card { border: none; border-radius: 15px; box-shadow: 0 10px 40px rgba(0,0,0,0.2); }
        .card-header { background: linear-gradient(135deg, #667eea, #764ba2); color: white; border-radius: 15px 15px 0 0; }
        .form-section { padding: 30px; }
    </style>
</head>
<body>
    <div class="container" style="max-width: 500px;">
        <div class="card">
            <div class="card-header">
                <h2 class="m-0">OTP Testing & Verification</h2>
            </div>
            <div class="form-section">
                <?php if ($message): ?>
                    <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show">
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                
                <ul class="nav nav-tabs" role="tablist" style="margin-bottom: 20px;">
                    <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#send">Send OTP</a></li>
                    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#verify">Verify OTP</a></li>
                </ul>
                
                <div class="tab-content">
                    <!-- Send OTP Tab -->
                    <div id="send" class="tab-pane fade show active">
                        <form method="POST">
                            <input type="hidden" name="action" value="send_otp">
                            <div class="form-group mb-3">
                                <label>Email Address</label>
                                <input type="email" class="form-control" name="email" placeholder="Enter email" required>
                            </div>
                            <button type="submit" class="btn btn-primary w-100">Send OTP</button>
                        </form>
                        
                        <?php if ($testOTP && $message_type === 'success'): ?>
                            <div class="alert alert-info mt-3">
                                <strong>Test OTP Code:</strong>
                                <div style="font-size: 24px; font-weight: bold; letter-spacing: 3px; text-align: center; margin-top: 10px;">
                                    <?php echo $testOTP; ?>
                                </div>
                                <small>Use this code in the Verify tab. Expires in 5 minutes.</small>
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Verify OTP Tab -->
                    <div id="verify" class="tab-pane fade">
                        <form method="POST">
                            <input type="hidden" name="action" value="verify_otp">
                            <div class="form-group mb-3">
                                <label>Email Address</label>
                                <input type="email" class="form-control" name="email" placeholder="Same email as above" required>
                            </div>
                            <div class="form-group mb-3">
                                <label>OTP Code (6 digits)</label>
                                <input type="text" class="form-control" name="otp" placeholder="000000" maxlength="6" pattern="[0-9]{6}" inputmode="numeric" required>
                            </div>
                            <button type="submit" class="btn btn-success w-100">Verify OTP</button>
                        </form>
                    </div>
                </div>
                
                <hr>
                
                <h5>Info</h5>
                <div class="alert alert-info small">
                    <strong>Spam Issue?</strong> If OTP goes to spam, it's a mail server config issue. Check your email provider's spam folder.
                    <br><br>
                    <strong>Config:</strong> Mode: php_mail | Timezone: Asia/Kolkata
                </div>
                
                <h5 style="margin-top: 20px;">Recent OTPs</h5>
                <table class="table table-sm">
                    <thead class="table-light">
                        <tr><th>Email</th><th>Code</th><th>Status</th></tr>
                    </thead>
                    <tbody>
                        <?php
                        $otps = $db->query('SELECT email, otp, expires_at FROM email_otps ORDER BY created_at DESC LIMIT 5')->fetchAll(PDO::FETCH_ASSOC);
                        foreach ($otps as $o) {
                            $expired = strtotime($o['expires_at']) < time() ? 'Expired' : 'Valid';
                            echo '<tr><td>' . htmlspecialchars($o['email']) . '</td><td><code>' . $o['otp'] . '</code></td><td>' . $expired . '</td></tr>';
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
