<?php
/**
 * Admin Email Settings - Clean Version
 * Shows only essential fields
 * Backend handles all configuration
 */

if (!isset($db)) {
    echo '<div class="alert alert-danger">Database connection missing.</div>';
    return;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_email_settings'])) {
    try {
        $mail_username = trim($_POST['mail_username'] ?? '');
        $mail_from_email = trim($_POST['mail_from_email'] ?? '');
        $mail_from_name = trim($_POST['mail_from_name'] ?? '');
        $test_email = trim($_POST['test_email'] ?? '');
        
        // Update database
        $settingKeys = [
            'mail_username' => $mail_username,
            'mail_from_email' => $mail_from_email,
            'mail_from_name' => $mail_from_name,
            'test_email' => $test_email
        ];
        
        foreach ($settingKeys as $key => $value) {
            if (empty($value)) continue;
            
            $exists = $db->fetch(
                'SELECT id FROM admin_settings WHERE setting_key = ?',
                [$key]
            );
            
            if ($exists) {
                $db->update(
                    'admin_settings',
                    ['setting_value' => $value],
                    'setting_key = ?',
                    [$key]
                );
            } else {
                $db->insert(
                    'admin_settings',
                    [
                        'setting_key' => $key,
                        'setting_value' => $value
                    ]
                );
            }
        }
        
        echo '<div class="alert alert-success alert-dismissible fade show" role="alert">
                Settings updated successfully!
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
              </div>';
              
    } catch (Exception $e) {
        echo '<div class="alert alert-danger">Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
    }
}

// Fetch current settings
$settings = [];
$settingsList = ['mail_username', 'mail_from_email', 'mail_from_name', 'test_email'];

foreach ($settingsList as $key) {
    $setting = $db->fetch(
        'SELECT setting_value FROM admin_settings WHERE setting_key = ?',
        [$key]
    );
    $settings[$key] = $setting['setting_value'] ?? '';
}

?>

