<?php
/**
 * OTP Email Diagnostic - Find Why Emails Not Received
 * This script checks every step of the OTP process
 */

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

$db = Database::getInstance();

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OTP Diagnostic</title>
    <style>
        body {
            font-family: monospace;
            background: #1e1e1e;
            color: #d4d4d4;
            padding: 20px;
            line-height: 1.6;
        }
        
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: #252526;
            padding: 20px;
            border-radius: 5px;
        }
        
        h1 {
            color: #4ec9b0;
            border-bottom: 2px solid #007acc;
            padding-bottom: 10px;
        }
        
        h2 {
            color: #569cd6;
            margin-top: 30px;
        }
        
        .test {
            background: #1e1e1e;
            padding: 15px;
            margin: 15px 0;
            border-left: 4px solid #007acc;
        }
        
        .success {
            border-left-color: #4ec9b0;
        }
        
        .error {
            border-left-color: #f48771;
        }
        
        .warning {
            border-left-color: #dcdcaa;
        }
        
        .info {
            border-left-color: #569cd6;
        }
        
        .status {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 3px;
            font-weight: bold;
            margin-left: 10px;
        }
        
        .status-pass {
            background: #4ec9b0;
            color: #000;
        }
        
        .status-fail {
            background: #f48771;
            color: #fff;
        }
        
        code {
            background: #1e1e1e;
            padding: 2px 5px;
            border-radius: 3px;
        }
        
        pre {
            background: #1e1e1e;
            padding: 15px;
            border-radius: 5px;
            overflow-x: auto;
        }
        
        .form-group {
            margin: 20px 0;
        }
        
        input, textarea {
            background: #3e3e42;
            color: #d4d4d4;
            border: 1px solid #555;
            padding: 10px;
            border-radius: 3px;
            width: 100%;
            box-sizing: border-box;
            font-family: monospace;
        }
        
        button {
            background: #007acc;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 3px;
            cursor: pointer;
            font-weight: bold;
        }
        
        button:hover {
            background: #005a9e;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 OTP Email Diagnostic</h1>
        
        <?php
        $tests = [];
        
        // Test 1: Email Config
        echo "<h2>Test 1: Email Configuration</h2>";
        try {
            $emailConfig = require 'config/email_config.php';
            $tests[] = ['Email Config', 'PASS'];
            echo '<div class="test success">';
            echo '<strong>✓ Email config loaded</strong>' . PHP_EOL;
            echo '<pre>' . print_r($emailConfig, true) . '</pre>';
            echo '</div>';
        } catch (Exception $e) {
            $tests[] = ['Email Config', 'FAIL'];
            echo '<div class="test error">';
            echo '<strong>✗ Error:</strong> ' . $e->getMessage();
            echo '</div>';
        }
        
        // Test 2: Database Connection
        echo "<h2>Test 2: Database Connection</h2>";
        try {
            $test = $db->fetch('SELECT 1');
            $tests[] = ['Database', 'PASS'];
            echo '<div class="test success">';
            echo '<strong>✓ Database connected</strong>' . PHP_EOL;
            echo '<p>Host: ' . DB_HOST . ' | DB: ' . DB_NAME . '</p>';
            echo '</div>';
        } catch (Exception $e) {
            $tests[] = ['Database', 'FAIL'];
            echo '<div class="test error">';
            echo '<strong>✗ Error:</strong> ' . $e->getMessage();
            echo '</div>';
        }
        
        // Test 3: Email OTP Table
        echo "<h2>Test 3: Database Tables</h2>";
        try {
            $result = $db->fetch("SHOW TABLES LIKE 'email_otps'");
            if ($result) {
                $tests[] = ['OTP Table', 'PASS'];
                echo '<div class="test success">';
                echo '<strong>✓ email_otps table exists</strong>';
                echo '</div>';
            } else {
                $tests[] = ['OTP Table', 'FAIL'];
                echo '<div class="test error">';
                echo '<strong>✗ email_otps table NOT found</strong>' . PHP_EOL;
                echo '<p><a href="setup_razorhost_otp.php">→ Run Setup Script First</a></p>';
                echo '</div>';
            }
        } catch (Exception $e) {
            echo '<div class="test error">';
            echo '<strong>✗ Error:</strong> ' . $e->getMessage();
            echo '</div>';
        }
        
        // Test 4: Mail Relay Connection
        echo "<h2>Test 4: Mail Relay Connection</h2>";
        $host = $emailConfig['mail_relay']['host'] ?? 'localhost';
        $port = $emailConfig['mail_relay']['port'] ?? 25;
        
        $fp = @fsockopen($host, $port, $errno, $errstr, 5);
        if ($fp) {
            $tests[] = ['Mail Relay', 'PASS'];
            echo '<div class="test success">';
            echo '<strong>✓ Mail relay accessible</strong>' . PHP_EOL;
            echo '<p>Host: ' . $host . ' | Port: ' . $port . '</p>';
            
            // Read greeting
            $greeting = fgets($fp, 1024);
            echo '<p>Server: ' . htmlspecialchars(trim($greeting)) . '</p>';
            fclose($fp);
            echo '</div>';
        } else {
            $tests[] = ['Mail Relay', 'FAIL'];
            echo '<div class="test error">';
            echo '<strong>✗ Cannot connect to mail relay</strong>' . PHP_EOL;
            echo '<p>Error: ' . $errstr . ' (Code: ' . $errno . ')</p>' . PHP_EOL;
            echo '<p><strong>Solutions:</strong></p>';
            echo '<ul>';
            echo '<li>Contact Razorhost support</li>';
            echo '<li>Ask them to enable port 25 for mail relay</li>';
            echo '<li>Check if sendmail/postfix is installed</li>';
            echo '</ul>';
            echo '</div>';
        }
        
        // Test 5: OTP Manager
        echo "<h2>Test 5: OTP Manager</h2>";
        try {
            $otpManager = new OTPManager($db);
            $tests[] = ['OTP Manager', 'PASS'];
            echo '<div class="test success">';
            echo '<strong>✓ OTPManager initialized</strong>';
            echo '</div>';
        } catch (Exception $e) {
            $tests[] = ['OTP Manager', 'FAIL'];
            echo '<div class="test error">';
            echo '<strong>✗ Error:</strong> ' . $e->getMessage();
            echo '</div>';
        }
        
        // Test 6: Recent OTPs
        echo "<h2>Test 6: Recent OTP Records in Database</h2>";
        try {
            $otps = $db->fetch("SELECT * FROM email_otps ORDER BY created_at DESC LIMIT 5");
            if ($otps) {
                echo '<div class="test success">';
                echo '<strong>✓ Found OTP records</strong>' . PHP_EOL;
                echo '<pre>';
                var_dump($otps);
                echo '</pre>';
                echo '</div>';
            } else {
                echo '<div class="test warning">';
                echo '<strong>⚠ No OTP records found yet</strong>' . PHP_EOL;
                echo '<p>Send a test OTP below to create records</p>';
                echo '</div>';
            }
        } catch (Exception $e) {
            echo '<div class="test error">';
            echo '<strong>✗ Error:</strong> ' . $e->getMessage();
            echo '</div>';
        }
        
        // Test 7: Send Test OTP
        echo "<h2>Test 7: Send Test OTP</h2>";
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['test_email'])) {
            $testEmail = $_POST['test_email'];
            
            try {
                $otpManager = new OTPManager($db);
                $result = $otpManager->generateAndSendOTP($testEmail, 'Test User');
                
                if ($result['success']) {
                    $tests[] = ['Test OTP Send', 'PASS'];
                    echo '<div class="test success">';
                    echo '<strong>✓ OTP Sent Successfully</strong>' . PHP_EOL;
                    echo '<p>Message: ' . htmlspecialchars($result['message']) . '</p>' . PHP_EOL;
                    
                    // Get OTP from DB
                    $otp = $db->fetch("SELECT otp, expires_at FROM email_otps WHERE email = ? ORDER BY created_at DESC LIMIT 1", [$testEmail]);
                    if ($otp) {
                        echo '<p><strong>OTP Code:</strong> ' . htmlspecialchars($otp['otp']) . '</p>' . PHP_EOL;
                        echo '<p><strong>Expires:</strong> ' . htmlspecialchars($otp['expires_at']) . '</p>' . PHP_EOL;
                    }
                    echo '</div>';
                } else {
                    $tests[] = ['Test OTP Send', 'FAIL'];
                    echo '<div class="test error">';
                    echo '<strong>✗ Failed to send OTP</strong>' . PHP_EOL;
                    echo '<p>Message: ' . htmlspecialchars($result['message']) . '</p>';
                    echo '</div>';
                }
            } catch (Exception $e) {
                echo '<div class="test error">';
                echo '<strong>✗ Exception:</strong> ' . $e->getMessage();
                echo '</div>';
            }
        }
        
        echo '<div class="test info">';
        echo '<form method="POST">';
        echo '<div class="form-group">';
        echo '<label>Test Email Address:</label>' . PHP_EOL;
        echo '<input type="email" name="test_email" placeholder="test@example.com" required>' . PHP_EOL;
        echo '</div>';
        echo '<button type="submit">Send Test OTP</button>';
        echo '</form>';
        echo '</div>';
        
        // Summary
        echo "<h2>Summary</h2>";
        echo '<div class="test info">';
        foreach ($tests as $test) {
            $status_class = $test[1] === 'PASS' ? 'status-pass' : 'status-fail';
            echo $test[0] . '<span class="status ' . $status_class . '">' . $test[1] . '</span>' . PHP_EOL;
        }
        echo '</div>';
        
        // Error Log
        echo "<h2>Check These Files</h2>";
        echo '<div class="test info">';
        echo '<p><strong>Error Log:</strong></p>';
        echo '<pre>';
        if (file_exists('error_log')) {
            $lines = file('error_log', FILE_SKIP_EMPTY_LINES);
            $recent = array_slice($lines, -20);
            echo implode('', $recent);
        } else {
            echo 'error_log file not found';
        }
        echo '</pre>';
        echo '</div>';
        
        ?>
    </div>
</body>
</html>
