<?php
/**
 * SMM Paket Satış Scripti - SMTP Ayarları
 * @version 1.0.1
 */

require_once __DIR__ . '/../config.php';

if (!isLoggedIn() || !isAdmin()) {
    redirect(SITE_URL . '/admin/');
    exit;
}

// CSRF Token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrfToken = $_SESSION['csrf_token'];

// Demo modu kontrolü
function isDemoMode() {
    global $db;
    try {
        $stmt = $db->prepare("SELECT setting_value FROM settings WHERE setting_key = 'demo_mode'");
        $stmt->execute();
        $value = $stmt->fetchColumn();
        return $value === '1' || $value === 1;
    } catch (PDOException $e) {
        return false;
    }
}

$demoMode = isDemoMode();

/**
 * Ayar kaydet/güncelle - Doğrudan veritabanına
 */
function saveSetting($db, $key, $value) {
    try {
        $stmt = $db->prepare("SELECT COUNT(*) FROM settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $exists = $stmt->fetchColumn() > 0;
        
        if ($exists) {
            $stmt = $db->prepare("UPDATE settings SET setting_value = ?, updated_at = NOW() WHERE setting_key = ?");
            $stmt->execute([$value, $key]);
        } else {
            $stmt = $db->prepare("INSERT INTO settings (setting_key, setting_value, setting_type, setting_group, created_at, updated_at) VALUES (?, ?, 'string', 'smtp', NOW(), NOW())");
            $stmt->execute([$key, $value]);
        }
        
        return true;
    } catch (PDOException $e) {
        return false;
    }
}

/**
 * Ayar oku - Doğrudan veritabanından
 */
function getSmtpSetting($db, $key, $default = '') {
    try {
        $stmt = $db->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $value = $stmt->fetchColumn();
        return $value !== false ? $value : $default;
    } catch (PDOException $e) {
        return $default;
    }
}

/**
 * Test mail şablonu
 */
function getTestEmailTemplate($siteName, $toEmail) {
    $date = date('d.m.Y H:i:s');
    
    return '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin:0;padding:0;background:#0f172a;font-family:Arial,Helvetica,sans-serif;">
    <div style="max-width:600px;margin:0 auto;padding:40px 20px;">
        <div style="background:#1e293b;border-radius:24px;overflow:hidden;border:1px solid #334155;">
            <div style="background:linear-gradient(135deg,#6366f1,#8b5cf6);padding:40px 30px;text-align:center;">
                <div style="width:80px;height:80px;background:rgba(255,255,255,0.2);border-radius:50%;margin:0 auto 20px;line-height:80px;">
                    <span style="font-size:40px;">✉️</span>
                </div>
                <h1 style="margin:0;color:#fff;font-size:28px;font-weight:700;">SMTP Test Başarılı!</h1>
                <p style="margin:15px 0 0;color:rgba(255,255,255,0.8);font-size:16px;">Mail gönderimi çalışıyor</p>
            </div>
            <div style="padding:40px 30px;">
                <div style="background:#0f172a;border-radius:16px;padding:25px;margin-bottom:25px;border:1px solid #334155;">
                    <div style="text-align:center;margin-bottom:25px;">
                        <div style="width:60px;height:60px;background:linear-gradient(135deg,#10b981,#059669);border-radius:50%;margin:0 auto;line-height:60px;">
                            <span style="font-size:30px;color:#fff;">✓</span>
                        </div>
                    </div>
                    <h2 style="color:#fff;font-size:20px;margin:0 0 15px;text-align:center;">Tebrikler!</h2>
                    <p style="color:#94a3b8;font-size:15px;line-height:1.7;margin:0;text-align:center;">
                        SMTP ayarlarınız doğru yapılandırılmış ve mail gönderimi başarıyla çalışıyor.
                    </p>
                </div>
                <div style="background:#0f172a;border-radius:16px;padding:20px;border:1px solid #334155;">
                    <h3 style="color:#fff;font-size:14px;margin:0 0 15px;text-transform:uppercase;letter-spacing:1px;">
                        <span style="color:#6366f1;">●</span> Test Detayları
                    </h3>
                    <table style="width:100%;border-collapse:collapse;">
                        <tr>
                            <td style="padding:10px 0;color:#64748b;font-size:14px;border-bottom:1px solid #1e293b;">Site</td>
                            <td style="padding:10px 0;color:#fff;font-size:14px;text-align:right;border-bottom:1px solid #1e293b;">' . htmlspecialchars($siteName) . '</td>
                        </tr>
                        <tr>
                            <td style="padding:10px 0;color:#64748b;font-size:14px;border-bottom:1px solid #1e293b;">Alıcı</td>
                            <td style="padding:10px 0;color:#60a5fa;font-size:14px;text-align:right;border-bottom:1px solid #1e293b;">' . htmlspecialchars($toEmail) . '</td>
                        </tr>
                        <tr>
                            <td style="padding:10px 0;color:#64748b;font-size:14px;">Tarih</td>
                            <td style="padding:10px 0;color:#fff;font-size:14px;text-align:right;">' . $date . '</td>
                        </tr>
                    </table>
                </div>
                <p style="color:#64748b;font-size:13px;margin:25px 0 0;text-align:center;line-height:1.6;">
                    Bu bir test mailidir. Herhangi bir işlem yapmanıza gerek yoktur.
                </p>
            </div>
            <div style="background:#0f172a;padding:25px 30px;text-align:center;border-top:1px solid #1e293b;">
                <p style="color:#64748b;font-size:13px;margin:0;">
                    © ' . date('Y') . ' ' . htmlspecialchars($siteName) . ' - Tüm hakları saklıdır.
                </p>
            </div>
        </div>
    </div>
</body>
</html>';
}

/**
 * PHPMailer ile mail gönder
 */
function sendTestMail($db, $settings, $toEmail) {
    // PHPMailer dosyaları var mı kontrol et
    $phpmailerPath = __DIR__ . '/../includes/PHPMailer/PHPMailer.php';
    if (!file_exists($phpmailerPath)) {
        return ['success' => false, 'error' => 'PHPMailer kütüphanesi bulunamadı. Lütfen includes/PHPMailer/ klasörüne PHPMailer dosyalarını yükleyin.'];
    }
    
    // PHPMailer'ı dahil et
    require_once __DIR__ . '/../includes/PHPMailer/Exception.php';
    require_once __DIR__ . '/../includes/PHPMailer/PHPMailer.php';
    require_once __DIR__ . '/../includes/PHPMailer/SMTP.php';
    
    // SMTP Ayarlarını al
    $smtpHost = getSmtpSetting($db, 'smtp_host', '');
    $smtpPort = (int)getSmtpSetting($db, 'smtp_port', 587);
    $smtpUsername = getSmtpSetting($db, 'smtp_username', '');
    $smtpPassword = getSmtpSetting($db, 'smtp_password', '');
    $smtpEncryption = getSmtpSetting($db, 'smtp_encryption', 'tls');
    $smtpFromEmail = getSmtpSetting($db, 'smtp_from_email', $smtpUsername);
    $smtpFromName = getSmtpSetting($db, 'smtp_from_name', $settings->get('site_name', 'SMM Panel'));
    
    if (empty($smtpHost) || empty($smtpUsername) || empty($smtpPassword)) {
        return ['success' => false, 'error' => 'SMTP ayarları eksik. Sunucu, kullanıcı adı ve şifre gereklidir.'];
    }
    
    try {
        $mail = new PHPMailer\PHPMailer\PHPMailer(true);
        
        // SMTP Ayarları
        $mail->isSMTP();
        $mail->Host = $smtpHost;
        $mail->Port = $smtpPort;
        $mail->SMTPAuth = true;
        $mail->Username = $smtpUsername;
        $mail->Password = $smtpPassword;
        
        // Şifreleme
        if ($smtpEncryption === 'tls') {
            $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
        } elseif ($smtpEncryption === 'ssl') {
            $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
        } else {
            $mail->SMTPSecure = false;
            $mail->SMTPAutoTLS = false;
        }
        
        // SSL sertifika doğrulaması
        $mail->SMTPOptions = [
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            ]
        ];
        
        // Karakter seti
        $mail->CharSet = 'UTF-8';
        $mail->Encoding = 'base64';
        
        // Gönderen
        $mail->setFrom($smtpFromEmail, $smtpFromName);
        $mail->addReplyTo($smtpFromEmail, $smtpFromName);
        
        // Alıcı
        $mail->addAddress($toEmail);
        
        // İçerik
        $mail->isHTML(true);
        $mail->Subject = '=?UTF-8?B?' . base64_encode('✉️ SMTP Test - ' . $smtpFromName) . '?=';
        $mail->Body = getTestEmailTemplate($smtpFromName, $toEmail);
        $mail->AltBody = 'SMTP test maili başarıyla gönderildi. Tarih: ' . date('d.m.Y H:i:s');
        
        // Gönder
        $mail->send();
        
        return ['success' => true];
        
    } catch (PHPMailer\PHPMailer\Exception $e) {
        return ['success' => false, 'error' => $mail->ErrorInfo];
    } catch (Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

// POST İşlemleri
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Demo modunda işlem yapılamaz
    if ($demoMode) {
        setFlash('error', '🔒 Demo modunda SMTP ayarları değiştirilemez.');
        redirect(SITE_URL . '/admin/smtp-ayarlari.php');
        exit;
    }
    
    if (!hash_equals($csrfToken, $_POST['csrf_token'] ?? '')) {
        setFlash('error', 'Güvenlik hatası. Lütfen tekrar deneyin.');
        redirect(SITE_URL . '/admin/smtp-ayarlari.php');
        exit;
    }
    
    $action = $_POST['action'] ?? '';
    
    try {
        if ($action === 'save_smtp') {
            // SMTP Ayarlarını Kaydet
            $smtpSettings = [
                'smtp_enabled' => isset($_POST['smtp_enabled']) ? '1' : '0',
                'smtp_host' => trim($_POST['smtp_host'] ?? ''),
                'smtp_port' => (int)($_POST['smtp_port'] ?? 587),
                'smtp_username' => trim($_POST['smtp_username'] ?? ''),
                'smtp_encryption' => $_POST['smtp_encryption'] ?? 'tls',
                'smtp_from_email' => trim($_POST['smtp_from_email'] ?? ''),
                'smtp_from_name' => trim($_POST['smtp_from_name'] ?? ''),
            ];
            
            // Şifre değiştiyse güncelle
            $newPassword = trim($_POST['smtp_password'] ?? '');
            if (!empty($newPassword)) {
                $smtpSettings['smtp_password'] = $newPassword;
            }
            
            // Validasyon
            if ($smtpSettings['smtp_enabled'] === '1') {
                if (empty($smtpSettings['smtp_host'])) {
                    throw new Exception('SMTP sunucu adresi gereklidir.');
                }
                if (empty($smtpSettings['smtp_username'])) {
                    throw new Exception('SMTP kullanıcı adı gereklidir.');
                }
                if (empty($newPassword) && empty(getSmtpSetting($db, 'smtp_password', ''))) {
                    throw new Exception('SMTP şifresi gereklidir.');
                }
                if (empty($smtpSettings['smtp_from_email'])) {
                    throw new Exception('Gönderen e-posta adresi gereklidir.');
                }
                if (!filter_var($smtpSettings['smtp_from_email'], FILTER_VALIDATE_EMAIL)) {
                    throw new Exception('Geçerli bir gönderen e-posta adresi girin.');
                }
            }
            
            // Kaydet
            foreach ($smtpSettings as $key => $value) {
                saveSetting($db, $key, $value);
            }
            
            setFlash('success', 'SMTP ayarları başarıyla kaydedildi.');
            
        } elseif ($action === 'test_smtp') {
            // Test Maili Gönder
            $testEmail = trim($_POST['test_email'] ?? '');
            
            if (empty($testEmail)) {
                throw new Exception('Test için e-posta adresi girin.');
            }
            
            if (!filter_var($testEmail, FILTER_VALIDATE_EMAIL)) {
                throw new Exception('Geçerli bir e-posta adresi girin.');
            }
            
            // SMTP aktif mi kontrol et
            if (getSmtpSetting($db, 'smtp_enabled', '0') !== '1') {
                throw new Exception('SMTP devre dışı. Önce SMTP ayarlarını yapın ve aktifleştirin.');
            }
            
            // Mail gönder
            $result = sendTestMail($db, $settings, $testEmail);
            
            if ($result['success']) {
                setFlash('success', 'Test maili başarıyla gönderildi! <strong>' . htmlspecialchars($testEmail) . '</strong> adresini kontrol edin.');
            } else {
                throw new Exception('Mail gönderilemedi: ' . $result['error']);
            }
        }
        
    } catch (Exception $e) {
        setFlash('error', $e->getMessage());
    }
    
    redirect(SITE_URL . '/admin/smtp-ayarlari.php');
    exit;
}

// Mevcut ayarları al
$smtpEnabled = getSmtpSetting($db, 'smtp_enabled', '0');
$smtpHost = getSmtpSetting($db, 'smtp_host', '');
$smtpPort = getSmtpSetting($db, 'smtp_port', '587');
$smtpUsername = getSmtpSetting($db, 'smtp_username', '');
$smtpPassword = getSmtpSetting($db, 'smtp_password', '');
$smtpEncryption = getSmtpSetting($db, 'smtp_encryption', 'tls');
$smtpFromEmail = getSmtpSetting($db, 'smtp_from_email', '');
$smtpFromName = getSmtpSetting($db, 'smtp_from_name', '');

// Demo modunda hassas bilgileri maskele
function maskSensitiveData($data, $visibleChars = 3) {
    if (empty($data)) return '';
    if (strlen($data) <= $visibleChars * 2) {
        return str_repeat('•', strlen($data));
    }
    return substr($data, 0, $visibleChars) . str_repeat('•', strlen($data) - $visibleChars * 2) . substr($data, -$visibleChars);
}

$adminPageTitle = 'SMTP Ayarları';
require_once __DIR__ . '/header.php';
?>

<style>
/* Demo Banner */
.demo-banner {
    background: linear-gradient(135deg, rgba(245, 158, 11, 0.15), rgba(239, 68, 68, 0.15));
    border: 1px solid rgba(245, 158, 11, 0.3);
    border-radius: 12px;
    padding: 15px 20px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 12px;
}
.demo-banner i { font-size: 24px; color: #f59e0b; }
.demo-banner-text h4 { margin: 0 0 4px; font-size: 14px; font-weight: 600; color: #f59e0b; }
.demo-banner-text p { margin: 0; font-size: 12px; color: var(--text-secondary); }

.smtp-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 25px;
}

.smtp-card {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 16px;
    overflow: hidden;
}

.smtp-card-header {
    padding: 20px 24px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    gap: 12px;
}

.smtp-card-icon {
    width: 44px;
    height: 44px;
    background: rgba(var(--primary-rgb), 0.15);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    color: var(--primary);
}

.smtp-card-header h3 {
    font-size: 17px;
    font-weight: 600;
    margin: 0;
}

.smtp-card-header p {
    font-size: 13px;
    color: var(--text-secondary);
    margin: 4px 0 0;
}

.smtp-card-body {
    padding: 24px;
}

.form-group {
    margin-bottom: 20px;
}

.form-group:last-child {
    margin-bottom: 0;
}

.form-label {
    display: block;
    font-size: 14px;
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: 8px;
}

.form-label .required {
    color: var(--danger);
}

.form-hint {
    font-size: 12px;
    color: var(--text-muted);
    margin-top: 6px;
}

.form-control, .form-select {
    width: 100%;
    padding: 12px 16px;
    background: var(--bg-dark);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    color: var(--text-primary);
    font-size: 14px;
    transition: all 0.2s;
}

.form-control:focus, .form-select:focus {
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(var(--primary-rgb), 0.15);
    outline: none;
}

.form-control::placeholder {
    color: var(--text-muted);
}

.form-control:disabled, .form-select:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.input-group {
    display: flex;
    gap: 10px;
}

.toggle-switch {
    display: flex;
    align-items: center;
    gap: 15px;
    padding: 16px 20px;
    background: var(--bg-dark);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    cursor: pointer;
}

.toggle-switch input {
    display: none;
}

.toggle-slider {
    width: 52px;
    height: 28px;
    background: var(--bg-hover);
    border-radius: 14px;
    position: relative;
    transition: all 0.3s;
    flex-shrink: 0;
}

.toggle-slider::before {
    content: '';
    position: absolute;
    top: 3px;
    left: 3px;
    width: 22px;
    height: 22px;
    background: #fff;
    border-radius: 50%;
    transition: all 0.3s;
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}

.toggle-switch input:checked + .toggle-slider {
    background: var(--success);
}

.toggle-switch input:checked + .toggle-slider::before {
    transform: translateX(24px);
}

.toggle-switch input:disabled + .toggle-slider {
    opacity: 0.5;
    cursor: not-allowed;
}

.toggle-info {
    flex: 1;
}

.toggle-info strong {
    display: block;
    font-size: 15px;
    color: var(--text-primary);
    margin-bottom: 3px;
}

.toggle-info span {
    font-size: 13px;
    color: var(--text-secondary);
}

.smtp-status {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 8px 16px;
    border-radius: 50px;
    font-size: 13px;
    font-weight: 600;
}

.smtp-status.active {
    background: rgba(16, 185, 129, 0.15);
    color: #10b981;
}

.smtp-status.inactive {
    background: rgba(239, 68, 68, 0.15);
    color: #ef4444;
}

.preset-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 20px;
}

.preset-btn {
    padding: 8px 16px;
    background: var(--bg-hover);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    color: var(--text-secondary);
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    gap: 8px;
}

.preset-btn:hover {
    background: rgba(var(--primary-rgb), 0.15);
    border-color: rgba(var(--primary-rgb), 0.3);
    color: var(--primary);
}

.preset-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.password-wrapper {
    position: relative;
}

.password-wrapper .form-control {
    padding-right: 50px;
}

.password-toggle {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    background: none;
    border: none;
    color: var(--text-muted);
    cursor: pointer;
    padding: 5px;
    font-size: 16px;
}

.password-toggle:hover {
    color: var(--text-primary);
}

.form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding-top: 20px;
    border-top: 1px solid var(--border-color);
    margin-top: 24px;
}