<!-- Email Settings Card -->
<div class="card shadow-sm border-0 mb-4">
    <div class="card-header bg-gradient" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none;">
        <h5 class="mb-0">Email Configuration</h5>
    </div>
    
    <div class="card-body">
        <form method="POST" class="needs-validation">
            <input type="hidden" name="save_email_settings" value="1">
            
            <!-- Admin Email Username -->
            <div class="mb-4">
                <label class="form-label fw-semibold">Admin Email (Username)</label>
                <input type="email" name="mail_username" class="form-control" 
                       value="<?= htmlspecialchars($settings['mail_username']) ?>" 
                       placeholder="admin@example.com" required>
                <small class="text-muted d-block mt-1">Email address used to send OTPs</small>
            </div>
            
            <!-- From Email Address -->
            <div class="mb-4">
                <label class="form-label fw-semibold">From Email Address</label>
                <input type="email" name="mail_from_email" class="form-control" 
                       value="<?= htmlspecialchars($settings['mail_from_email']) ?>" 
                       placeholder="noreply@example.com" required>
                <small class="text-muted d-block mt-1">Email that appears as sender in OTP emails</small>
            </div>
            
            <!-- From Name -->
            <div class="mb-4">
                <label class="form-label fw-semibold">From Name</label>
                <input type="text" name="mail_from_name" class="form-control" 
                       value="<?= htmlspecialchars($settings['mail_from_name']) ?>" 
                       placeholder="Advanced Mobile Info" required>
                <small class="text-muted d-block mt-1">Company/app name shown in emails</small>
            </div>
            
            <!-- Test Email -->
            <div class="mb-4">
                <label class="form-label fw-semibold">Test Email Address</label>
                <input type="email" name="test_email" class="form-control" 
                       value="<?= htmlspecialchars($settings['test_email']) ?>" 
                       placeholder="test@example.com">
                <small class="text-muted d-block mt-1">Where to send test emails</small>
            </div>
            
            <!-- Save Button -->
            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                <button type="submit" class="btn btn-primary px-4">Save Settings</button>
            </div>
        </form>
        
        <!-- SPF Configuration Alert -->
        <div class="alert alert-info alert-dismissible fade show mt-4" role="alert">
            <h6 class="alert-heading"><i class="bi bi-info-circle"></i> Email Deliverability Setup</h6>
            <p class="mb-2">To prevent OTP emails from going to spam:</p>
            <ol class="mb-0">
                <li>Login to <strong>Razorhost cPanel</strong> → Zone Editor</li>
                <li>Add TXT Record with:
                    <div class="bg-light p-2 rounded mt-1" style="font-family: monospace; font-size: 12px;">
                        Type: TXT<br>
                        Name: simplechecks.xyz<br>
                        Value: <code>v=spf1 include:brevo.com ~all</code>
                    </div>
                </li>
                <li>Wait 15-30 minutes for DNS propagation</li>
                <li>Test with button below after propagation</li>
            </ol>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        
        <!-- Test Email Button -->
        <div class="mt-3">
            <form method="POST" class="d-inline">
                <input type="hidden" name="send_test_email" value="1">
                <button type="submit" class="btn btn-outline-info btn-sm">
                    <i class="bi bi-envelope-check"></i> Send Test Email
                </button>
            </form>
            <?php
            // Handle test email
            if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_test_email'])) {
                $testEmail = $settings['test_email'] ?? '';
                if ($testEmail) {
                    // Send test email directly via Brevo
                    $fromEmail = $settings['mail_from_email'] ?? 'noreply@simplechecks.xyz';
                    $fromName = $settings['mail_from_name'] ?? 'Advanced Mobile Info';
                    
                    $apiKey = getenv('BREVO_API_KEY') ?: ($db->fetch('SELECT setting_value FROM admin_settings WHERE setting_key = "brevo_api_key"')['setting_value'] ?? '');
                    
                    if ($apiKey) {
                        $payload = json_encode([
                            'sender' => ['email' => $fromEmail, 'name' => $fromName],
                            'to' => [['email' => $testEmail, 'name' => 'Test Recipient']],
                            'subject' => 'Test Email from ' . $fromName,
                            'htmlContent' => '<h2>Test Email</h2><p>This is a test email to verify your email configuration is working correctly.</p><p style="color: green;"><strong>✓ Your email settings are properly configured!</strong></p>',
                            'replyTo' => ['email' => $fromEmail],
                            'tags' => ['test', 'configuration']
                        ]);
                        
                        $ch = curl_init('https://api.brevo.com/v3/smtp/email');
                        curl_setopt_array($ch, [
                            CURLOPT_RETURNTRANSFER => true,
                            CURLOPT_HTTPHEADER => [
                                'Accept: application/json',
                                'Content-Type: application/json',
                                'api-key: ' . $apiKey
                            ],
                            CURLOPT_POSTFIELDS => $payload,
                            CURLOPT_TIMEOUT => 10
                        ]);
                        
                        $response = curl_exec($ch);
                        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                        curl_close($ch);
                        
                        if ($httpCode === 201) {
                            echo '<span class="text-success ms-2"><i class="bi bi-check-circle"></i> Test email sent! Check inbox.</span>';
                        } else {
                            echo '<span class="text-danger ms-2"><i class="bi bi-x-circle"></i> Failed to send (Code: ' . $httpCode . ')</span>';
                        }
                    } else {
                        echo '<span class="text-warning ms-2"><i class="bi bi-exclamation-circle"></i> Brevo API key not configured</span>';
                    }
                } else {
                    echo '<span class="text-warning ms-2"><i class="bi bi-exclamation-circle"></i> Set test email first</span>';
                }
            }
            ?>
        </div>
    </div>
</div>

