<?php
/**
 * SMM Paket Satış Scripti - Mail Gönderici
 * @version 1.0.0
 */

// PHPMailer dosyalarını dahil et
require_once __DIR__ . '/PHPMailer/Exception.php';
require_once __DIR__ . '/PHPMailer/PHPMailer.php';
require_once __DIR__ . '/PHPMailer/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

class Mailer {
    
    private $settings;
    private $lastError = '';
    
    public function __construct($settings) {
        $this->settings = $settings;
    }
    
    /**
     * Mail Gönder
     */
    public function send($to, $subject, $body, $altBody = '', $attachments = []) {
        
        // SMTP aktif değilse
        if ($this->settings->get('smtp_enabled', '0') !== '1') {
            return [
                'success' => false,
                'error' => 'SMTP devre dışı. Lütfen admin panelinden SMTP ayarlarını yapın.'
            ];
        }
        
        try {
            $mail = new PHPMailer(true);
            
            // Debug (geliştirme için)
            // $mail->SMTPDebug = SMTP::DEBUG_SERVER;
            
            // SMTP Ayarları
            $mail->isSMTP();
            $mail->Host = $this->settings->get('smtp_host', '');
            $mail->Port = (int)$this->settings->get('smtp_port', 587);
            $mail->SMTPAuth = true;
            $mail->Username = $this->settings->get('smtp_username', '');
            $mail->Password = $this->settings->get('smtp_password', '');
            
            // Şifreleme
            $encryption = $this->settings->get('smtp_encryption', 'tls');
            if ($encryption === 'tls') {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            } elseif ($encryption === 'ssl') {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            } else {
                $mail->SMTPSecure = false;
                $mail->SMTPAutoTLS = false;
            }
            
            // Karakter seti
            $mail->CharSet = 'UTF-8';
            $mail->Encoding = 'base64';
            
            // Gönderen
            $fromEmail = $this->settings->get('smtp_from_email', $this->settings->get('smtp_username', ''));
            $fromName = $this->settings->get('smtp_from_name', $this->settings->get('site_name', 'SMM Panel'));
            $mail->setFrom($fromEmail, $fromName);
            
            // Reply-To
            $mail->addReplyTo($fromEmail, $fromName);
            
            // Alıcı
            if (is_array($to)) {
                foreach ($to as $recipient) {
                    $mail->addAddress($recipient);
                }
            } else {
                $mail->addAddress($to);
            }
            
            // Ekler
            if (!empty($attachments)) {
                foreach ($attachments as $attachment) {
                    if (is_array($attachment)) {
                        $mail->addAttachment($attachment['path'], $attachment['name'] ?? '');
                    } else {
                        $mail->addAttachment($attachment);
                    }
                }
            }
            
            // İçerik
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body = $body;
            $mail->AltBody = $altBody ?: strip_tags($body);
            
            // Gönder
            $mail->send();
            
            return [
                'success' => true,
                'message' => 'Mail başarıyla gönderildi.'
            ];
            
        } catch (Exception $e) {
            $this->lastError = $mail->ErrorInfo;
            
            return [
                'success' => false,
                'error' => $mail->ErrorInfo
            ];
        }
    }
    
    /**
     * Sipariş Onay Maili
     */
    public function sendOrderConfirmation($order, $package) {
        $siteName = $this->settings->get('site_name', 'SMM Panel');
        $siteUrl = $this->settings->get('site_url', SITE_URL);
        $currencySymbol = $this->settings->get('currency_symbol', '₺');
        
        $subject = "Sipariş Onayı - #" . $order['order_number'] . " - " . $siteName;
        
        $body = $this->getEmailTemplate('order_confirmation', [
            'site_name' => $siteName,
            'site_url' => $siteUrl,
            'order_number' => $order['order_number'],
            'package_name' => $package['name'],
            'amount' => $currencySymbol . number_format($order['amount'], 2, ',', '.'),
            'status' => $this->getStatusText($order['status']),
            'date' => date('d.m.Y H:i', strtotime($order['created_at'])),
            'customer_name' => $order['customer_name'] ?? 'Müşteri',
            'target_url' => $order['target_url'] ?? '-',
        ]);
        
        return $this->send($order['customer_email'], $subject, $body);
    }
    
