<?php
/**
 * Admin — SMTP / Email Settings Page
 *
 * Dedicated page for configuring and testing SMTP settings.
 *
 * @var array $config          — current SMTP config (merged DB + defaults)
 * @var bool  $mailerAvailable
 * @var bool  $smtpConfigured
 * @var string|null $phpMailerPath
 * @var array $dbSettings      — raw DB values for debug
 * @var array $dbColumns       — which columns exist in settings table
 */
$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$csrf = htmlspecialchars($csrfToken ?? '', ENT_QUOTES, 'UTF-8');

// Status indicators
$hostOk      = !empty($config['smtp_host']);
$fromOk      = !empty($config['smtp_from_email']);
$authOk      = !empty($config['smtp_username']);
$portOk      = !empty($config['smtp_port']);

// Column info for debug
$hasAllCols = ($dbColumns['setting_key'] ?? false) && ($dbColumns['setting_value'] ?? false)
           && ($dbColumns['key_name'] ?? false) && ($dbColumns['value'] ?? false);
?>

<!-- Status Dashboard -->
<div class="admin-card" style="margin-bottom:1.5rem;">
    <div class="admin-card-header">
        <h3 class="admin-card-title">Email System Status</h3>
    </div>
    <div class="admin-card-body">
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:1rem;">
            <!-- PHPMailer Status -->
            <div style="padding:1rem;border-radius:8px;border:1px solid <?= $mailerAvailable ? '#43a047' : '#e53935' ?>;background:<?= $mailerAvailable ? '#e8f5e9' : '#ffebee' ?>;">
                <div style="display:flex;align-items:center;gap:0.5rem;margin-bottom:0.5rem;">
                    <?php if ($mailerAvailable): ?>
                    <svg viewBox="0 0 24 24" fill="#43a047" width="20" height="20"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>
                    <?php else: ?>
                    <svg viewBox="0 0 24 24" fill="#e53935" width="20" height="20"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/></svg>
                    <?php endif; ?>
                    <strong style="font-size:0.9rem;"><?= $mailerAvailable ? 'PHPMailer Found' : 'PHPMailer Missing' ?></strong>
                </div>
                <?php if ($mailerAvailable): ?>
                <p style="font-size:0.8rem;color:#555;margin:0;word-break:break-all;"><?= htmlspecialchars($phpMailerPath ?? '', ENT_QUOTES, 'UTF-8') ?></p>
                <?php else: ?>
                <p style="font-size:0.8rem;color:#c62828;margin:0;">Upload <code>phpmailer/src/</code> to project root</p>
                <?php endif; ?>
            </div>

            <!-- SMTP Connection Status -->
            <div style="padding:1rem;border-radius:8px;border:1px solid <?= $smtpConfigured ? '#43a047' : '#ff9800' ?>;background:<?= $smtpConfigured ? '#e8f5e9' : '#fff3e0' ?>;">
                <div style="display:flex;align-items:center;gap:0.5rem;margin-bottom:0.5rem;">
                    <?php if ($smtpConfigured): ?>
                    <svg viewBox="0 0 24 24" fill="#43a047" width="20" height="20"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>
                    <?php else: ?>
                    <svg viewBox="0 0 24 24" fill="#ff9800" width="20" height="20"><path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/></svg>
                    <?php endif; ?>
                    <strong style="font-size:0.9rem;"><?= $smtpConfigured ? 'SMTP Configured' : 'SMTP Incomplete' ?></strong>
                </div>
                <p style="font-size:0.8rem;color:#555;margin:0;">
                    Host: <?= $hostOk ? '<span style="color:#43a047;">Set</span>' : '<span style="color:#e53935;">Missing</span>' ?> |
                    From: <?= $fromOk ? '<span style="color:#43a047;">Set</span>' : '<span style="color:#e53935;">Missing</span>' ?> |
                    Auth: <?= $authOk ? '<span style="color:#43a047;">Set</span>' : '<span style="color:#999;">Optional</span>' ?>
                </p>
            </div>

            <!-- Quick Actions -->
            <div style="padding:1rem;border-radius:8px;border:1px solid #1a73e8;background:#e3f2fd;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:0.5rem;">
                <strong style="font-size:0.9rem;">Quick Test</strong>
                <div style="display:flex;gap:0.5rem;">
                    <form method="POST" action="<?= $bp ?>/admin/smtp-settings/test-connection">
                        <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
                        <button type="submit" class="admin-btn admin-btn-sm admin-btn-outline" <?= !$mailerAvailable ? 'disabled' : '' ?>>
                            Test Connection
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<?php if (!$mailerAvailable): ?>
<div class="admin-alert admin-alert-error" style="margin-bottom:1.5rem;">
    <strong>PHPMailer Not Found!</strong>
    <br><br>
    <strong>How to install PHPMailer:</strong>
    <ol style="margin:0.5rem 0 0 1.5rem;font-size:0.875rem;">
        <li>Download ZIP from <a href="https://github.com/PHPMailer/PHPMailer/releases" target="_blank" style="color:inherit;text-decoration:underline;">GitHub Releases</a></li>
        <li>Extract the downloaded ZIP file on your computer</li>
        <li>Inside the extracted folder, you will find a <code>src</code> subfolder</li>
        <li>Rename the main folder to <code>phpmailer</code> (lowercase)</li>
        <li>Upload the entire <code>phpmailer</code> folder to your server inside <code>/gmind/</code> via cPanel File Manager</li>
        <li>Final structure must be: <code>/gmind/phpmailer/src/PHPMailer.php</code></li>
    </ol>