<!-- Email Verification Status Grid -->
<div class="card shadow-sm border-0">
    <div class="card-header bg-gradient" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none;">
        <h5 class="mb-0">User Email Verification Status</h5>
    </div>
    
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th>User</th>
                        <th>Email</th>
                        <th>Status</th>
                        <th>OTP Code</th>
                        <th>OTP Expires</th>
                        <th>Attempts</th>
                        <th>Created</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // Get all users - simple query first
                    $query = 'SELECT * FROM users ORDER BY created_at DESC LIMIT 50';
                    
                    $result = $db->query($query);
                    $users = [];
                    
                    if ($result) {
                        $users = $result->fetchAll(PDO::FETCH_ASSOC);
                    }
                    
                    if (!empty($users)) {
                        foreach ($users as $user) {
                            // Get OTP for this user
                            $otp = $db->fetch(
                                'SELECT * FROM email_otps WHERE email = ? LIMIT 1',
                                [$user['email']]
                            );
                            
                            // Determine status
                            if ($user['email_verified']) {
                                $status = '<span class="badge bg-success">Verified</span>';
                                $statusClass = '';
                            } else if ($otp && $otp['otp']) {
                                $status = '<span class="badge bg-warning">Pending</span>';
                                $statusClass = 'table-warning';
                            } else {
                                $status = '<span class="badge bg-secondary">Not Started</span>';
                                $statusClass = '';
                            }
                            
                            // Check OTP expiry
                            $otpStatus = '';
                            if ($otp && $otp['expires_at']) {
                                $expiryCheck = $db->fetch(
                                    'SELECT CASE WHEN NOW() > ? THEN "EXPIRED" ELSE "VALID" END as status',
                                    [$otp['expires_at']]
                                );
                                $otpStatus = $expiryCheck['status'] === 'EXPIRED' ? 'EXPIRED' : 'Valid';
                            }
                    ?>
                    <tr class="<?= $statusClass ?>">
                        <td>
                            <strong><?= htmlspecialchars($user['name']) ?></strong>
                        </td>
                        <td><?= htmlspecialchars($user['email']) ?></td>
                        <td><?= $status ?></td>
                        <td>
                            <?php if ($otp && $otp['otp']): ?>
                                <code><?= htmlspecialchars($otp['otp']) ?></code>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($otp && $otp['expires_at']): ?>
                                <small><?= $otp['expires_at'] ?></small>
                                <br>
                                <small class="<?= $otpStatus === 'EXPIRED' ? 'text-danger' : 'text-success' ?>">
                                    <?= $otpStatus ?>
                                </small>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($otp && $otp['attempts'] !== null): ?>
                                <span class="badge <?= $otp['attempts'] >= 5 ? 'bg-danger' : 'bg-info' ?>">
                                    <?= $otp['attempts'] ?>/5
                                </span>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td>
                            <small><?= date('M d, Y', strtotime($user['created_at'])) ?></small>
                        </td>
                    </tr>
                    <?php
                        }
                    } else {
                        echo '<tr><td colspan="7" class="text-center text-muted py-4">No users yet</td></tr>';
                    }
                    ?>
                </tbody>
            </table>
        </div>
        
        <!-- Summary Stats -->
        <div class="row mt-4 g-3">
            <?php
            $totalUsers = $db->fetch('SELECT COUNT(*) as cnt FROM users');
            $verifiedUsers = $db->fetch('SELECT COUNT(*) as cnt FROM users WHERE email_verified = 1');
            $pendingOTP = $db->fetch('SELECT COUNT(*) as cnt FROM email_otps WHERE expires_at > NOW()');
            $expiredOTP = $db->fetch('SELECT COUNT(*) as cnt FROM email_otps WHERE expires_at <= NOW()');
            ?>
            <div class="col-md-3">
                <div class="card border-0 shadow-sm">
                    <div class="card-body text-center">
                        <h6 class="text-muted mb-2">Total Users</h6>
                        <h3 class="mb-0" style="color: #667eea;"><strong><?= $totalUsers['cnt'] ?></strong></h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card border-0 shadow-sm">
                    <div class="card-body text-center">
                        <h6 class="text-muted mb-2">Verified Emails</h6>
                        <h3 class="mb-0" style="color: #28a745;"><strong><?= $verifiedUsers['cnt'] ?></strong></h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card border-0 shadow-sm">
                    <div class="card-body text-center">
                        <h6 class="text-muted mb-2">Active OTPs</h6>
                        <h3 class="mb-0" style="color: #ffc107;"><strong><?= $pendingOTP['cnt'] ?></strong></h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card border-0 shadow-sm">
                    <div class="card-body text-center">
                        <h6 class="text-muted mb-2">Expired OTPs</h6>
                        <h3 class="mb-0" style="color: #dc3545;"><strong><?= $expiredOTP['cnt'] ?></strong></h3>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