.btn-save {
    background: var(--gradient);
    border: none;
    color: #fff;
    padding: 14px 28px;
    border-radius: 12px;
    font-weight: 600;
    font-size: 15px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 10px;
    transition: all 0.3s;
}

.btn-save:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(var(--primary-rgb), 0.4);
}

.btn-save:disabled {
    opacity: 0.5;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
}

.btn-reset {
    background: var(--bg-hover);
    border: 1px solid var(--border-color);
    color: var(--text-primary);
    padding: 14px 28px;
    border-radius: 12px;
    font-weight: 600;
    font-size: 15px;
    cursor: pointer;
    transition: all 0.2s;
}

.btn-reset:hover {
    background: var(--bg-card);
}

.btn-reset:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.btn-test {
    background: var(--gradient);
    border: none;
    color: #fff;
    padding: 12px 24px;
    border-radius: 10px;
    font-weight: 600;
    font-size: 14px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
    transition: all 0.3s;
    white-space: nowrap;
}

.btn-test:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(var(--primary-rgb), 0.4);
}

.btn-test:disabled {
    background: var(--bg-hover);
    color: var(--text-muted);
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
}

.info-box {
    background: rgba(59, 130, 246, 0.1);
    border: 1px solid rgba(59, 130, 246, 0.2);
    border-radius: 12px;
    padding: 16px 20px;
    display: flex;
    gap: 14px;
    margin-bottom: 20px;
}

