<?php
/**
 * OTP System Complete Test for Razorhost
 * Tests timezone, database, and email sending
 */

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

$db = Database::getInstance();
$testResults = [];

?>
<!DOCTYPE html>
<html>
<head>
    <title>OTP System Test</title>
    <style>
        body { font-family: Arial; margin: 30px; background: #f5f5f5; }
        .container { max-width: 700px; margin: 0 auto; background: white; padding: 30px; border-radius: 10px; }
        h1 { color: #667eea; }
        .test-section { margin: 20px 0; padding: 15px; background: #f9f9f9; border-left: 4px solid #667eea; }
        .pass { color: green; font-weight: bold; }
        .fail { color: red; font-weight: bold; }
        .info { color: #666; margin: 10px 0; }
        code { background: #eee; padding: 3px 8px; border-radius: 3px; }
        .test-form { background: white; padding: 20px; border: 1px solid #ddd; border-radius: 5px; margin-top: 20px; }
        input { padding: 10px; width: 100%; margin: 10px 0; border: 1px solid #ddd; border-radius: 5px; }
        button { padding: 10px 20px; background: #667eea; color: white; border: none; cursor: pointer; border-radius: 5px; }
        button:hover { background: #764ba2; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🧪 OTP System Complete Test</h1>
        
        <!-- 1. Timezone Test -->
        <div class="test-section">
            <h3>1️⃣ Timezone Configuration</h3>
            <?php
            date_default_timezone_set('Asia/Kolkata');
            $phpTimezone = date_default_timezone_get();
            $phpTime = date('Y-m-d H:i:s');
            echo "<div class='info'>PHP Timezone: <code>$phpTimezone</code></div>";
            echo "<div class='info'>PHP Current Time: <code>$phpTime</code></div>";
            if ($phpTimezone === 'Asia/Kolkata') {
                echo "<div class='pass'>✅ PASS: Timezone set to IST</div>";
            } else {
                echo "<div class='fail'>❌ FAIL: Timezone not IST</div>";
            }
            ?>
        </div>
        
        <!-- 2. Database Connection Test -->
        <div class="test-section">
            <h3>2️⃣ Database Connection</h3>
            <?php
            try {
                $testQuery = $db->query("SELECT NOW() as db_time");
                $dbTime = $testQuery->fetch(PDO::FETCH_ASSOC);
                echo "<div class='info'>Database Current Time: <code>" . $dbTime['db_time'] . "</code></div>";
                
                // Check email_otps table
                $tableCheck = $db->query("SHOW TABLES LIKE 'email_otps'")->fetch(PDO::FETCH_ASSOC);
                if ($tableCheck) {
                    echo "<div class='pass'>✅ PASS: email_otps table exists</div>";
                    
                    // Check table structure
                    $columns = $db->query("SHOW COLUMNS FROM email_otps")->fetchAll(PDO::FETCH_ASSOC);
                    echo "<div class='info'>Columns: " . implode(', ', array_column($columns, 'Field')) . "</div>";
                } else {
                    echo "<div class='fail'>❌ FAIL: email_otps table not found</div>";
                }
            } catch (Exception $e) {
                echo "<div class='fail'>❌ FAIL: " . $e->getMessage() . "</div>";
            }
            ?>
        </div>
        
        <!-- 3. OTPManager Test -->
        <div class="test-section">
            <h3>3️⃣ OTPManager Class</h3>
            <?php
            try {
                $otpManager = new OTPManager($db);
                echo "<div class='pass'>✅ PASS: OTPManager loaded successfully</div>";
                echo "<div class='info'>Email Config Mode: <code>php_mail</code></div>";
            } catch (Exception $e) {
                echo "<div class='fail'>❌ FAIL: " . $e->getMessage() . "</div>";
            }
            ?>
        </div>
        
        <!-- 4. Email Configuration Test -->
        <div class="test-section">
            <h3>4️⃣ Email Configuration</h3>
            <?php
            $config = require 'config/email_config.php';
            echo "<div class='info'>Mode: <code>" . $config['mode'] . "</code></div>";
            echo "<div class='info'>From Email: <code>" . $config['from_email'] . "</code></div>";
            echo "<div class='info'>From Name: <code>" . $config['from_name'] . "</code></div>";
            
            if (ini_get('disable_functions') && strpos(ini_get('disable_functions'), 'mail') !== false) {
                echo "<div class='fail'>❌ FAIL: mail() function is DISABLED</div>";
            } else {
                echo "<div class='pass'>✅ PASS: mail() function is ENABLED</div>";
            }
            ?>
        </div>
        
        <!-- 5. Generate Test OTP -->
        <div class="test-section">
            <h3>5️⃣ Generate and Send Test OTP</h3>
            
            <?php
            if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['test_email'])) {
                $testEmail = trim($_POST['test_email']);
                
                echo "<div class='info'>Testing with: <code>$testEmail</code></div>";
                
                try {
                    $otpManager = new OTPManager($db);
                    $result = $otpManager->generateAndSendOTP($testEmail, 'Test User');
                    
                    if ($result['success']) {
                        echo "<div class='pass'>✅ PASS: " . $result['message'] . "</div>";
                        
                        // Check database
                        $otpRecord = $db->fetch(
                            'SELECT otp, created_at, expires_at FROM email_otps WHERE email = ? ORDER BY created_at DESC LIMIT 1',
                            [$testEmail]
                        );
                        
                        if ($otpRecord) {
                            echo "<div class='info'>OTP Code: <code>" . $otpRecord['otp'] . "</code></div>";
                            echo "<div class='info'>Created: <code>" . $otpRecord['created_at'] . "</code></div>";
                            echo "<div class='info'>Expires: <code>" . $otpRecord['expires_at'] . "</code></div>";
                            
                            // Calculate remaining time
                            $remaining = strtotime($otpRecord['expires_at']) - time();
                            if ($remaining > 0) {
                                echo "<div class='pass'>✅ OTP valid for: <code>" . ceil($remaining) . "</code> seconds</div>";
                            } else {
                                echo "<div class='fail'>❌ OTP already expired</div>";
                            }
                        }
                    } else {
                        echo "<div class='fail'>❌ FAIL: " . $result['message'] . "</div>";
                    }
                    
                    // Show error log
                    if (file_exists('error_log')) {
                        echo "<div class='info' style='margin-top:15px;'><strong>Error Log (Last 10 lines):</strong></div>";
                        $errors = array_slice(file('error_log'), -10);
                        echo "<pre style='background:#fff; border:1px solid #ddd; padding:10px; font-size:11px;'>";
                        foreach ($errors as $error) {
                            echo htmlspecialchars($error);
                        }
                        echo "</pre>";
                    }
                    
                } catch (Exception $e) {
                    echo "<div class='fail'>❌ ERROR: " . $e->getMessage() . "</div>";
                }
            }
            ?>
            
            <div class="test-form">
                <form method="POST">
                    <input type="email" name="test_email" placeholder="Enter email to test OTP" required>
                    <button type="submit">Send Test OTP</button>
                </form>
            </div>
        </div>
        
        <!-- Summary -->
        <div class="test-section" style="background: #e8f5e9;">
            <h3>📋 Summary</h3>
            <p><strong>If all tests pass:</strong> OTP system is working correctly on your live server!</p>
            <p><strong>If email test fails:</strong> Check error logs above for specific issues.</p>
            <p><strong>Common fixes:</strong></p>
            <ul>
                <li>Clear old OTPs: <code>DELETE FROM email_otps;</code></li>
                <li>Check sendmail path: <code>php -r "echo ini_get('sendmail_path');"</code></li>
                <li>Check error logs in root directory</li>
            </ul>
        </div>
    </div>
</body>
</html>