    /**
     * Sipariş Durum Güncelleme Maili
     */
    public function sendOrderStatusUpdate($order, $package) {
        $siteName = $this->settings->get('site_name', 'SMM Panel');
        $siteUrl = $this->settings->get('site_url', SITE_URL);
        
        $subject = "Sipariş Durumu Güncellendi - #" . $order['order_number'] . " - " . $siteName;
        
        $body = $this->getEmailTemplate('order_status', [
            'site_name' => $siteName,
            'site_url' => $siteUrl,
            'order_number' => $order['order_number'],
            'package_name' => $package['name'],
            'status' => $this->getStatusText($order['status']),
            'status_color' => $this->getStatusColor($order['status']),
            'date' => date('d.m.Y H:i'),
            'customer_name' => $order['customer_name'] ?? 'Müşteri',
        ]);
        
        return $this->send($order['customer_email'], $subject, $body);
    }
    
    /**
     * Ödeme Onay Maili
     */
    public function sendPaymentConfirmation($order, $package) {
        $siteName = $this->settings->get('site_name', 'SMM Panel');
        $currencySymbol = $this->settings->get('currency_symbol', '₺');
        
        $subject = "Ödeme Onaylandı - #" . $order['order_number'] . " - " . $siteName;
        
        $body = $this->getEmailTemplate('payment_confirmation', [
            'site_name' => $siteName,
            'order_number' => $order['order_number'],
            'package_name' => $package['name'],
            'amount' => $currencySymbol . number_format($order['amount'], 2, ',', '.'),
            'payment_method' => $order['payment_method'] ?? 'Havale/EFT',
            'date' => date('d.m.Y H:i'),
            'customer_name' => $order['customer_name'] ?? 'Müşteri',
        ]);
        
        return $this->send($order['customer_email'], $subject, $body);
    }
    
    /**
     * Durum metni
     */
    private function getStatusText($status) {
        $statuses = [
            'pending' => 'Beklemede',
            'processing' => 'İşleniyor',
            'completed' => 'Tamamlandı',
            'cancelled' => 'İptal Edildi',
            'refunded' => 'İade Edildi',
        ];
        return $statuses[$status] ?? $status;
    }
    
    /**
     * Durum rengi
     */
    private function getStatusColor($status) {
        $colors = [
            'pending' => '#f59e0b',
            'processing' => '#3b82f6',
            'completed' => '#10b981',
            'cancelled' => '#ef4444',
            'refunded' => '#8b5cf6',
        ];
        return $colors[$status] ?? '#64748b';
    }
    