.info-box i {
    color: #3b82f6;
    font-size: 18px;
    flex-shrink: 0;
    margin-top: 2px;
}

.info-box-content h5 {
    font-size: 14px;
    font-weight: 600;
    margin: 0 0 6px;
    color: #3b82f6;
}

.info-box-content p {
    font-size: 13px;
    color: var(--text-secondary);
    margin: 0;
    line-height: 1.6;
}

.info-box-content a {
    color: #60a5fa;
}

.test-input-group {
    display: flex;
    gap: 12px;
}

.test-input-group .form-control {
    flex: 1;
}

@media (max-width: 991px) {
    .smtp-grid {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 576px) {
    .test-input-group,
    .form-actions,
    .preset-buttons,
    .input-group {
        flex-direction: column;
    }
    
    .form-actions button,
    .preset-btn {
        width: 100%;
        justify-content: center;
    }
}
</style>

<?php if ($demoMode): ?>
<div class="demo-banner">
    <i class="fas fa-shield-alt"></i>
    <div class="demo-banner-text">
        <h4>Demo Modu Aktif</h4>
        <p>Demo modunda SMTP ayarları görüntülenebilir ancak değiştirilemez. Hassas bilgiler gizlenmiştir.</p>
    </div>
</div>
<?php endif; ?>

<div class="smtp-grid">
    <div>
        <form method="POST" action="">
            <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
            <input type="hidden" name="action" value="save_smtp">
            
            <div class="smtp-card">
                <div class="smtp-card-header">
                    <div class="smtp-card-icon"><i class="fas fa-server"></i></div>
                    <div>
                        <h3>SMTP Sunucu Ayarları</h3>
                        <p>E-posta gönderimi için sunucu yapılandırması</p>
                    </div>
                </div>
                
                <div class="smtp-card-body">
                    <div class="form-group">
                        <label class="toggle-switch">
                            <input type="checkbox" name="smtp_enabled" id="smtpEnabled" <?php echo $smtpEnabled === '1' ? 'checked' : ''; ?> <?php echo $demoMode ? 'disabled' : ''; ?>>
                            <span class="toggle-slider"></span>
                            <div class="toggle-info">
                                <strong>SMTP Mail Gönderimi</strong>
                                <span>Aktifleştirdiğinizde sistem mailleri SMTP üzerinden gönderilir</span>
                            </div>
                        </label>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Hazır Sunucu Ayarları</label>
                        <div class="preset-buttons">
                            <button type="button" class="preset-btn" onclick="setPreset('gmail')" <?php echo $demoMode ? 'disabled' : ''; ?>>
                                <i class="fab fa-google" style="color: #ea4335;"></i> Gmail
                            </button>
                            <button type="button" class="preset-btn" onclick="setPreset('yandex')" <?php echo $demoMode ? 'disabled' : ''; ?>>
                                <i class="fas fa-envelope" style="color: #fc3f1d;"></i> Yandex
                            </button>
                            <button type="button" class="preset-btn" onclick="setPreset('outlook')" <?php echo $demoMode ? 'disabled' : ''; ?>>
                                <i class="fab fa-microsoft" style="color: #0078d4;"></i> Outlook
                            </button>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">SMTP Sunucu <span class="required">*</span></label>
                        <input type="text" name="smtp_host" id="smtpHost" class="form-control" 
                               value="<?php echo $demoMode ? maskSensitiveData($smtpHost, 4) : htmlspecialchars($smtpHost); ?>" 
                               placeholder="smtp.gmail.com" <?php echo $demoMode ? 'disabled' : ''; ?>>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Port & Şifreleme <span class="required">*</span></label>
                        <div class="input-group">
                            <input type="number" name="smtp_port" id="smtpPort" class="form-control" 
                                   value="<?php echo htmlspecialchars($smtpPort); ?>" placeholder="587" style="max-width: 120px;" <?php echo $demoMode ? 'disabled' : ''; ?>>
                            <select name="smtp_encryption" id="smtpEncryption" class="form-select" <?php echo $demoMode ? 'disabled' : ''; ?>>
                                <option value="tls" <?php echo $smtpEncryption === 'tls' ? 'selected' : ''; ?>>TLS</option>
                                <option value="ssl" <?php echo $smtpEncryption === 'ssl' ? 'selected' : ''; ?>>SSL</option>
                                <option value="none" <?php echo $smtpEncryption === 'none' ? 'selected' : ''; ?>>Yok</option>
                            </select>
                        </div>
                        <div class="form-hint">TLS: 587, SSL: 465</div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Kullanıcı Adı <span class="required">*</span></label>
                        <input type="text" name="smtp_username" id="smtpUsername" class="form-control" 
                               value="<?php echo $demoMode ? maskSensitiveData($smtpUsername, 3) : htmlspecialchars($smtpUsername); ?>" 
                               placeholder="ornek@gmail.com" <?php echo $demoMode ? 'disabled' : ''; ?>>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Şifre <span class="required">*</span></label>
                        <div class="password-wrapper">
                            <input type="password" name="smtp_password" id="smtpPassword" class="form-control" 
                                   placeholder="<?php echo !empty($smtpPassword) ? '••••••••••••' : 'SMTP şifresi'; ?>" <?php echo $demoMode ? 'disabled' : ''; ?>>
                            <button type="button" class="password-toggle" onclick="togglePassword()" <?php echo $demoMode ? 'disabled' : ''; ?>>
                                <i class="fas fa-eye" id="passwordIcon"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="smtp-card" style="margin-top: 20px;">
                <div class="smtp-card-header">
                    <div class="smtp-card-icon"><i class="fas fa-user-circle"></i></div>
                    <div>
                        <h3>Gönderen Bilgileri</h3>
                        <p>Maillerde görünecek bilgiler</p>
                    </div>
                </div>
                
                <div class="smtp-card-body">
                    <div class="form-group">
                        <label class="form-label">Gönderen E-posta <span class="required">*</span></label>
                        <input type="email" name="smtp_from_email" id="smtpFromEmail" class="form-control" 
                               value="<?php echo $demoMode ? maskSensitiveData($smtpFromEmail, 3) : htmlspecialchars($smtpFromEmail); ?>" 
                               placeholder="noreply@siteniz.com" <?php echo $demoMode ? 'disabled' : ''; ?>>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Gönderen Adı</label>
                        <input type="text" name="smtp_from_name" class="form-control" 
                               value="<?php echo htmlspecialchars($smtpFromName); ?>" 
                               placeholder="<?php echo htmlspecialchars($settings->get('site_name', 'SMM Panel')); ?>" <?php echo $demoMode ? 'disabled' : ''; ?>>
                    </div>
                    
                    <div class="form-actions">
                        <?php if ($demoMode): ?>
                        <button type="button" class="btn-save" disabled style="opacity: 0.5; cursor: not-allowed;">
                            <i class="fas fa-lock"></i> Demo Mod
                        </button>
                        <?php else: ?>
                        <button type="reset" class="btn-reset"><i class="fas fa-undo"></i> Sıfırla</button>
                        <button type="submit" class="btn-save"><i class="fas fa-save"></i> Kaydet</button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </form>
    </div>
    
    <div>
        <div class="smtp-card" style="margin-bottom: 20px;">
            <div class="smtp-card-body" style="display: flex; align-items: center; justify-content: space-between;">
                <div>
                    <h4 style="margin: 0 0 5px; font-size: 15px;">SMTP Durumu</h4>
                    <p style="margin: 0; color: var(--text-secondary); font-size: 13px;">Mail gönderim sistemi</p>
                </div>
                <?php if ($smtpEnabled === '1'): ?>
                    <span class="smtp-status active"><i class="fas fa-check-circle"></i> Aktif</span>
                <?php else: ?>
                    <span class="smtp-status inactive"><i class="fas fa-times-circle"></i> Pasif</span>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="smtp-card" style="margin-bottom: 20px;">
            <div class="smtp-card-header">
                <div class="smtp-card-icon" style="background: rgba(16, 185, 129, 0.15);">
                    <i class="fas fa-paper-plane" style="color: #10b981;"></i>
                </div>
                <div>
                    <h3>Test Mail Gönder</h3>
                    <p>SMTP ayarlarınızı test edin</p>
                </div>
            </div>
            
            <div class="smtp-card-body">
                <form method="POST" action="">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="action" value="test_smtp">
                    
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label">Test E-posta Adresi</label>
                        <div class="test-input-group">
                            <input type="email" name="test_email" class="form-control" placeholder="test@ornek.com" 
                                   <?php echo ($smtpEnabled !== '1' || $demoMode) ? 'disabled' : ''; ?> required>
                            <button type="submit" class="btn-test" <?php echo ($smtpEnabled !== '1' || $demoMode) ? 'disabled' : ''; ?>>
                                <?php if ($demoMode): ?>
                                <i class="fas fa-lock"></i> Demo
                                <?php else: ?>
                                <i class="fas fa-paper-plane"></i> Gönder
                                <?php endif; ?>
                            </button>
                        </div>
                        <?php if ($demoMode): ?>
                        <div class="form-hint" style="color: var(--warning);"><i class="fas fa-shield-alt"></i> Demo modunda test yapılamaz</div>
                        <?php elseif ($smtpEnabled !== '1'): ?>
                        <div class="form-hint" style="color: var(--warning);"><i class="fas fa-exclamation-triangle"></i> Önce SMTP'yi aktifleştirin</div>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
        
        <div class="info-box">
            <i class="fab fa-google"></i>
            <div class="info-box-content">
                <h5>Gmail Kullanıyorsanız</h5>
                <p>
                    Normal şifrenizi kullanamazsınız. Google hesabınızdan "Uygulama Şifresi" oluşturmanız gerekir.<br><br>
                    <strong>Adımlar:</strong><br>
                    1. 2 Adımlı Doğrulama aktifleştirin<br>
                    2. Uygulama Şifreleri → Yeni şifre oluşturun<br>
                    3. 16 haneli şifreyi kullanın
                </p>
            </div>
        </div>
        
        <?php if (!file_exists(__DIR__ . '/../includes/PHPMailer/PHPMailer.php')): ?>
        <div class="info-box" style="background: rgba(239, 68, 68, 0.1); border-color: rgba(239, 68, 68, 0.2);">
            <i class="fas fa-exclamation-triangle" style="color: #ef4444;"></i>
            <div class="info-box-content">
                <h5 style="color: #ef4444;">PHPMailer Eksik!</h5>
                <p>
                    <a href="https://github.com/PHPMailer/PHPMailer/releases" target="_blank">GitHub'dan indirin</a> ve 
                    src/ klasöründeki 3 dosyayı (Exception.php, PHPMailer.php, SMTP.php) 
                    <strong>includes/PHPMailer/</strong> klasörüne yükleyin.
                </p>
            </div>
        </div>
        <?php else: ?>
        <div class="info-box" style="background: rgba(16, 185, 129, 0.1); border-color: rgba(16, 185, 129, 0.2);">
            <i class="fas fa-check-circle" style="color: #10b981;"></i>
            <div class="info-box-content">
                <h5 style="color: #10b981;">PHPMailer Yüklü ✓</h5>
                <p>Mail gönderimi için hazırsınız.</p>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
var demoMode = <?php echo $demoMode ? 'true' : 'false'; ?>;

function setPreset(provider) {
    if (demoMode) return;
    
    var presets = {
        'gmail': { host: 'smtp.gmail.com', port: 587, encryption: 'tls' },
        'yandex': { host: 'smtp.yandex.com', port: 465, encryption: 'ssl' },
        'outlook': { host: 'smtp.office365.com', port: 587, encryption: 'tls' }
    };
    
    var p = presets[provider];
    if (p) {
        document.getElementById('smtpHost').value = p.host;
        document.getElementById('smtpPort').value = p.port;
        document.getElementById('smtpEncryption').value = p.encryption;
    }
}

function togglePassword() {
    if (demoMode) return;
    
    var input = document.getElementById('smtpPassword');
    var icon = document.getElementById('passwordIcon');
    
    if (input.type === 'password') {
        input.type = 'text';
        icon.classList.replace('fa-eye', 'fa-eye-slash');
    } else {
        input.type = 'password';
        icon.classList.replace('fa-eye-slash', 'fa-eye');
    }
}

<?php if (!$demoMode): ?>
document.getElementById('smtpUsername').addEventListener('blur', function() {
    var fromEmail = document.getElementById('smtpFromEmail');
    if (!fromEmail.value && this.value.includes('@')) {
        fromEmail.value = this.value;
    }
});
<?php endif; ?>
</script>

<?php require_once __DIR__ . '/footer.php'; ?>