</div>

<!-- Debug Info — Server Paths (only when PHPMailer missing) -->
<div class="admin-card" style="margin-bottom:1.5rem;border-color:#ff9800;">
    <div class="admin-card-header" style="background:#fff3e0;">
        <h3 class="admin-card-title" style="color:#e65100;">Debug — Server Path Info</h3>
    </div>
    <div class="admin-card-body">
        <table style="width:100%;font-size:0.8rem;border-collapse:collapse;">
            <tr style="background:#f5f5f5;">
                <td style="padding:6px 10px;font-weight:600;border:1px solid #e0e0e0;">DOCUMENT_ROOT</td>
                <td style="padding:6px 10px;border:1px solid #e0e0e0;font-family:monospace;"><?= htmlspecialchars($_SERVER['DOCUMENT_ROOT'] ?? 'not set', ENT_QUOTES, 'UTF-8') ?></td>
            </tr>
            <tr>
                <td style="padding:6px 10px;font-weight:600;border:1px solid #e0e0e0;">BASE_PATH</td>
                <td style="padding:6px 10px;border:1px solid #e0e0e0;font-family:monospace;"><?= htmlspecialchars(defined('BASE_PATH') ? BASE_PATH : 'not defined', ENT_QUOTES, 'UTF-8') ?></td>
            </tr>
            <tr style="background:#f5f5f5;">
                <td style="padding:6px 10px;font-weight:600;border:1px solid #e0e0e0;">phpmailer folder?</td>
                <td style="padding:6px 10px;border:1px solid #e0e0e0;">
                    <?php
                    $docRoot = rtrim($_SERVER['DOCUMENT_ROOT'] ?? '', '/');
                    $bpVal = defined('BASE_PATH') ? BASE_PATH : '';
                    $pmDir = $docRoot . $bpVal . '/phpmailer';
                    if (is_dir($pmDir)): ?>
                        <span style="color:#43a047;font-weight:600;">YES — Found</span>
                        <br><small>Contents: </small>
                        <?php
                        $items = @scandir($pmDir);
                        if ($items) {
                            $items = array_diff($items, ['.', '..']);
                            echo '<small style="font-family:monospace;">' . htmlspecialchars(implode(', ', $items), ENT_QUOTES, 'UTF-8') . '</small>';
                        }
                        ?>
                    <?php else: ?>
                        <span style="color:#e53935;">Not found at <code><?= htmlspecialchars($pmDir, ENT_QUOTES, 'UTF-8') ?></code></span>
                    <?php endif; ?>
                </td>
            </tr>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- Database Debug — Current Saved Values -->
