<?php
// Email testing page - Development only
session_start();

// Check if user is logged in as admin (or allow in development)
$is_admin = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin';
$allow_access = $is_admin || getenv('DEVELOPMENT') === 'true';

require_once 'EmailService.php';
$emailService = new EmailService();

// Get email status
$status = $emailService->checkEmailStatus();

// Get recent emails if in dev mode
$recent_emails = $status['dev_mode'] ? $emailService->getRecentEmails(20) : array();

// Test email sending on form submission
$test_result = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $to_email = $_POST['email'] ?? '';
    $email_type = $_POST['email_type'] ?? 'otp';
    
    if (filter_var($to_email, FILTER_VALIDATE_EMAIL)) {
        $otp_code = $emailService->generateOTP(6);
        
        if ($email_type === 'otp') {
            $result = $emailService->sendEmailVerificationOTP($to_email, 'Test User', $otp_code);
            $test_result = $result ? '✅ Email logged successfully (Check logs)' : '❌ Failed to log email';
        } elseif ($email_type === 'reset') {
            $reset_link = 'http://localhost/interior/auth-system/forgot-password.php?token=' . $emailService->generateResetToken();
            $result = $emailService->sendPasswordResetEmail($to_email, 'Test User', $reset_link);
            $test_result = $result ? '✅ Email logged successfully (Check logs)' : '❌ Failed to log email';
        } elseif ($email_type === '2fa') {
            $result = $emailService->send2FAOTP($to_email, 'Test User', $otp_code);
            $test_result = $result ? '✅ Email logged successfully (Check logs)' : '❌ Failed to log email';
        }
    } else {
        $test_result = '❌ Invalid email address';
    }
}

// Read today's log file
$log_file = dirname(__FILE__) . '/logs/emails/' . date('Y-m-d') . '.log';
$log_content = file_exists($log_file) ? file_get_contents($log_file) : 'No emails logged yet today.';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Testing - Faren</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'DM Sans', Arial, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .header {
            background: linear-gradient(135deg, #D4A574 0%, #b8905a 100%);
            color: white;
            padding: 30px;
            border-radius: 8px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        .header p {
            font-size: 1.1em;
            opacity: 0.95;
        }
        .content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            margin-bottom: 30px;
        }
        .card {
            background: white;
            border-radius: 8px;
            padding: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .card h2 {
            color: #D4A574;
            margin-bottom: 20px;
            font-size: 1.5em;
        }
        .status-box {
            background: #f0e6d8;
            border-left: 4px solid #D4A574;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 4px;
        }
        .status-box.success {
            border-left-color: #28a745;
            background: #d4edda;
        }
        .status-box.error {
            border-left-color: #dc3545;
            background: #f8d7da;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            color: #333;
            font-weight: 500;
        }
        input, select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-family: inherit;
            font-size: 0.95em;
        }
        input:focus, select:focus {
            outline: none;
            border-color: #D4A574;
            box-shadow: 0 0 5px rgba(212, 165, 116, 0.3);
        }
        button {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #D4A574 0%, #b8905a 100%);
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 1em;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s;
        }
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(212, 165, 116, 0.3);
        }
        .info-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-bottom: 20px;
        }
        .info-item {
            background: #f9f9f9;
            padding: 12px;
            border-radius: 4px;
            border-left: 3px solid #D4A574;
        }
        .info-item strong {
            color: #D4A574;
        }
        .logs-section {
            grid-column: 1 / -1;
        }
        .log-viewer {
            background: #1a1a1a;
            color: #00ff00;
            padding: 15px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            font-size: 0.85em;
            max-height: 400px;
            overflow-y: auto;
            white-space: pre-wrap;
            word-break: break-all;
            line-height: 1.4;
        }
        .test-result {
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 15px;
            font-weight: 600;
        }
        .test-result.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .test-result.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .feature-list {
            list-style: none;
            margin: 15px 0;
        }
        .feature-list li {
            padding: 8px 0;
            border-bottom: 1px solid #eee;
        }
        .feature-list li:before {
            content: "✅ ";
            color: #28a745;
            margin-right: 8px;
        }
        .footer {
            text-align: center;
            color: #999;
            padding-top: 20px;
            border-top: 1px solid #ddd;
        }
        @media (max-width: 768px) {
            .content {
                grid-template-columns: 1fr;
            }
            .header h1 {
                font-size: 1.8em;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📧 Email System Testing</h1>
            <p>Development Email Service - All emails are logged to files</p>
        </div>

        <div class="content">
            <!-- Status Card -->
            <div class="card">
                <h2>System Status</h2>
                
                <div class="status-box success">
                    <strong>Mode:</strong> <?php echo $status['mode']; ?>
                </div>

                <div class="info-grid">
                    <div class="info-item">
                        <strong>Status:</strong><br>
                        <?php echo $status['status']; ?>
                    </div>
                    <div class="info-item">
                        <strong>Log Directory:</strong><br>
                        logs/emails/
                    </div>
                </div>

                <h3 style="margin-top: 20px; margin-bottom: 10px; color: #333;">Features</h3>
                <ul class="feature-list">
                    <li>📧 Email verification OTP</li>
                    <li>🔐 Password reset emails</li>
                    <li>🔑 Two-factor authentication (2FA)</li>
                    <li>💾 All emails logged to files</li>
                    <li>📝 View all sent emails</li>
                </ul>
            </div>

            <!-- Test Form Card -->
            <div class="card">
                <h2>Test Email Sending</h2>

                <?php if ($test_result): ?>
                    <div class="test-result <?php echo strpos($test_result, '✅') === 0 ? 'success' : 'error'; ?>">
                        <?php echo $test_result; ?>
                    </div>
                <?php endif; ?>

                <form method="POST">
                    <div class="form-group">
                        <label for="email">Test Email Address:</label>
                        <input type="email" id="email" name="email" placeholder="test@example.com" required>
                    </div>

                    <div class="form-group">
                        <label for="email_type">Email Type:</label>
                        <select id="email_type" name="email_type" required>
                            <option value="otp">Registration OTP</option>
                            <option value="reset">Password Reset</option>
                            <option value="2fa">2FA Code</option>
                        </select>
                    </div>

                    <button type="submit">Send Test Email</button>
                </form>

                <p style="margin-top: 15px; font-size: 0.9em; color: #666;">
                    ℹ️ All test emails will be logged to the logs/emails directory.
                </p>
            </div>

            <!-- Logs Viewer -->
            <div class="card logs-section">
                <h2>Today's Email Logs</h2>
                <p style="margin-bottom: 15px; color: #666;">
                    Last updated: <?php echo date('Y-m-d H:i:s'); ?>
                </p>
                <div class="log-viewer">
<?php 
    // Display logs with syntax highlighting for important lines
    $log_lines = explode("\n", $log_content);
    foreach ($log_lines as $line) {
        if (strpos($line, 'To:') === 0 || strpos($line, 'Subject:') === 0) {
            echo '<span style="color: #ffff00;">' . htmlspecialchars($line) . '</span>' . "\n";
        } else {
            echo htmlspecialchars($line) . "\n";
        }
    }
?>
                </div>
            </div>
        </div>

        <div class="footer">
            <p>💡 Development Email Service | All emails logged to files | Configure SMTP to send real emails</p>
            <p style="margin-top: 10px; font-size: 0.9em;">
                To enable production mode, edit EmailService.php and set $dev_mode = false, then configure your SMTP settings in php.ini
            </p>
        </div>
    </div>
</body>
</html>
