<?php
/**
 * OTP Testing & Verification Page for Admin Panel
 * Test OTP sending and verify emails on live server
 */

require_once __DIR__ . '/../../classes/OTPManager.php';

$otpManager = new OTPManager($db);
$message = '';
$message_type = '';
$testOTP = '';
$testEmail = '';

// Handle OTP sending
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'send_test_otp') {
        $testEmail = trim($_POST['test_email'] ?? '');
        
        if (!filter_var($testEmail, FILTER_VALIDATE_EMAIL)) {
            $message = 'Invalid email address';
            $message_type = 'danger';
        } else {
            $result = $otpManager->generateAndSendOTP($testEmail, 'Test User');
            
            if ($result['success']) {
                // Get the OTP for display
                $otpRecord = $db->fetch(
                    'SELECT otp, created_at, expires_at FROM email_otps WHERE email = ? ORDER BY created_at DESC LIMIT 1',
                    [$testEmail]
                );
                
                if ($otpRecord) {
                    $testOTP = $otpRecord['otp'];
                    $message = 'OTP sent successfully to ' . htmlspecialchars($testEmail) . '! Test code: <strong>' . $testOTP . '</strong>';
                    $message_type = 'success';
                }
            } else {
                $message = 'Failed to send OTP: ' . $result['message'];
                $message_type = 'danger';
            }
        }
    } elseif ($action === 'verify_test_otp') {
        $testEmail = trim($_POST['verify_email'] ?? '');
        $otp = trim($_POST['verify_code'] ?? '');
        
        if (!filter_var($testEmail, FILTER_VALIDATE_EMAIL)) {
            $message = 'Invalid email address';
            $message_type = 'danger';
        } elseif (strlen($otp) !== 6 || !ctype_digit($otp)) {
            $message = 'OTP must be 6 digits';
            $message_type = 'danger';
        } else {
            $result = $otpManager->verifyOTP($testEmail, $otp);
            
            if ($result['success']) {
                $message = 'OTP verified successfully! ✅';
                $message_type = 'success';
            } else {
                $message = $result['message'];
                $message_type = 'danger';
            }
        }
    } elseif ($action === 'clear_otps') {
        $db->query('DELETE FROM email_otps');
        $message = 'All OTP records cleared';
        $message_type = 'info';
    }
}

// Get email configuration
$config = require __DIR__ . '/../../config/email_config.php';

