<?php
/**
 * Email Configuration Test
 * Tests if PHPMailer is properly configured and can send emails
 */

session_start();

// Check if logged in
if (!isset($_SESSION['user_id'])) {
    die('<h2 style="color:red;">Please login first</h2>');
}

require_once __DIR__ . '/auth-system/EmailService.php';

$test_results = [];
$test_email = $_POST['test_email'] ?? '';
$send_test = isset($_POST['send_test']);

?>
<!DOCTYPE html>
<html>
<head>
    <title>Email Configuration Test</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: Arial, sans-serif; background: #f5f5f5; padding: 20px; }
        .container { max-width: 900px; margin: 0 auto; }
        h1 { color: #333; margin-bottom: 30px; }
        .section { background: white; padding: 20px; margin: 20px 0; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
        h2 { color: #333; border-bottom: 2px solid #d4a574; padding-bottom: 10px; margin-bottom: 15px; }
        .test-item { padding: 12px; margin: 10px 0; border-radius: 6px; border-left: 4px solid #999; }
        .pass { background: #d4edda; border-left-color: #28a745; color: #155724; }
        .fail { background: #f8d7da; border-left-color: #dc3545; color: #721c24; }
        .info { background: #d1ecf1; border-left-color: #17a2b8; color: #0c5460; }
        .form-group { margin: 15px 0; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input { padding: 10px; border: 1px solid #ddd; border-radius: 5px; width: 100%; }
        button { padding: 10px 20px; background: #d4a574; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: bold; margin-top: 10px; }
        button:hover { background: #b8905a; }
        .code { background: #f4f4f4; padding: 10px; border-radius: 5px; font-family: monospace; font-size: 12px; overflow-x: auto; margin: 10px 0; }
        .success { color: #28a745; font-weight: bold; }
        .error { color: #dc3545; font-weight: bold; }
    </style>
</head>
<body>
    <div class="container">
        <h1>📧 Email Service Configuration Test</h1>

        <!-- PHPMailer Status -->
        <div class="section">
            <h2>✅ System Check</h2>
            <?php
            // Check 1: PHPMailer files exist
            $phpmailer_check = file_exists(__DIR__ . '/auth-system/PHPMailer/src/PHPMailer.php');
            echo '<div class="test-item ' . ($phpmailer_check ? 'pass' : 'fail') . '">';
            echo $phpmailer_check ? '✓ ' : '✗ ';
            echo 'PHPMailer Files Installed: ';
            echo $phpmailer_check ? '<span class="success">YES</span>' : '<span class="error">NO (Install PHPMailer first)</span>';
            echo '</div>';

            // Check 2: EmailService exists
            $emailservice_check = file_exists(__DIR__ . '/auth-system/EmailService.php');
            echo '<div class="test-item ' . ($emailservice_check ? 'pass' : 'fail') . '">';
            echo $emailservice_check ? '✓ ' : '✗ ';
            echo 'EmailService.php Exists: ';
            echo $emailservice_check ? '<span class="success">YES</span>' : '<span class="error">NO</span>';
            echo '</div>';

            // Check 3: Database connection
            try {
                if (file_exists(__DIR__ . '/auth-system/config/db.php')) {
                    require_once __DIR__ . '/auth-system/config/db.php';
                    $db_check = isset($connection) && $connection->ping();
                } else {
                    $db_check = false;
                }
            } catch (Exception $e) {
                $db_check = false;
            }
            echo '<div class="test-item ' . ($db_check ? 'pass' : 'fail') . '">';
            echo $db_check ? '✓ ' : '✗ ';
            echo 'Database Connected: ';
            echo $db_check ? '<span class="success">YES</span>' : '<span class="error">NO (Not required for email testing)</span>';
            echo '</div>';

            // Check 4: OTP Table exists
            if ($db_check) {
                $result = $connection->query("SHOW TABLES LIKE 'otp_verification'");
                $otp_table_check = $result && $result->num_rows > 0;
                echo '<div class="test-item ' . ($otp_table_check ? 'pass' : 'fail') . '">';
                echo $otp_table_check ? '✓ ' : '✗ ';
                echo 'OTP Verification Table Exists: ';
                echo $otp_table_check ? '<span class="success">YES</span>' : '<span class="error">NO (Create table first)</span>';
                echo '</div>';
            }
            ?>
        </div>

        <!-- Send Test Email -->
        <div class="section">
            <h2>📤 Send Test Email</h2>
            <form method="POST">
                <div class="form-group">
                    <label for="test_email">Recipient Email:</label>
                    <input type="email" id="test_email" name="test_email" placeholder="Enter email address" value="<?php echo htmlspecialchars($test_email); ?>" required>
                </div>
                <button type="submit" name="send_test" value="1">Send Test OTP Email</button>
            </form>

            <?php
            if ($send_test && $test_email) {
                echo '<div class="test-item info" style="margin-top: 15px;">';
                echo '<strong>Sending test email to: ' . htmlspecialchars($test_email) . '</strong><br>';
                
                // Generate test OTP
                $test_otp = EmailService::generateOTP(6);
                
                // Send email
                $result = EmailService::sendEmailVerificationOTP($test_email, 'Test User', $test_otp);
                
                if ($result) {
                    echo '<br><span class="success">✓ Email sent successfully!</span>';
                    echo '<br>Check your inbox or spam folder for the test email.';
                    echo '<br><strong>Test OTP Code:</strong> ' . $test_otp;
                } else {
                    echo '<br><span class="error">✗ Email failed to send</span>';
                    echo '<br>Possible issues:';
                    echo '<ul style="margin-left: 20px; margin-top: 10px;">';
                    echo '<li>Gmail SMTP credentials incorrect</li>';
                    echo '<li>App password expired or invalid</li>';
                    echo '<li>PHPMailer not installed properly</li>';
                    echo '<li>Email address is invalid</li>';
                    echo '</ul>';
                }
                echo '</div>';
            }
            ?>
        </div>

        <!-- Email Service Configuration -->
        <div class="section">
            <h2>⚙️ Current Configuration</h2>
            <div class="code">
SMTP Server: smtp.gmail.com<br>
Port: 465<br>
Security: SMTPS (SSL)<br>
Username: mohamedhalith117@gmail.com<br>
Auth Method: Enabled<br>
            </div>
            <p style="color: #666; font-size: 13px; margin-top: 10px;">
                <strong>Note:</strong> If emails aren't sending, verify that:
                <ul style="margin-top: 10px; margin-left: 20px;">
                    <li>Gmail account has 2FA enabled</li>
                    <li>App password is generated and correct</li>
                    <li>PHPMailer files are properly installed in auth-system/PHPMailer/</li>
                    <li>The email address being used is Gmail</li>
                </ul>
            </p>
        </div>

        <!-- Email Log -->
        <div class="section">
            <h2>📋 Recent Email Logs</h2>
            <?php
            $log_file = __DIR__ . '/auth-system/logs/email_log.txt';
            if (file_exists($log_file)) {
                $logs = file_get_contents($log_file);
                $log_lines = array_slice(explode("\n", $logs), -20); // Last 20 lines
                echo '<div class="code">';
                foreach (array_reverse($log_lines) as $line) {
                    if (trim($line)) {
                        echo htmlspecialchars($line) . '<br>';
                    }
                }
                echo '</div>';
            } else {
                echo '<p style="color: #999;">No email logs found. Try sending a test email first.</p>';
            }
            ?>
        </div>

        <!-- Help Section -->
        <div class="section">
            <h2>🆘 Troubleshooting</h2>
            <h3 style="color: #333; margin: 15px 0;">If emails aren't sending:</h3>
            <ol style="margin-left: 20px; line-height: 1.8;">
                <li><strong>Check PHPMailer Installation:</strong>
                    <div class="code" style="margin: 5px 0;">
                        Visit: http://localhost/interior/verify-phpmailer.php
                    </div>
                </li>
                <li><strong>Verify Gmail Credentials:</strong>
                    <ul style="margin: 10px 0 10px 20px;">
                        <li>Gmail 2FA must be enabled</li>
                        <li>Generate app password from: https://myaccount.google.com/apppasswords</li>
                        <li>Copy the 16-character password (remove spaces)</li>
                    </ul>
                </li>
                <li><strong>Enable SMTP Debug:</strong>
                    <div class="code" style="margin: 5px 0;">
In EmailService.php, change:
$mail->SMTPDebug = 0;  // to 2 for debugging
                    </div>
                </li>
                <li><strong>Check Email Logs:</strong>
                    <div class="code" style="margin: 5px 0;">
cat auth-system/logs/email_log.txt
                    </div>
                </li>
            </ol>
        </div>

        <div style="text-align: center; margin-top: 30px;">
            <a href="admin-dashboard.php" style="color: #d4a574; text-decoration: none;">← Back to Admin Dashboard</a>
        </div>
    </div>
</body>
</html>