<div class="admin-card" style="margin-bottom:1.5rem;border-color:#9c27b0;">
    <div class="admin-card-header" style="background:#f3e5f5;cursor:pointer;" onclick="document.getElementById('dbDebugSection').style.display = document.getElementById('dbDebugSection').style.display === 'none' ? 'block' : 'none'">
        <h3 class="admin-card-title" style="color:#6a1b9a;">Database — Current Saved Values (click to expand)</h3>
    </div>
    <div class="admin-card-body" id="dbDebugSection" style="display:none;">
        <p style="font-size:0.85rem;color:#666;margin-bottom:0.75rem;">
            This shows what is currently stored in your <code>settings</code> table for SMTP keys.
            If values are blank here after saving, the save is not working.
        </p>
        <table style="width:100%;font-size:0.8rem;border-collapse:collapse;">
            <tr style="background:#4a148c;color:#fff;">
                <th style="padding:8px 10px;text-align:left;border:1px solid #7b1fa2;">Setting Key</th>
                <th style="padding:8px 10px;text-align:left;border:1px solid #7b1fa2;">Saved Value</th>
                <th style="padding:8px 10px;text-align:left;border:1px solid #7b1fa2;">Status</th>
            </tr>
            <?php
            $smtpLabels = [
                'smtp_host' => 'SMTP Host',
                'smtp_port' => 'SMTP Port',
                'smtp_username' => 'SMTP Username',
                'smtp_password' => 'SMTP Password',
                'smtp_encryption' => 'Encryption',
                'smtp_from_email' => 'From Email',
                'smtp_from_name' => 'From Name',
            ];
            foreach ($smtpLabels as $key => $label):
                $savedVal = $dbSettings[$key] ?? null;
                $isSaved = ($savedVal !== null && $savedVal !== '');
            ?>
            <tr style="background:<?= $isSaved ? '#e8f5e9' : '#ffebee' ?>;">
                <td style="padding:6px 10px;font-weight:600;border:1px solid #e0e0e0;"><?= $label ?> <code style="font-size:0.75rem;color:#666;"><?= $key ?></code></td>
                <td style="padding:6px 10px;border:1px solid #e0e0e0;font-family:monospace;word-break:break-all;">
                    <?php if ($key === 'smtp_password' && $isSaved): ?>
                        •••••••• (hidden)
                    <?php elseif ($savedVal !== null): ?>
                        <?= htmlspecialchars($savedVal, ENT_QUOTES, 'UTF-8') ?: '<em style="color:#999;">(empty)</em>' ?>
                    <?php else: ?>
                        <em style="color:#e53935;">(not in database)</em>
                    <?php endif; ?>
                </td>
                <td style="padding:6px 10px;border:1px solid #e0e0e0;">
                    <?php if ($isSaved): ?>
                        <span style="color:#43a047;font-weight:600;">Saved</span>
                    <?php elseif ($savedVal === ''): ?>
                        <span style="color:#ff9800;font-weight:600;">Empty</span>
                    <?php else: ?>
                        <span style="color:#e53935;font-weight:600;">Not Found</span>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </table>

        <div style="margin-top:1rem;padding:0.75rem;background:#f5f5f5;border-radius:6px;font-size:0.8rem;">
            <strong>Table Columns Detected:</strong>
            setting_key: <?= ($dbColumns['setting_key'] ?? false) ? '<span style="color:#43a047;">YES</span>' : '<span style="color:#e53935;">NO</span>' ?> |
            setting_value: <?= ($dbColumns['setting_value'] ?? false) ? '<span style="color:#43a047;">YES</span>' : '<span style="color:#e53935;">NO</span>' ?> |
            key_name: <?= ($dbColumns['key_name'] ?? false) ? '<span style="color:#43a047;">YES</span>' : '<span style="color:#e53935;">NO</span>' ?> |
            value: <?= ($dbColumns['value'] ?? false) ? '<span style="color:#43a047;">YES</span>' : '<span style="color:#e53935;">NO</span>' ?>
            <?php if ($hasAllCols): ?>
                <br><span style="color:#43a047;font-weight:600;">All 4 columns found — save will use dual-column strategy.</span>
            <?php else: ?>
                <br><span style="color:#ff9800;font-weight:600;">Some columns missing — save will use available columns only.</span>
            <?php endif; ?>
        </div>

        <?php if (empty($dbSettings)): ?>
        <div style="margin-top:1rem;padding:0.75rem;background:#ffebee;border-radius:6px;font-size:0.85rem;border:1px solid #e53935;">
            <strong style="color:#c62828;">No SMTP settings found in database!</strong>
            You need to run the SQL migration first. Please execute the SQL from <code>database/migrate_newsletter.sql</code> in phpMyAdmin.
            <br><br>
            <strong>Quick SQL to run:</strong>
            <pre style="background:#fff;padding:10px;border-radius:4px;font-size:0.75rem;overflow-x:auto;margin-top:0.5rem;border:1px solid #ddd;">INSERT INTO `settings` (`setting_key`, `setting_value`, `key_name`, `value`) VALUES
