<?php
/**
 * Email Delivery Diagnostic Tool
 * Identifies why registration emails aren't being received
 */

session_start();

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

// Collect diagnostic info
$diagnostics = [
    'timestamp' => date('Y-m-d H:i:s'),
    'phpmailer_files' => [],
    'emailservice' => false,
    'database' => false,
    'logs_dir' => false,
    'recent_logs' => []
];

// Check PHPMailer files
$phpmailer_base = __DIR__ . '/auth-system/PHPMailer/src';
$diagnostics['phpmailer_files'] = [
    'PHPMailer.php' => file_exists($phpmailer_base . '/PHPMailer.php'),
    'SMTP.php' => file_exists($phpmailer_base . '/SMTP.php'),
    'Exception.php' => file_exists($phpmailer_base . '/Exception.php'),
];

// Check EmailService
$diagnostics['emailservice'] = file_exists(__DIR__ . '/auth-system/EmailService.php');

// Check Database
try {
    if (file_exists(__DIR__ . '/auth-system/config/db.php')) {
        require_once __DIR__ . '/auth-system/config/db.php';
        $diagnostics['database'] = isset($connection) && !($connection instanceof mysqli) ? false : (isset($connection) ? $connection->ping() : false);
    }
} catch (Exception $e) {
    $diagnostics['database'] = false;
}

// Check logs directory
$logs_dir = __DIR__ . '/auth-system/logs';
$diagnostics['logs_dir'] = is_dir($logs_dir);

// Get recent logs
if ($diagnostics['logs_dir'] && file_exists($logs_dir . '/email_log.txt')) {
    $logs = file_get_contents($logs_dir . '/email_log.txt');
    $diagnostics['recent_logs'] = array_slice(explode("\n", $logs), -5);
}

// Determine status
$all_ok = array_reduce($diagnostics['phpmailer_files'], fn($c, $i) => $c && $i, true) &&
          $diagnostics['emailservice'] &&
          $diagnostics['database'] &&
          $diagnostics['logs_dir'];