// Get recent OTPs
$recentOTPs = $db->query(
    'SELECT email, otp, attempts, created_at, expires_at FROM email_otps ORDER BY created_at DESC LIMIT 20'
)->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-12">
            <h2>
                <span data-feather="mail"></span>
                OTP Testing & Verification
            </h2>
            <p class="text-muted">Test OTP sending and verify email functionality on live server</p>
        </div>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
            <?php echo $message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="row">
        <!-- Configuration Info -->
        <div class="col-lg-4 mb-4">
            <div class="card">
                <div class="card-header bg-light">
                    <h5 class="mb-0">📋 Configuration</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <small class="text-muted">Email Mode</small>
                        <div class="fw-bold">
                            <span class="badge bg-primary"><?php echo $config['mode']; ?></span>
                        </div>
                    </div>
                    <div class="mb-3">
                        <small class="text-muted">From Email</small>
                        <div><code><?php echo $config['from_email']; ?></code></div>
                    </div>
                    <div class="mb-3">
                        <small class="text-muted">From Name</small>
                        <div><?php echo $config['from_name']; ?></div>
                    </div>
                    <div class="mb-3">
                        <small class="text-muted">OTP Expiry</small>
                        <div class="fw-bold"><?php echo $config['otp_expiry_minutes']; ?> minutes</div>
                    </div>
                    <div class="mb-3">
                        <small class="text-muted">Max Attempts</small>
                        <div class="fw-bold"><?php echo $config['otp_max_attempts']; ?> attempts</div>
                    </div>
                    <div class="mb-3">
                        <small class="text-muted">Server Timezone</small>
                        <div><?php echo date_default_timezone_get(); ?></div>
                    </div>
                    <div>
                        <small class="text-muted">Current Server Time</small>
                        <div><?php echo date('Y-m-d H:i:s'); ?></div>
                    </div>
                </div>
            </div>

            <!-- Clear OTPs Button -->
            <div class="card mt-3">
                <div class="card-body">
                    <form method="POST" onsubmit="return confirm('Clear all OTP records?');">
                        <input type="hidden" name="action" value="clear_otps">
                        <button type="submit" class="btn btn-danger btn-sm w-100">
                            🗑️ Clear All OTPs
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Send & Verify OTP -->
        <div class="col-lg-8">
            <!-- Send OTP Tab -->
            <div class="card mb-4">
                <div class="card-header bg-light">
                    <h5 class="mb-0">📧 Send Test OTP</h5>
                </div>
                <div class="card-body">
                    <form method="POST">
                        <input type="hidden" name="action" value="send_test_otp">
                        <div class="mb-3">
                            <label class="form-label">Email Address</label>
                            <input 
                                type="email" 
                                class="form-control" 
                                name="test_email" 
                                placeholder="Enter email address to test"
                                value="<?php echo htmlspecialchars($testEmail); ?>"
                                required
                            >
                            <small class="text-muted">You can use any email address for testing</small>
                        </div>
                        <button type="submit" class="btn btn-primary">
                            🚀 Send Test OTP
                        </button>
                    </form>

                    <?php if ($testOTP && $message_type === 'success'): ?>
                        <div class="alert alert-success mt-3">
                            <strong>✅ OTP Test Code:</strong>
                            <div style="font-size: 32px; font-weight: bold; letter-spacing: 5px; text-align: center; margin: 15px 0; font-family: monospace;">
                                <?php echo $testOTP; ?>
                            </div>
                            <small>This code expires in <?php echo $config['otp_expiry_minutes']; ?> minutes. Use it in the Verify tab below to test.</small>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Verify OTP Tab -->
            <div class="card">
                <div class="card-header bg-light">
                    <h5 class="mb-0">✅ Verify Test OTP</h5>
                </div>
                <div class="card-body">
                    <form method="POST">
                        <input type="hidden" name="action" value="verify_test_otp">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Email Address</label>
                                <input 
                                    type="email" 
                                    class="form-control" 
                                    name="verify_email" 
                                    placeholder="Email used above"
                                    required
                                >
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">OTP Code (6 digits)</label>
                                <input 
                                    type="text" 
                                    class="form-control" 
                                    name="verify_code" 
                                    placeholder="000000"
                                    maxlength="6"
                                    pattern="[0-9]{6}"
                                    inputmode="numeric"
                                    required
                                >
                            </div>
                        </div>
                        <button type="submit" class="btn btn-success">
                            ✔️ Verify OTP
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Recent OTPs Table -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-light">
                    <h5 class="mb-0">📊 Recent OTP Records (Last 20)</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover table-sm">
                            <thead class="table-light">
                                <tr>
                                    <th>Email</th>
                                    <th>OTP Code</th>
                                    <th>Attempts</th>
                                    <th>Created</th>
                                    <th>Expires</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                if (empty($recentOTPs)) {
                                    echo '<tr><td colspan="6" class="text-center text-muted">No OTP records yet</td></tr>';
                                } else {
                                    foreach ($recentOTPs as $otp) {
                                        $isExpired = strtotime($otp['expires_at']) < time();
                                        $status = $isExpired ? '<span class="badge bg-danger">Expired</span>' : '<span class="badge bg-success">Valid</span>';
                                        $rowClass = $isExpired ? 'table-light' : '';
                                        
                                        echo '<tr class="' . $rowClass . '">';
                                        echo '<td>' . htmlspecialchars($otp['email']) . '</td>';
                                        echo '<td><code>' . $otp['otp'] . '</code></td>';
                                        echo '<td>' . $otp['attempts'] . '/5</td>';
                                        echo '<td><small>' . $otp['created_at'] . '</small></td>';
                                        echo '<td><small>' . $otp['expires_at'] . '</small></td>';
                                        echo '<td>' . $status . '</td>';
                                        echo '</tr>';
                                    }
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Troubleshooting Info -->
    <div class="row mt-4">
        <div class="col-lg-6">
            <div class="card border-warning">
                <div class="card-header bg-warning text-dark">
                    <h5 class="mb-0">⚠️ If OTP Goes to Spam</h5>
                </div>
                <div class="card-body">
                    <ol>
                        <li>Check your email's <strong>spam/junk folder</strong></li>
                        <li>Click <strong>"Not Spam"</strong> on the email</li>
                        <li>Add sender to contacts</li>
                        <li>Future emails will go to inbox</li>
                    </ol>
                    <p class="mt-3 mb-0"><small class="text-muted">This is normal for shared hosting. Gmail learns after marking "Not Spam".</small></p>
                </div>
            </div>
        </div>
        <div class="col-lg-6">
            <div class="card border-info">
                <div class="card-header bg-info text-white">
                    <h5 class="mb-0">ℹ️ How to Use</h5>
                </div>
                <div class="card-body">
                    <ol>
                        <li>Enter your email in "Send Test OTP" section</li>
                        <li>Click <strong>Send Test OTP</strong></li>
                        <li>OTP code will display here</li>
                        <li>Check your email (check spam folder too)</li>
                        <li>Enter code in "Verify Test OTP" section</li>
                        <li>Click <strong>Verify OTP</strong> to test verification</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.badge {
    font-size: 12px;
    padding: 0.4rem 0.8rem;
}

code {
    background: #f8f9fa;
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-size: 0.9em;
}

.table-hover tbody tr:hover {
    background-color: #f8f9fa;
}
</style>