('smtp_host', '', 'smtp_host', ''),
('smtp_port', '587', 'smtp_port', '587'),
('smtp_username', '', 'smtp_username', ''),
('smtp_password', '', 'smtp_password', ''),
('smtp_encryption', 'tls', 'smtp_encryption', 'tls'),
('smtp_from_email', '', 'smtp_from_email', ''),
('smtp_from_name', 'Gmind Institute', 'smtp_from_name', 'Gmind Institute')
ON DUPLICATE KEY UPDATE `setting_value` = VALUES(`setting_value`), `value` = VALUES(`value`);</pre>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- SMTP Settings Form -->
<div class="admin-card" style="margin-bottom:1.5rem;">
    <div class="admin-card-header">
        <h3 class="admin-card-title">SMTP Configuration</h3>
    </div>
    <div class="admin-card-body">
        <form method="POST" action="<?= $bp ?>/admin/smtp-settings/save" id="smtpForm">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:1.5rem;">
                <!-- SMTP Host -->
                <div class="admin-form-group">
                    <label for="smtp_host">SMTP Host <span class="admin-required">*</span></label>
                    <input type="text" id="smtp_host" name="smtp_host" class="admin-form-control"
                           value="<?= htmlspecialchars($config['smtp_host'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                           placeholder="e.g., smtp.gmail.com or mail.yourdomain.com">
                    <small class="admin-form-help">Your email provider's SMTP server address.</small>
                </div>

                <!-- SMTP Port -->
                <div class="admin-form-group">
                    <label for="smtp_port">SMTP Port <span class="admin-required">*</span></label>
                    <input type="number" id="smtp_port" name="smtp_port" class="admin-form-control"
                           value="<?= htmlspecialchars($config['smtp_port'] ?? '587', ENT_QUOTES, 'UTF-8') ?>"
                           placeholder="587">
                    <small class="admin-form-help">Common: 587 (TLS), 465 (SSL), 25 (No encryption)</small>
                </div>

                <!-- SMTP Username -->
                <div class="admin-form-group">
                    <label for="smtp_username">SMTP Username (Email)</label>
                    <input type="text" id="smtp_username" name="smtp_username" class="admin-form-control"
                           value="<?= htmlspecialchars($config['smtp_username'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                           placeholder="e.g., info@yourdomain.com" autocomplete="off">
                    <small class="admin-form-help">Usually your full email address.</small>
                </div>

                <!-- SMTP Password -->
                <div class="admin-form-group">
                    <label for="smtp_password">SMTP Password</label>
                    <div style="position:relative;">
                        <input type="password" id="smtp_password" name="smtp_password" class="admin-form-control"
                               value="<?= !empty($config['smtp_password']) ? '••••••••' : '' ?>"
                               placeholder="Enter password or app password" autocomplete="new-password">
                        <button type="button" class="admin-btn-icon-only" style="position:absolute;right:8px;top:50%;transform:translateY(-50%);"
                                onclick="togglePassword('smtp_password')" title="Show/Hide password">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                        </button>
                    </div>
                    <small class="admin-form-help">
                        For Gmail: Use <strong>App Password</strong>, not regular password.
                        <a href="https://support.google.com/accounts/answer/185833" target="_blank" style="color:#1a73e8;">How to create?</a>
                    </small>
                </div>

                <!-- Encryption -->
                <div class="admin-form-group">
                    <label for="smtp_encryption">Encryption</label>
                    <select id="smtp_encryption" name="smtp_encryption" class="admin-form-control">
                        <option value="tls" <?= ($config['smtp_encryption'] ?? 'tls') === 'tls' ? 'selected' : '' ?>>TLS (Port 587) — Recommended</option>
                        <option value="ssl" <?= ($config['smtp_encryption'] ?? '') === 'ssl' ? 'selected' : '' ?>>SSL (Port 465)</option>
                        <option value="none" <?= ($config['smtp_encryption'] ?? '') === 'none' ? 'selected' : '' ?>>None (Port 25) — Not recommended</option>
                    </select>
                    <small class="admin-form-help">TLS is most common and secure. Use SSL only if TLS fails.</small>
                </div>

                <!-- From Email -->
                <div class="admin-form-group">
                    <label for="smtp_from_email">From Email <span class="admin-required">*</span></label>
                    <input type="email" id="smtp_from_email" name="smtp_from_email" class="admin-form-control"
                           value="<?= htmlspecialchars($config['smtp_from_email'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                           placeholder="e.g., info@yourdomain.com">
                    <small class="admin-form-help">Email address shown as sender in all outgoing emails.</small>
                </div>

                <!-- From Name -->
                <div class="admin-form-group" style="grid-column:1/-1;">
                    <label for="smtp_from_name">From Name</label>
                    <input type="text" id="smtp_from_name" name="smtp_from_name" class="admin-form-control"
                           value="<?= htmlspecialchars($config['smtp_from_name'] ?? 'Gmind Institute', ENT_QUOTES, 'UTF-8') ?>"
                           placeholder="Gmind Institute"
                           style="max-width:400px;">
                    <small class="admin-form-help">Display name shown alongside the from email.</small>
                </div>
            </div>

            <!-- Common SMTP Providers Quick Fill -->
            <div style="margin-top:1rem;margin-bottom:1.5rem;">
                <label style="font-size:0.85rem;font-weight:600;margin-bottom:0.5rem;display:block;">Quick Fill — Common Providers:</label>
                <div style="display:flex;gap:0.5rem;flex-wrap:wrap;">
                    <button type="button" class="admin-btn admin-btn-outline admin-btn-sm" onclick="fillSmtp('gmail')">Gmail</button>
                    <button type="button" class="admin-btn admin-btn-outline admin-btn-sm" onclick="fillSmtp('hostinger')">Hostinger</button>
                    <button type="button" class="admin-btn admin-btn-outline admin-btn-sm" onclick="fillSmtp('godaddy')">GoDaddy</button>
                    <button type="button" class="admin-btn admin-btn-outline admin-btn-sm" onclick="fillSmtp('outlook')">Outlook/Hotmail</button>
                    <button type="button" class="admin-btn admin-btn-outline admin-btn-sm" onclick="fillSmtp('zoho')">Zoho Mail</button>
                    <button type="button" class="admin-btn admin-btn-outline admin-btn-sm" style="background:#e3f2fd;border-color:#1565c0;color:#1565c0;" onclick="fillSmtp('cpanel')">cPanel (SSL/465)</button>
                </div>
            </div>

            <div style="display:flex;gap:1rem;align-items:center;">
                <button type="submit" class="admin-btn admin-btn-primary">
                    <svg class="admin-btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
                    Save SMTP Settings
                </button>
                <span style="font-size:0.85rem;color:#666;">Save first, then test connection below.</span>
            </div>
        </form>
    </div>