    /**
     * Email Template
     */
    private function getEmailTemplate($type, $data) {
        $templates = [
            'order_confirmation' => '
<!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:20px;overflow:hidden;border:1px solid #334155;">
            <!-- Header -->
            <div style="background:linear-gradient(135deg,#6366f1,#8b5cf6);padding:30px;text-align:center;">
                <h1 style="margin:0;color:#fff;font-size:24px;">🎉 Sipariş Alındı!</h1>
            </div>
            
            <!-- Body -->
            <div style="padding:35px 30px;">
                <p style="color:#e2e8f0;font-size:16px;margin:0 0 25px;line-height:1.6;">
                    Merhaba <strong>{customer_name}</strong>,<br><br>
                    Siparişiniz başarıyla alındı. Ödemeniz onaylandıktan sonra işleme alınacaktır.
                </p>
                
                <!-- Order Box -->
                <div style="background:#0f172a;border-radius:16px;padding:25px;margin:25px 0;border:1px solid #334155;">
                    <table style="width:100%;border-collapse:collapse;">
                        <tr>
                            <td style="padding:12px 0;border-bottom:1px solid #1e293b;color:#94a3b8;font-size:14px;">Sipariş No</td>
                            <td style="padding:12px 0;border-bottom:1px solid #1e293b;color:#fff;font-size:14px;text-align:right;font-weight:600;">#{order_number}</td>
                        </tr>
                        <tr>
                            <td style="padding:12px 0;border-bottom:1px solid #1e293b;color:#94a3b8;font-size:14px;">Paket</td>
                            <td style="padding:12px 0;border-bottom:1px solid #1e293b;color:#fff;font-size:14px;text-align:right;font-weight:600;">{package_name}</td>
                        </tr>
                        <tr>
                            <td style="padding:12px 0;border-bottom:1px solid #1e293b;color:#94a3b8;font-size:14px;">Hedef URL</td>
                            <td style="padding:12px 0;border-bottom:1px solid #1e293b;color:#60a5fa;font-size:14px;text-align:right;word-break:break-all;">{target_url}</td>
                        </tr>
                        <tr>
                            <td style="padding:12px 0;border-bottom:1px solid #1e293b;color:#94a3b8;font-size:14px;">Tarih</td>
                            <td style="padding:12px 0;border-bottom:1px solid #1e293b;color:#fff;font-size:14px;text-align:right;">{date}</td>
                        </tr>
                        <tr>
                            <td style="padding:12px 0;color:#94a3b8;font-size:14px;">Durum</td>
                            <td style="padding:12px 0;color:#f59e0b;font-size:14px;text-align:right;font-weight:600;">{status}</td>
                        </tr>
                    </table>
                    
                    <div style="margin-top:20px;padding-top:20px;border-top:1px solid #1e293b;text-align:center;">
                        <span style="color:#94a3b8;font-size:13px;">Toplam Tutar</span>
                        <div style="color:#10b981;font-size:32px;font-weight:800;margin-top:5px;">{amount}</div>
                    </div>
                </div>
                
                <!-- Button -->
                <div style="text-align:center;margin:30px 0;">
                    <a href="{site_url}/siparis-sorgula.php" style="display:inline-block;background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;text-decoration:none;padding:16px 40px;border-radius:12px;font-weight:600;font-size:15px;">
                        Sipariş Durumunu Takip Et
                    </a>
                </div>
                
                <p style="color:#64748b;font-size:13px;margin:25px 0 0;line-height:1.6;text-align:center;">
                    Sorularınız için bizimle iletişime geçebilirsiniz.
                </p>
            </div>
            
            <!-- Footer -->
            <div style="background:#0f172a;padding:25px;text-align:center;border-top:1px solid #1e293b;">
                <p style="color:#64748b;font-size:13px;margin:0;">
                    © ' . date('Y') . ' {site_name} - Tüm hakları saklıdır.
                </p>
            </div>
        </div>
    </div>
</body>
</html>',

            'order_status' => '
<!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:20px;overflow:hidden;border:1px solid #334155;">
            <!-- Header -->
            <div style="background:linear-gradient(135deg,#6366f1,#8b5cf6);padding:30px;text-align:center;">
                <h1 style="margin:0;color:#fff;font-size:24px;">📦 Sipariş Güncellendi</h1>
            </div>
            
            <!-- Body -->
            <div style="padding:35px 30px;text-align:center;">
                <p style="color:#e2e8f0;font-size:16px;margin:0 0 30px;">
                    Merhaba <strong>{customer_name}</strong>,<br>
                    Siparişinizin durumu güncellendi.
                </p>
                
                <div style="background:#0f172a;border-radius:16px;padding:30px;margin:0 0 25px;border:1px solid #334155;">
                    <p style="color:#94a3b8;font-size:13px;margin:0 0 8px;">Sipariş No: <strong style="color:#fff;">#{order_number}</strong></p>
                    <p style="color:#94a3b8;font-size:13px;margin:0 0 20px;">{package_name}</p>
                    
                    <div style="display:inline-block;background:{status_color};color:#fff;padding:12px 30px;border-radius:50px;font-weight:700;font-size:16px;">
                        {status}
                    </div>
                </div>
                
                <a href="{site_url}/siparis-sorgula.php" style="display:inline-block;background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;text-decoration:none;padding:14px 35px;border-radius:12px;font-weight:600;font-size:14px;">
                    Detayları Görüntüle
                </a>
            </div>
            
            <!-- Footer -->
            <div style="background:#0f172a;padding:25px;text-align:center;border-top:1px solid #1e293b;">
                <p style="color:#64748b;font-size:13px;margin:0;">© ' . date('Y') . ' {site_name}</p>
            </div>
        </div>
    </div>
</body>
</html>',

            'payment_confirmation' => '
<!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:20px;overflow:hidden;border:1px solid #334155;">
            <!-- Header -->
            <div style="background:linear-gradient(135deg,#10b981,#059669);padding:30px;text-align:center;">
                <h1 style="margin:0;color:#fff;font-size:24px;">✅ Ödeme Onaylandı!</h1>
            </div>
            
            <!-- Body -->
            <div style="padding:35px 30px;text-align:center;">
                <div style="width:80px;height:80px;background:linear-gradient(135deg,#10b981,#059669);border-radius:50%;margin:0 auto 25px;line-height:80px;">
                    <span style="font-size:40px;">✓</span>
                </div>
                
                <p style="color:#e2e8f0;font-size:16px;margin:0 0 25px;line-height:1.6;">
                    Merhaba <strong>{customer_name}</strong>,<br><br>
                    Ödemeniz başarıyla onaylandı. Siparişiniz işleme alındı.
                </p>
                
                <div style="background:#0f172a;border-radius:16px;padding:25px;margin:25px 0;border:1px solid #334155;">
                    <table style="width:100%;border-collapse:collapse;">
                        <tr>
                            <td style="padding:10px 0;color:#94a3b8;font-size:14px;">Sipariş No</td>
                            <td style="padding:10px 0;color:#fff;font-size:14px;text-align:right;font-weight:600;">#{order_number}</td>
                        </tr>
                        <tr>
                            <td style="padding:10px 0;color:#94a3b8;font-size:14px;">Paket</td>
                            <td style="padding:10px 0;color:#fff;font-size:14px;text-align:right;">{package_name}</td>
                        </tr>
                        <tr>
                            <td style="padding:10px 0;color:#94a3b8;font-size:14px;">Ödeme Yöntemi</td>
                            <td style="padding:10px 0;color:#fff;font-size:14px;text-align:right;">{payment_method}</td>
                        </tr>
                        <tr>
                            <td style="padding:10px 0;color:#94a3b8;font-size:14px;">Tutar</td>
                            <td style="padding:10px 0;color:#10b981;font-size:18px;text-align:right;font-weight:700;">{amount}</td>
                        </tr>
                    </table>
                </div>
                
                <p style="color:#64748b;font-size:13px;margin:0;line-height:1.6;">
                    Siparişiniz en kısa sürede tamamlanacaktır.<br>
                    Teşekkür ederiz!
                </p>
            </div>
            
            <!-- Footer -->
            <div style="background:#0f172a;padding:25px;text-align:center;border-top:1px solid #1e293b;">
                <p style="color:#64748b;font-size:13px;margin:0;">© ' . date('Y') . ' {site_name}</p>
            </div>
        </div>
    </div>
</body>
</html>',
        ];
        
        $template = $templates[$type] ?? '';
        
        // Değişkenleri değiştir
        foreach ($data as $key => $value) {
            $template = str_replace('{' . $key . '}', htmlspecialchars($value), $template);
        }
        
        return $template;
    }
    
    /**
     * Son hatayı al
     */
    public function getLastError() {
        return $this->lastError;
    }
}