?>
<!DOCTYPE html>
<html>
<head>
    <title>Email Delivery Diagnostics</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px; }
        .container { max-width: 1000px; margin: 0 auto; }
        h1 { color: white; margin-bottom: 30px; text-align: center; }
        .card { background: white; border-radius: 10px; padding: 25px; margin: 20px 0; box-shadow: 0 10px 30px rgba(0,0,0,0.2); }
        h2 { color: #333; border-bottom: 3px solid #667eea; padding-bottom: 15px; margin-bottom: 20px; }
        .status-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin: 15px 0; }
        .status-item { padding: 15px; border-radius: 8px; border-left: 4px solid; }
        .ok { background: #d4edda; border-left-color: #28a745; }
        .fail { background: #f8d7da; border-left-color: #dc3545; }
        .item-title { font-weight: bold; color: #333; }
        .item-value { font-size: 18px; font-weight: bold; margin-top: 5px; }
        .ok .item-value { color: #28a745; }
        .fail .item-value { color: #dc3545; }
        .action-buttons { display: flex; gap: 10px; margin-top: 20px; flex-wrap: wrap; }
        .btn { padding: 12px 24px; border: none; border-radius: 6px; cursor: pointer; font-weight: bold; text-decoration: none; display: inline-block; text-align: center; }
        .btn-primary { background: #667eea; color: white; }
        .btn-primary:hover { background: #5568d3; }
        .btn-secondary { background: #6c757d; color: white; }
        .btn-secondary:hover { background: #5a6268; }
        .recommendations { background: #e7f3ff; border-left: 4px solid #2196F3; padding: 15px; border-radius: 6px; margin: 15px 0; }
        .recommendation-item { margin: 10px 0; padding: 10px; }
        .recommendation-item strong { color: #1976d2; }
        .code-block { background: #f5f5f5; padding: 15px; border-radius: 6px; font-family: 'Courier New'; font-size: 13px; overflow-x: auto; margin: 10px 0; }
        .logs { background: #f5f5f5; padding: 15px; border-radius: 6px; font-family: 'Courier New'; font-size: 12px; max-height: 300px; overflow-y: auto; }
        .log-entry { padding: 5px 0; border-bottom: 1px solid #eee; }
        .log-entry:last-child { border-bottom: none; }
    </style>
</head>
<body>
    <div class="container">
        <h1>📊 Email Delivery Diagnostics</h1>

        <!-- Overall Status -->
        <div class="card">
            <h2>🔍 System Status</h2>
            <div class="status-grid">
                <div class="status-item <?php echo $diagnostics['phpmailer_files']['PHPMailer.php'] ? 'ok' : 'fail'; ?>">
                    <div class="item-title">PHPMailer Files</div>
                    <div class="item-value"><?php echo $diagnostics['phpmailer_files']['PHPMailer.php'] ? '✓ Installed' : '✗ Missing'; ?></div>
                </div>
                <div class="status-item <?php echo $diagnostics['emailservice'] ? 'ok' : 'fail'; ?>">
                    <div class="item-title">EmailService.php</div>
                    <div class="item-value"><?php echo $diagnostics['emailservice'] ? '✓ Found' : '✗ Missing'; ?></div>
                </div>
                <div class="status-item <?php echo $diagnostics['database'] ? 'ok' : 'fail'; ?>">
                    <div class="item-title">Database Connection</div>
                    <div class="item-value"><?php echo $diagnostics['database'] ? '✓ Connected' : '✗ Failed'; ?></div>
                </div>
                <div class="status-item <?php echo $diagnostics['logs_dir'] ? 'ok' : 'fail'; ?>">
                    <div class="item-title">Logs Directory</div>
                    <div class="item-value"><?php echo $diagnostics['logs_dir'] ? '✓ Exists' : '✗ Missing'; ?></div>
                </div>
            </div>
        </div>

        <!-- Detailed PHPMailer Check -->
        <div class="card">
            <h2>📦 PHPMailer Installation</h2>
            <div class="status-grid">
                <?php foreach ($diagnostics['phpmailer_files'] as $file => $status): ?>
                    <div class="status-item <?php echo $status ? 'ok' : 'fail'; ?>">
                        <div class="item-title"><?php echo $file; ?></div>
                        <div class="item-value"><?php echo $status ? '✓ OK' : '✗ Missing'; ?></div>
                    </div>
                <?php endforeach; ?>
            </div>
            <?php if (!array_reduce($diagnostics['phpmailer_files'], fn($c, $i) => $c && $i, true)): ?>
                <div class="recommendations">
                    <div class="recommendation-item">
                        <strong>⚠️ Action Required:</strong> PHPMailer files are missing!<br>
                        Download the missing files and place them in: <code>auth-system/PHPMailer/src/</code>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- Email Configuration -->
        <div class="card">
            <h2>⚙️ Email Configuration</h2>
            <div class="code-block">
SMTP Host: smtp.gmail.com<br>
SMTP Port: 465<br>
SMTP Security: SMTPS (SSL)<br>
Auth: Enabled<br>
Username: mohamedhalith117@gmail.com<br>
            </div>
            <div class="recommendations">
                <div class="recommendation-item">
                    <strong>💡 Tip:</strong> If using Gmail, ensure:
                    <ul style="margin: 10px 0 0 15px;">
                        <li>✓ 2FA is enabled on your Gmail account</li>
                        <li>✓ An "App Password" is generated (not regular password)</li>
                        <li>✓ The 16-character app password is copied to EmailService.php</li>
                    </ul>
                </div>
            </div>
        </div>

        <!-- Recent Logs -->
        <div class="card">
            <h2>📋 Recent Email Logs</h2>
            <?php if (!empty(array_filter($diagnostics['recent_logs']))): ?>
                <div class="logs">
                    <?php foreach (array_reverse(array_filter($diagnostics['recent_logs'])) as $log): ?>
                        <div class="log-entry"><?php echo htmlspecialchars($log); ?></div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p style="color: #999;">No email logs found. Send a test email to generate logs.</p>
            <?php endif; ?>
        </div>

        <!-- Recommendations -->
        <div class="card">
            <h2>📝 Recommendations</h2>
            <div class="recommendations">
                <div class="recommendation-item">
                    <strong>Step 1:</strong> Visit <a href="test-email-config.php" style="color: #1976d2;">test-email-config.php</a> to test email sending
                </div>
                <div class="recommendation-item">
                    <strong>Step 2:</strong> Send a test email to verify configuration works
                </div>
                <div class="recommendation-item">
                    <strong>Step 3:</strong> Check your email inbox (including spam folder) for the test message
                </div>
                <div class="recommendation-item">
                    <strong>Step 4:</strong> If test fails, review the troubleshooting guide: <a href="EMAIL_TROUBLESHOOTING.md" style="color: #1976d2;">EMAIL_TROUBLESHOOTING.md</a>
                </div>
                <div class="recommendation-item">
                    <strong>Step 5:</strong> Once working, try registering at <a href="auth-system/register.php" style="color: #1976d2;">register.php</a>
                </div>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="card">
            <h2>🚀 Next Steps</h2>
            <div class="action-buttons">
                <a href="test-email-config.php" class="btn btn-primary">Send Test Email</a>
                <a href="verify-phpmailer.php" class="btn btn-primary">Verify PHPMailer</a>
                <a href="EMAIL_TROUBLESHOOTING.md" class="btn btn-secondary">View Troubleshooting Guide</a>
                <a href="admin-dashboard.php" class="btn btn-secondary">Back to Dashboard</a>
            </div>
        </div>
    </div>
</body>
</html>