</div>

<!-- Test Email Section -->
<div class="admin-card">
    <div class="admin-card-header">
        <h3 class="admin-card-title">Send Test Email</h3>
    </div>
    <div class="admin-card-body">
        <p style="font-size:0.9rem;color:#666;margin-bottom:1rem;">
            After saving your SMTP settings, send a test email to verify everything is working correctly.
        </p>

        <form method="POST" action="<?= $bp ?>/admin/smtp-settings/send-test">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">

            <div style="display:flex;gap:1rem;align-items:flex-end;flex-wrap:wrap;">
                <div class="admin-form-group" style="flex:1;min-width:250px;margin-bottom:0;">
                    <label for="test_email">Test Email Address</label>
                    <input type="email" id="test_email" name="test_email" class="admin-form-control"
                           placeholder="your-personal@email.com"
                           value="<?= htmlspecialchars($config['smtp_from_email'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                </div>
                <button type="submit" class="admin-btn admin-btn-primary" <?= (!$mailerAvailable || !$smtpConfigured) ? 'disabled' : '' ?>>
                    <svg class="admin-btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
                    Send Test Email
                </button>
            </div>

            <?php if (!$smtpConfigured): ?>
            <p style="font-size:0.85rem;color:#e53935;margin-top:0.75rem;">
                Please save SMTP settings (at least Host and From Email) before sending a test email.
            </p>
            <?php endif; ?>
        </form>
    </div>
</div>

<script>
function togglePassword(fieldId) {
    const field = document.getElementById(fieldId);
    if (field.type === 'password') {
        field.type = 'text';
    } else {
        field.type = 'password';
    }
}

function fillSmtp(provider) {
    const providers = {
        gmail: { host: 'smtp.gmail.com', port: '587', encryption: 'tls', username: '@gmail.com' },
        hostinger: { host: 'smtp.hostinger.com', port: '587', encryption: 'tls', username: '' },
        godaddy: { host: 'smtpout.secureserver.net', port: '465', encryption: 'ssl', username: '' },
        outlook: { host: 'smtp-mail.outlook.com', port: '587', encryption: 'tls', username: '@outlook.com' },
        zoho: { host: 'smtp.zoho.com', port: '587', encryption: 'tls', username: '' },
        cpanel: { host: '', port: '465', encryption: 'ssl', username: '' },
    };

    const p = providers[provider];
    if (!p) return;

    document.getElementById('smtp_host').value = p.host;
    document.getElementById('smtp_port').value = p.port;
    document.getElementById('smtp_encryption').value = p.encryption;

    if (p.username && !document.getElementById('smtp_username').value) {
        document.getElementById('smtp_username').value = p.username;
    }

    document.getElementById('smtp_username').focus();
}
</script>
