<?php
/**
 * SMM Paket Satış Scripti - Ödeme Sayfası
 * Havale/EFT + iyzico Kredi Kartı Desteği
 * Telegram Bildirimi Dahil
 * @version 2.1.0
 */

// Config'i dahil et
require_once __DIR__ . '/config.php';

// Telegram bildirim fonksiyonlarını dahil et
require_once __DIR__ . '/includes/telegram.php';

// iyzico helper'ı dahil et
require_once __DIR__ . '/includes/iyzico.php';

// Paket ID kontrolü
$packageId = isset($_GET['paket']) ? (int)$_GET['paket'] : 0;

if (!$packageId) {
    setFlash('error', 'Geçersiz paket seçimi.');
    redirect(SITE_URL);
    exit;
}

// Ödeme yöntemi (URL'den veya varsayılan)
$selectedPaymentMethod = isset($_GET['yontem']) ? clean($_GET['yontem']) : 'bank_transfer';

// Paketi çek
try {
    $stmt = $db->prepare("
        SELECT p.*, c.name as category_name, c.icon as category_icon, c.color as category_color 
        FROM packages p 
        JOIN categories c ON p.category_id = c.id 
        WHERE p.id = ? AND p.is_active = 1
    ");
    $stmt->execute([$packageId]);
    $package = $stmt->fetch();
    
    if (!$package) {
        setFlash('error', 'Paket bulunamadı.');
        redirect(SITE_URL);
        exit;
    }
} catch (PDOException $e) {
    setFlash('error', 'Bir hata oluştu.');
    redirect(SITE_URL);
    exit;
}

// Banka hesaplarını çek
try {
    $bankAccounts = $db->query("SELECT * FROM bank_accounts WHERE is_active = 1 ORDER BY sort_order ASC")->fetchAll();
} catch (PDOException $e) {
    $bankAccounts = [];
}

// Aktif ödeme yöntemlerini çek
try {
    $paymentMethods = $db->query("SELECT * FROM payment_methods WHERE is_active = 1 ORDER BY sort_order ASC")->fetchAll();
} catch (PDOException $e) {
    $paymentMethods = [];
}

// iyzico aktif mi kontrol et
$iyzicoEnabled = isIyzicoEnabled($settings);
$iyzicoSDKLoaded = isIyzicoSDKLoaded();

// ==================== KDV AYARLARI ====================
$kdvEnabled = $settings->get('kdv_enabled', '0') == '1';
$kdvRate = floatval($settings->get('kdv_rate', '20'));

// Başlangıç fiyat hesaplaması
$basePrice = floatval($package['price']);
$kdvAmount = 0;
$subtotalWithKdv = $basePrice;

if ($kdvEnabled) {
    $kdvAmount = round($basePrice * ($kdvRate / 100), 2);
    $subtotalWithKdv = $basePrice + $kdvAmount;
}

// Özel alan bilgileri
$fieldLabel = $package['required_field_label'] ?? 'Sosyal Medya Linki / Kullanıcı Adı';
$fieldPlaceholder = $package['required_field_placeholder'] ?? 'https://instagram.com/kullaniciadi veya @kullaniciadi';
$fieldHint = $package['required_field_hint'] ?? 'Hizmetin uygulanacağı hesabın linkini veya kullanıcı adını girin';

// ==================== KUPON DOĞRULAMA FONKSİYONU ====================
function validateCoupon($db, $code, $amount, $ip) {
    $result = [
        'valid' => false,
        'message' => '',
        'coupon' => null,
        'discount' => 0
    ];
    
    if (empty($code)) {
        $result['message'] = 'Kupon kodu girin.';
        return $result;
    }
    
    $stmt = $db->prepare("SELECT * FROM coupons WHERE code = ? AND is_active = 1");
    $stmt->execute([strtoupper($code)]);
    $coupon = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$coupon) {
        $result['message'] = 'Geçersiz kupon kodu.';
        return $result;
    }
    
    $now = time();
    if ($coupon['starts_at'] && strtotime($coupon['starts_at']) > $now) {
        $result['message'] = 'Bu kupon henüz aktif değil.';
        return $result;
    }
    
    if ($coupon['expires_at'] && strtotime($coupon['expires_at']) < $now) {
        $result['message'] = 'Bu kuponun süresi dolmuş.';
        return $result;
    }
    
    if ($coupon['min_amount'] && $amount < $coupon['min_amount']) {
        $result['message'] = 'Bu kupon minimum ' . number_format($coupon['min_amount'], 2, ',', '.') . '₺ siparişlerde geçerlidir.';
        return $result;
    }
    
    if ($coupon['max_amount'] && $amount > $coupon['max_amount']) {
        $result['message'] = 'Bu kupon maksimum ' . number_format($coupon['max_amount'], 2, ',', '.') . '₺ siparişlerde geçerlidir.';
        return $result;
    }
    
    if ($coupon['usage_limit'] && $coupon['usage_count'] >= $coupon['usage_limit']) {
        $result['message'] = 'Bu kuponun kullanım limiti dolmuş.';
        return $result;
    }
    
    if ($coupon['usage_limit_per_ip']) {
        $stmt = $db->prepare("SELECT COUNT(*) FROM coupon_usage WHERE coupon_id = ? AND ip_address = ?");
        $stmt->execute([$coupon['id'], $ip]);
        $ipUsage = $stmt->fetchColumn();
        
        if ($ipUsage >= $coupon['usage_limit_per_ip']) {
            $result['message'] = 'Bu kuponu daha fazla kullanamazsınız.';
            return $result;
        }
    }
    
    if ($coupon['discount_type'] === 'percent') {
        $discount = $amount * ($coupon['discount_value'] / 100);
        if ($coupon['max_discount'] && $discount > $coupon['max_discount']) {
            $discount = $coupon['max_discount'];
        }
    } else {
        $discount = $coupon['discount_value'];
        if ($discount > $amount) {
            $discount = $amount;
        }
    }
    
    $result['valid'] = true;
    $result['coupon'] = $coupon;
    $result['discount'] = round($discount, 2);
    $result['message'] = 'Kupon uygulandı!';
    
    return $result;
}

// ==================== AJAX KUPON KONTROLÜ ====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_coupon_check'])) {
    header('Content-Type: application/json; charset=utf-8');
    
    $couponCode = trim($_POST['coupon_code'] ?? '');
    $ip = getClientIP();
    
    $couponResult = validateCoupon($db, $couponCode, $subtotalWithKdv, $ip);
    $finalTotal = $subtotalWithKdv - $couponResult['discount'];
    
    $response = [
        'success' => $couponResult['valid'],
        'message' => $couponResult['message'],
        'discount' => $couponResult['discount'],
        'discount_formatted' => $couponResult['discount'] > 0 ? formatMoney($couponResult['discount']) : '',
        'final_total' => $finalTotal,
        'final_total_formatted' => formatMoney($finalTotal)
    ];
    
    if ($couponResult['valid'] && $couponResult['coupon']) {
        $c = $couponResult['coupon'];
        if ($c['discount_type'] === 'percent') {
            $response['discount_text'] = '%' . rtrim(rtrim(number_format($c['discount_value'], 2), '0'), '.') . ' indirim';
        } else {
            $response['discount_text'] = formatMoney($c['discount_value']) . ' indirim';
        }
    }
    
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
    exit;
}

// Form değişkenleri
$errors = [];
$formData = [
    'customer_name' => '',
    'customer_email' => '',
    'customer_phone' => '',
    'social_media_link' => '',
    'customer_note' => '',
    'coupon_code' => '',
    'payment_method' => $selectedPaymentMethod
];

// Giriş yapmış kullanıcı varsa bilgilerini doldur
if (isLoggedIn()) {
    try {
        $userStmt = $db->prepare("SELECT full_name, email, phone FROM users WHERE id = ?");
        $userStmt->execute([$_SESSION['user_id']]);
        $currentUser = $userStmt->fetch();
        if ($currentUser) {
            $formData['customer_name'] = $currentUser['full_name'] ?? '';
            $formData['customer_email'] = $currentUser['email'] ?? '';
            $formData['customer_phone'] = $currentUser['phone'] ?? '';
        }
    } catch (PDOException $e) {}
}

// iyzico checkout form içeriği (başarılı başlatma sonrası doldurulacak)
$iyzicoCheckoutForm = null;
$showIyzicoForm = false;

// ==================== FORM GÖNDERİMİ ====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['ajax_coupon_check'])) {
    
    // CSRF kontrolü
    if (!validateCSRFToken($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Güvenlik doğrulaması başarısız. Sayfayı yenileyip tekrar deneyin.';
    }
    
    // Form verilerini al
    $formData = [
        'customer_name' => trim($_POST['customer_name'] ?? ''),
        'customer_email' => trim($_POST['customer_email'] ?? ''),
        'customer_phone' => trim($_POST['customer_phone'] ?? ''),
        'social_media_link' => trim($_POST['social_media_link'] ?? ''),
        'customer_note' => trim($_POST['customer_note'] ?? ''),
        'coupon_code' => strtoupper(trim($_POST['coupon_code'] ?? '')),
        'payment_method' => trim($_POST['payment_method'] ?? 'bank_transfer')
    ];
    
    // Validasyon
    if (empty($formData['customer_name'])) {
        $errors[] = 'Ad soyad zorunludur.';
    } elseif (strlen($formData['customer_name']) < 3) {
        $errors[] = 'Ad soyad en az 3 karakter olmalıdır.';
    }
    
    if (empty($formData['customer_email'])) {
        $errors[] = 'E-posta adresi zorunludur.';
    } elseif (!filter_var($formData['customer_email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Geçerli bir e-posta adresi girin.';
    }
    
    if (empty($formData['customer_phone'])) {
        $errors[] = 'Telefon numarası zorunludur.';
    }
    
    if (empty($formData['social_media_link'])) {
        $errors[] = $fieldLabel . ' zorunludur.';
    }
    
    // Ödeme yöntemi kontrolü
    $validPaymentMethods = ['bank_transfer'];
    if ($iyzicoEnabled) {
        $validPaymentMethods[] = 'iyzico';
    }
    
    if (!in_array($formData['payment_method'], $validPaymentMethods)) {
        $errors[] = 'Geçersiz ödeme yöntemi.';
    }
    
    // Fiyat hesaplama
    $couponId = null;
    $discountAmount = 0;
    $finalAmount = $subtotalWithKdv;
    
    // Kupon kontrolü
    if (!empty($formData['coupon_code'])) {
        $couponResult = validateCoupon($db, $formData['coupon_code'], $subtotalWithKdv, getClientIP());
        
        if (!$couponResult['valid']) {
            $errors[] = $couponResult['message'];
        } else {
            $couponId = $couponResult['coupon']['id'];
            $discountAmount = $couponResult['discount'];
            $finalAmount = $subtotalWithKdv - $discountAmount;
        }
    }
    
    // Dekont yükleme (sadece havale için)
    $paymentProof = null;
    if ($formData['payment_method'] === 'bank_transfer') {
        if (isset($_FILES['payment_proof']) && $_FILES['payment_proof']['error'] === UPLOAD_ERR_OK) {
            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
            $maxSize = 5 * 1024 * 1024;
            
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $fileType = finfo_file($finfo, $_FILES['payment_proof']['tmp_name']);
            finfo_close($finfo);
            
            if (!in_array($fileType, $allowedTypes)) {
                $errors[] = 'Sadece JPG, PNG, GIF veya PDF dosyası yükleyebilirsiniz.';
            } elseif ($_FILES['payment_proof']['size'] > $maxSize) {
                $errors[] = 'Dosya boyutu 5MB\'dan büyük olamaz.';
            } else {
                $uploadDir = __DIR__ . '/uploads/dekont/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                
                $ext = strtolower(pathinfo($_FILES['payment_proof']['name'], PATHINFO_EXTENSION));
                $fileName = 'dekont_' . time() . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
                $uploadPath = $uploadDir . $fileName;
                
                if (move_uploaded_file($_FILES['payment_proof']['tmp_name'], $uploadPath)) {
                    $paymentProof = 'uploads/dekont/' . $fileName;
                } else {
                    $errors[] = 'Dosya yüklenirken hata oluştu.';
                }
            }
        }
    }
    
    // Hata yoksa siparişi oluştur
    if (empty($errors)) {
        try {
            $orderNumber = generateOrderNumber();
            
            $orderStatus = 'pending';
            
            $stmt = $db->prepare("
                INSERT INTO orders (
                    order_number, user_id, package_id, customer_name, customer_email, 
                    customer_phone, social_media_link, payment_method, amount, 
                    discount_amount, coupon_id, coupon_code,
                    kdv_rate, kdv_amount,
                    payment_proof, customer_note, ip_address, status, created_at
                ) VALUES (
                    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW()
                )
            ");
            
            $stmt->execute([
                $orderNumber,
                isLoggedIn() ? $_SESSION['user_id'] : null,
                $packageId,
                $formData['customer_name'],
                $formData['customer_email'],
                $formData['customer_phone'],
                $formData['social_media_link'],
                $formData['payment_method'],
                $finalAmount,
                $discountAmount,
                $couponId,
                $formData['coupon_code'] ?: null,
                $kdvEnabled ? $kdvRate : null,
                $kdvEnabled ? $kdvAmount : null,
                $paymentProof,
                $formData['customer_note'],
                getClientIP(),
                $orderStatus
            ]);
            
            $orderId = $db->lastInsertId();
            
            // Kupon kullanımını kaydet
            if ($couponId) {
                $db->prepare("UPDATE coupons SET usage_count = usage_count + 1 WHERE id = ?")->execute([$couponId]);
                
                $stmt = $db->prepare("
                    INSERT INTO coupon_usage (coupon_id, order_id, ip_address, discount_amount, used_at)
                    VALUES (?, ?, ?, ?, NOW())
                ");
                $stmt->execute([$couponId, $orderId, getClientIP(), $discountAmount]);
            }
            
            // Paket satış sayısını artır
            $db->prepare("UPDATE packages SET total_sales = total_sales + 1 WHERE id = ?")->execute([$packageId]);
            
            // ==================== ÖDEME YÖNTEMİNE GÖRE İŞLEM ====================
            
            if ($formData['payment_method'] === 'iyzico' && $iyzicoEnabled) {
                // ==================== IYZICO ÖDEME ====================
                
                $iyzico = getIyzicoInstance($db, $settings);
                
                // Callback URL
                $callbackUrl = SITE_URL . '/iyzico-callback.php';
                
                // Sipariş verileri
                $orderData = [
                    'order_id' => $orderId,
                    'order_number' => $orderNumber,
                    'package_id' => $packageId,
                    'package_name' => $package['name'],
                    'category_name' => $package['category_name'],
                    'base_price' => $basePrice,
                    'total_price' => $finalAmount
                ];
                
                // Müşteri verileri
                $customerData = [
                    'user_id' => isLoggedIn() ? $_SESSION['user_id'] : null,
                    'name' => $formData['customer_name'],
                    'email' => $formData['customer_email'],
                    'phone' => $formData['customer_phone'],
                    'ip' => getClientIP()
                ];
                
                // iyzico checkout form başlat
                $iyzicoResult = $iyzico->initCheckoutForm($orderData, $customerData, $callbackUrl);
                
                if ($iyzicoResult['success']) {
                    
                    // Sipariş bilgilerini session'a kaydet (callback için)
                    $_SESSION['iyzico_order'] = [
                        'order_id' => $orderId,
                        'order_number' => $orderNumber,
                        'package_name' => $package['name'],
                        'amount' => $finalAmount,
                        'discount' => $discountAmount,
                        'original_amount' => $basePrice,
                        'kdv_enabled' => $kdvEnabled,
                        'kdv_rate' => $kdvRate,
                        'kdv_amount' => $kdvAmount,
                        'subtotal_with_kdv' => $subtotalWithKdv
                    ];
                    
                    // ==================== MOBİL: paymentPageUrl'e yönlendir ====================
                    // iyzico checkout popup mobil tarayıcılarda engelleniyor
                    // Mobil cihazlarda iyzico'nun kendi ödeme sayfasına tam sayfa yönlendirme yap
                    $paymentPageUrl = $iyzicoResult['paymentPageUrl'] ?? null;
                    
                    if (isMobileDevice() && !empty($paymentPageUrl)) {
                        // Mobil: iyzico ödeme sayfasına doğrudan yönlendir
                        header('Location: ' . $paymentPageUrl);
                        exit;
                    }
                    
                    // ==================== MASAÜSTÜ/TABLET: Popup form göster ====================
                    // Masaüstünde popup zaten çalışıyor, aynen devam
                    $iyzicoCheckoutForm = $iyzicoResult['checkoutFormContent'];
                    $showIyzicoForm = true;
                    
                } else {
                    // Hata - Siparişi iptal et
                    $db->prepare("UPDATE orders SET status = 'cancelled', admin_note = ? WHERE id = ?")->execute([
                        'iyzico başlatma hatası: ' . ($iyzicoResult['error_message'] ?? 'Bilinmeyen hata'),
                        $orderId
                    ]);
                    
                    $errors[] = 'Ödeme başlatılamadı: ' . ($iyzicoResult['error_message'] ?? 'Bilinmeyen bir hata oluştu.');
                }
                
            } else {
                // ==================== HAVALE/EFT ÖDEME ====================
                
                // Telegram bildirimi gönder
                try {
                    $orderDataTelegram = [
                        'order_number' => $orderNumber,
                        'customer_name' => $formData['customer_name'],
                        'customer_email' => $formData['customer_email'],
                        'customer_phone' => $formData['customer_phone'],
                        'social_media_link' => $formData['social_media_link'],
                        'amount' => $finalAmount,
                        'discount_amount' => $discountAmount,
                        'coupon_code' => $formData['coupon_code'] ?: null,
                        'kdv_amount' => $kdvEnabled ? $kdvAmount : 0
                    ];
                    
                    $packageDataTelegram = [
                        'name' => $package['name'],
                        'category_name' => $package['category_name']
                    ];
                    
                    sendNewOrderNotification($orderDataTelegram, $packageDataTelegram);
                    
                    if ($paymentProof) {
                        sendPaymentNotification($orderDataTelegram, $packageDataTelegram);
                    }
                } catch (Exception $e) {
                    error_log('Telegram bildirim hatası: ' . $e->getMessage());
                }
                
                // Başarılı sayfasına yönlendir
                $_SESSION['order_success'] = [
                    'order_number' => $orderNumber,
                    'package_name' => $package['name'],
                    'amount' => $finalAmount,
                    'discount' => $discountAmount,
                    'original_amount' => $basePrice,
                    'kdv_enabled' => $kdvEnabled,
                    'kdv_rate' => $kdvRate,
                    'kdv_amount' => $kdvAmount,
                    'subtotal_with_kdv' => $subtotalWithKdv,
                    'payment_method' => 'bank_transfer'
                ];
                
                redirect(SITE_URL . '/siparis-basarili.php');
                exit;
            }
            
        } catch (PDOException $e) {
            $errors[] = 'Sipariş oluşturulurken hata oluştu: ' . $e->getMessage();
        }
    }
}

// Şimdi header'ı dahil et
$pageTitle = 'Ödeme';
require_once __DIR__ . '/header.php';

$features = json_decode($package['features'], true) ?: [];
?>
<style>
.payment-page {
    padding: 40px 0 80px;
}
.payment-container {
    max-width: 1000px;
    margin: 0 auto;
}
.payment-grid {
    display: grid;
    grid-template-columns: 1fr 400px;
    gap: 30px;
}
@media (max-width: 991px) {
    .payment-grid { grid-template-columns: 1fr; }
}

.form-card {
    background: rgba(255,255,255,0.03);
    border: 1px solid rgba(255,255,255,0.08);
    border-radius: 20px;
    padding: 35px;
}
.form-card-title {
    font-size: 22px;
    font-weight: 700;
    margin-bottom: 25px;
    display: flex;
    align-items: center;
    gap: 12px;
}
.form-card-title i {
    width: 45px;
    height: 45px;
    background: var(--gradient);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.form-group { margin-bottom: 20px; }
.form-label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: rgba(255,255,255,0.9);
}
.form-label .required { color: #ef4444; margin-left: 3px; }
.form-control {
    width: 100%;
    background: rgba(255,255,255,0.05);
    border: 1px solid rgba(255,255,255,0.1);
    border-radius: 12px;
    padding: 14px 18px;
    color: #fff;
    font-size: 15px;
    transition: all 0.3s;
    box-sizing: border-box;
}
.form-control:focus {
    outline: none;
    border-color: var(--primary);
    background: rgba(var(--primary-rgb), 0.05);
}
.form-control::placeholder { color: rgba(255,255,255,0.4); }
textarea.form-control { min-height: 100px; resize: vertical; }
.form-hint {
    font-size: 13px;
    color: rgba(255,255,255,0.5);
    margin-top: 6px;
}
.form-hint i { margin-right: 5px; }

/* ==================== ÖDEME YÖNTEMİ SEÇİMİ ==================== */
.payment-method-section {
    margin-bottom: 25px;
    padding-bottom: 25px;
    border-bottom: 1px solid rgba(255,255,255,0.1);
}

.payment-method-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 10px;
    color: rgba(255,255,255,0.9);
}

.payment-method-title i {
    color: var(--primary);
}

.payment-method-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.payment-method-item {
    display: flex;
    align-items: center;
    gap: 15px;
    padding: 18px 20px;
    background: rgba(255,255,255,0.03);
    border: 2px solid rgba(255,255,255,0.08);
    border-radius: 14px;
    cursor: pointer;
    transition: all 0.3s;
}

.payment-method-item:hover {
    border-color: rgba(var(--primary-rgb), 0.3);
    background: rgba(var(--primary-rgb), 0.05);
}

.payment-method-item.active {
    border-color: var(--primary);
    background: rgba(var(--primary-rgb), 0.1);
}

.payment-method-item.disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.payment-method-radio {
    width: 22px;
    height: 22px;
    border: 2px solid rgba(255,255,255,0.3);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    transition: all 0.3s;
}

.payment-method-item.active .payment-method-radio {
    border-color: var(--primary);
    background: var(--primary);
}

.payment-method-item.active .payment-method-radio::after {
    content: '';
    width: 8px;
    height: 8px;
    background: #fff;
    border-radius: 50%;
}

.payment-method-icon {
    width: 50px;
    height: 50px;
    background: rgba(255,255,255,0.05);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
    flex-shrink: 0;
}

.payment-method-item.active .payment-method-icon {
    background: var(--gradient);
    color: #fff;
}

.payment-method-icon.bank { color: #3b82f6; }
.payment-method-icon.card { color: #10b981; }

.payment-method-info {
    flex: 1;
}

.payment-method-info h5 {
    font-size: 16px;
    font-weight: 600;
    margin: 0 0 4px;
    color: #fff;
}

.payment-method-info p {
    font-size: 13px;
    color: rgba(255,255,255,0.6);
    margin: 0;
}

.payment-method-badge {
    padding: 4px 10px;
    background: rgba(16, 185, 129, 0.15);
    border: 1px solid rgba(16, 185, 129, 0.3);
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
    color: #10b981;
}

/* ==================== KUPON BÖLÜMÜ ==================== */
.coupon-section {
    margin-top: 25px;
    padding-top: 25px;
    border-top: 1px solid rgba(255,255,255,0.1);
}

.coupon-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    gap: 8px;
    color: rgba(255,255,255,0.9);
}

.coupon-title i {
    color: var(--primary);
}

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

.coupon-input-group .form-control {
    flex: 1;
    text-transform: uppercase;
}

.coupon-apply-btn {
    padding: 14px 24px;
    background: rgba(var(--primary-rgb), 0.15);
    border: 1px solid rgba(var(--primary-rgb), 0.3);
    border-radius: 12px;
    color: var(--primary);
    font-weight: 600;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s;
    white-space: nowrap;
    display: flex;
    align-items: center;
    gap: 8px;
}

.coupon-apply-btn:hover {
    background: var(--primary);
    color: #fff;
}

.coupon-apply-btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.coupon-apply-btn .spinner {
    width: 16px;
    height: 16px;
    border: 2px solid rgba(255,255,255,0.3);
    border-top-color: currentColor;
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
}

.coupon-result {
    margin-top: 12px;
    padding: 12px 16px;
    border-radius: 10px;
    font-size: 14px;
    display: none;
    align-items: center;
    gap: 10px;
}

.coupon-result.show {
    display: flex;
}

.coupon-result.success {
    background: rgba(16, 185, 129, 0.15);
    border: 1px solid rgba(16, 185, 129, 0.3);
    color: #34d399;
}

.coupon-result.error {
    background: rgba(239, 68, 68, 0.15);
    border: 1px solid rgba(239, 68, 68, 0.3);
    color: #f87171;
}

.coupon-result i {
    font-size: 16px;
}

.coupon-result-text {
    flex: 1;
}

.coupon-remove-btn {
    background: none;
    border: none;
    color: inherit;
    cursor: pointer;
    padding: 4px;
    opacity: 0.7;
    transition: opacity 0.2s;
}

.coupon-remove-btn:hover {
    opacity: 1;
}

/* ==================== BANKA BÖLÜMÜ ==================== */
.bank-section {
    margin-top: 30px;
    padding-top: 30px;
    border-top: 1px solid rgba(255,255,255,0.1);
}

.bank-section.hidden {
    display: none;
}

.bank-section-title {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 10px;
}
.bank-section-title i { color: var(--primary); }

.bank-amount-info {
    background: rgba(var(--primary-rgb), 0.1);
    border: 1px solid rgba(var(--primary-rgb), 0.2);
    border-radius: 12px;
    padding: 15px 20px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.bank-amount-label { font-size: 14px; opacity: 0.8; }
.bank-amount-value { font-size: 24px; font-weight: 800; color: var(--primary); }

.bank-list { display: flex; flex-direction: column; gap: 15px; }
.bank-item {
    background: rgba(255,255,255,0.03);
    border: 1px solid rgba(255,255,255,0.08);
    border-radius: 12px;
    padding: 20px;
}
.bank-item-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 15px;
}
.bank-logo {
    width: 45px;
    height: 45px;
    background: linear-gradient(135deg, #667eea, #764ba2);
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    color: #fff;
    font-size: 14px;
}
.bank-name { font-weight: 600; font-size: 16px; }
.bank-details { display: flex; flex-direction: column; gap: 8px; }
.bank-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 14px;
    background: rgba(255,255,255,0.03);
    border-radius: 8px;
    gap: 10px;
    flex-wrap: wrap;
}
.bank-row-label { font-size: 13px; opacity: 0.6; }
.bank-row-value {
    font-family: monospace;
    font-size: 14px;
    font-weight: 500;
    word-break: break-all;
}
.btn-copy {
    background: rgba(var(--primary-rgb), 0.1);
    border: none;
    color: var(--primary);
    cursor: pointer;
    padding: 8px 12px;
    border-radius: 6px;
    font-size: 13px;
    transition: all 0.3s;
}
.btn-copy:hover { background: var(--primary); color: #fff; }
.btn-copy.copied { background: #10b981; color: #fff; }

/* ==================== DEKONT YÜKLEME ==================== */
.upload-section { margin-top: 25px; }

.upload-section.hidden {
    display: none;
}

.upload-area {
    border: 2px dashed rgba(255,255,255,0.2);
    border-radius: 12px;
    padding: 30px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s;
}
.upload-area:hover { border-color: var(--primary); background: rgba(var(--primary-rgb), 0.05); }
.upload-icon {
    width: 60px;
    height: 60px;
    background: rgba(var(--primary-rgb), 0.1);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 15px;
    font-size: 24px;
    color: var(--primary);
}
.upload-text { font-size: 15px; margin-bottom: 5px; }
.upload-hint { font-size: 13px; opacity: 0.6; }
.upload-input { display: none; }
.upload-preview {
    margin-top: 15px;
    padding: 15px;
    background: rgba(16, 185, 129, 0.1);
    border: 1px solid rgba(16, 185, 129, 0.2);
    border-radius: 10px;
    display: none;
    align-items: center;
    gap: 12px;
}
.upload-preview.show { display: flex; }
.upload-preview i.fa-file { font-size: 28px; color: #10b981; }
.upload-preview-info { flex: 1; }
.upload-preview-name { font-size: 14px; font-weight: 500; }
.upload-preview-size { font-size: 12px; opacity: 0.6; }
.upload-preview-remove { color: #ef4444; cursor: pointer; font-size: 18px; }

/* ==================== IYZICO BÖLÜMÜ ==================== */
.iyzico-section {
    margin-top: 30px;
    padding-top: 30px;
    border-top: 1px solid rgba(255,255,255,0.1);
}

.iyzico-section.hidden {
    display: none;
}

.iyzico-info-box {
    background: rgba(16, 185, 129, 0.1);
    border: 1px solid rgba(16, 185, 129, 0.2);
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 20px;
}

.iyzico-info-box i {
    color: #10b981;
    margin-right: 10px;
}

.iyzico-info-box p {
    margin: 0;
    font-size: 14px;
    color: rgba(255,255,255,0.8);
}

.iyzico-logos {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 15px;
    margin-top: 15px;
    flex-wrap: wrap;
}

.iyzico-logos img {
    height: 30px;
    opacity: 0.8;
}

.iyzico-logos span {
    padding: 6px 12px;
    background: rgba(255,255,255,0.1);
    border-radius: 6px;
    font-size: 12px;
    font-weight: 600;
}

/* ==================== IYZICO CHECKOUT FORM ==================== */
.iyzico-checkout-container {
    background: rgba(255,255,255,0.03);
    border: 1px solid rgba(255,255,255,0.08);
    border-radius: 20px;
    padding: 35px;
    margin-top: 30px;
}

.iyzico-checkout-header {
    text-align: center;
    margin-bottom: 25px;
}

.iyzico-checkout-header h3 {
    font-size: 20px;
    font-weight: 700;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
}

.iyzico-checkout-header h3 i {
    color: #10b981;
}

.iyzico-checkout-header p {
    font-size: 14px;
    color: rgba(255,255,255,0.6);
    margin: 0;
}

.iyzico-checkout-form-wrapper {
    min-height: 400px;
}

#iyzipay-checkout-form {
    width: 100% !important;
}

#iyzipay-checkout-form iframe {
    width: 100% !important;
    min-height: 450px;
}

/* ==================== ÖZET KARTI ==================== */
.summary-card {
    background: rgba(255,255,255,0.03);
    border: 1px solid rgba(255,255,255,0.08);
    border-radius: 20px;
    padding: 30px;
    position: sticky;
    top: 100px;
    height: fit-content;
}
.summary-title {
    font-size: 18px;
    font-weight: 700;
    margin-bottom: 25px;
}
.summary-package {
    display: flex;
    align-items: center;
    gap: 15px;
    padding: 20px;
    background: rgba(var(--primary-rgb), 0.1);
    border-radius: 14px;
    margin-bottom: 25px;
}
.summary-package-icon {
    width: 55px;
    height: 55px;
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 26px;
    color: #fff;
}
.summary-package-info h4 { font-size: 16px; font-weight: 600; margin: 0 0 4px; }
.summary-package-info span { font-size: 13px; opacity: 0.7; }

.summary-features { list-style: none; padding: 0; margin: 0 0 20px; }
.summary-features li {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 8px 0;
    font-size: 14px;
    border-bottom: 1px solid rgba(255,255,255,0.05);
}
.summary-features li:last-child { border: none; }
.summary-features li i { color: #10b981; font-size: 12px; }

.summary-delivery {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 12px 15px;
    background: rgba(255,255,255,0.03);
    border-radius: 10px;
    font-size: 14px;
    margin-bottom: 20px;
}
.summary-delivery i { color: var(--primary); }

/* ==================== ÖZET FİYAT BÖLÜMÜ ==================== */
.summary-pricing {
    border-top: 1px solid rgba(255,255,255,0.1);
    padding-top: 20px;
    margin-bottom: 20px;
}

.summary-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    font-size: 14px;
}

.summary-row.base-price {
    color: rgba(255,255,255,0.7);
}

.summary-row.kdv {
    color: rgba(255,255,255,0.6);
    font-size: 13px;
}

.summary-row.kdv.hidden {
    display: none;
}

.summary-row.subtotal {
    color: rgba(255,255,255,0.8);
    padding-top: 10px;
    margin-top: 5px;
    border-top: 1px dashed rgba(255,255,255,0.08);
    font-weight: 600;
}

.summary-row.subtotal.hidden {
    display: none;
}

.summary-row.discount {
    color: #34d399;
    display: none;
}

.summary-row.discount.show {
    display: flex;
}

.summary-row.discount .discount-value {
    display: flex;
    align-items: center;
    gap: 6px;
}

.summary-row.total {
    padding-top: 15px;
    margin-top: 10px;
    border-top: 1px solid rgba(255,255,255,0.15);
}

.summary-row.total .label {
    font-size: 16px;
    font-weight: 600;
}

.summary-row.total .value {
    font-size: 28px;
    font-weight: 800;
    background: var(--gradient);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

/* ==================== BUTONLAR ==================== */
.btn-submit {
    width: 100%;
    background: var(--gradient);
    border: none;
    color: #fff;
    padding: 16px;
    border-radius: 12px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
}
.btn-submit:hover { transform: translateY(-2px); box-shadow: var(--shadow); }
.btn-submit:disabled { opacity: 0.6; cursor: not-allowed; transform: none; }
.btn-submit .spinner {
    display: inline-block;
    width: 18px;
    height: 18px;
    border: 2px solid rgba(255,255,255,0.3);
    border-top-color: #fff;
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
    margin-right: 8px;
}
@keyframes spin { to { transform: rotate(360deg); } }

.secure-badge {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    margin-top: 15px;
    font-size: 13px;
    opacity: 0.6;
}
.secure-badge i { color: #10b981; }

/* ==================== HATA KUTUSU ==================== */
.error-box {
    background: rgba(239, 68, 68, 0.1);
    border: 1px solid rgba(239, 68, 68, 0.3);
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 25px;
}
.error-box-title {
    font-weight: 600;
    color: #ef4444;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    gap: 8px;
}
.error-box ul { margin: 0; padding-left: 20px; }
.error-box li { color: rgba(255,255,255,0.8); margin-bottom: 5px; font-size: 14px; }

.back-link {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: rgba(255,255,255,0.7);
    margin-bottom: 30px;
    font-size: 15px;
}
.back-link:hover { color: #fff; }

/* ==================== RESPONSIVE ==================== */
@media (max-width: 576px) {
    .form-card, .summary-card { padding: 25px; }
    .coupon-input-group { flex-direction: column; }
    .coupon-apply-btn { justify-content: center; }
    .summary-row.total .value { font-size: 24px; }
    .payment-method-item { flex-wrap: wrap; }
    .payment-method-badge { margin-top: 10px; width: 100%; text-align: center; }
}
</style>

<section class="payment-page">
    <div class="container">
        <div class="payment-container">
            <a href="<?php echo SITE_URL; ?>/#packages" class="back-link">
                <i class="fas fa-arrow-left"></i> Paketlere Dön
            </a>
            
            <?php if ($showIyzicoForm && $iyzicoCheckoutForm): ?>
            <!-- ==================== IYZICO CHECKOUT FORM (MASAÜSTÜ) ==================== -->
            <div class="iyzico-checkout-container">
                <div class="iyzico-checkout-header">
                    <h3><i class="fas fa-lock"></i> Güvenli Ödeme</h3>
                    <p>Kart bilgilerinizi girerek ödemenizi tamamlayın</p>
                </div>
                
                <div class="iyzico-checkout-form-wrapper">
                    <?php echo $iyzicoCheckoutForm; ?>
                </div>
            </div>
            
            <?php else: ?>
            <!-- ==================== NORMAL ÖDEME FORMU ==================== -->
            <div class="payment-grid">
                <!-- Form -->
                <div class="form-card">
                    <h2 class="form-card-title">
                        <i class="fas fa-file-invoice"></i>
                        Sipariş Bilgileri
                    </h2>
                    
                    <?php if (!empty($errors)): ?>
                    <div class="error-box">
                        <div class="error-box-title">
                            <i class="fas fa-exclamation-circle"></i> Lütfen hataları düzeltin
                        </div>
                        <ul>
                            <?php foreach ($errors as $error): ?>
                            <li><?php echo clean($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                    <?php endif; ?>
                    
                    <form method="POST" enctype="multipart/form-data" id="paymentForm">
                        <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                        <input type="hidden" name="payment_method" id="paymentMethodInput" value="<?php echo clean($formData['payment_method']); ?>">
                        
                        <!-- Ödeme Yöntemi Seçimi -->
                        <div class="payment-method-section">
                            <div class="payment-method-title">
                                <i class="fas fa-wallet"></i> Ödeme Yöntemi Seçin
                            </div>
                            
                            <div class="payment-method-list">
                                <!-- Havale/EFT -->
                                <div class="payment-method-item <?php echo $formData['payment_method'] === 'bank_transfer' ? 'active' : ''; ?>" 
                                     data-method="bank_transfer" onclick="selectPaymentMethod('bank_transfer')">
                                    <div class="payment-method-radio"></div>
                                    <div class="payment-method-icon bank">
                                        <i class="fas fa-university"></i>
                                    </div>
                                    <div class="payment-method-info">
                                        <h5>Havale / EFT</h5>
                                        <p>Banka havalesi ile ödeme yapın</p>
                                    </div>
                                </div>
                                
                                <!-- Kredi Kartı (iyzico) -->
                                <?php if ($iyzicoEnabled): ?>
                                <div class="payment-method-item <?php echo $formData['payment_method'] === 'iyzico' ? 'active' : ''; ?>" 
                                     data-method="iyzico" onclick="selectPaymentMethod('iyzico')">
                                    <div class="payment-method-radio"></div>
                                    <div class="payment-method-icon card">
                                        <i class="fas fa-credit-card"></i>
                                    </div>
                                    <div class="payment-method-info">
                                        <h5>Kredi / Banka Kartı</h5>
                                        <p>Güvenli ödeme - Taksit imkanı</p>
                                    </div>
                                    <div class="payment-method-badge">
                                        <i class="fas fa-shield-alt"></i> Güvenli
                                    </div>
                                </div>
                                <?php elseif ($iyzicoSDKLoaded): ?>
                                <div class="payment-method-item disabled" title="Kredi kartı ödemesi şu an aktif değil">
                                    <div class="payment-method-radio"></div>
                                    <div class="payment-method-icon card">
                                        <i class="fas fa-credit-card"></i>
                                    </div>
                                    <div class="payment-method-info">
                                        <h5>Kredi / Banka Kartı</h5>
                                        <p>Şu an kullanılamıyor</p>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <!-- Müşteri Bilgileri -->
                        <div class="form-group">
                            <label class="form-label">Ad Soyad<span class="required">*</span></label>
                            <input type="text" name="customer_name" class="form-control" placeholder="Adınız Soyadınız" value="<?php echo clean($formData['customer_name']); ?>" required>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">E-posta Adresi<span class="required">*</span></label>
                            <input type="email" name="customer_email" class="form-control" placeholder="ornek@email.com" value="<?php echo clean($formData['customer_email']); ?>" required>
                            <div class="form-hint"><i class="fas fa-info-circle"></i> Sipariş durumu bu adrese gönderilecek</div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Telefon Numarası<span class="required">*</span></label>
                            <input type="tel" name="customer_phone" class="form-control" placeholder="05XX XXX XX XX" value="<?php echo clean($formData['customer_phone']); ?>" required>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label"><?php echo clean($fieldLabel); ?><span class="required">*</span></label>
                            <input type="text" name="social_media_link" class="form-control" placeholder="<?php echo clean($fieldPlaceholder); ?>" value="<?php echo clean($formData['social_media_link']); ?>" required>
                            <div class="form-hint"><i class="fas fa-info-circle"></i> <?php echo clean($fieldHint); ?></div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Not (Opsiyonel)</label>
                            <textarea name="customer_note" class="form-control" placeholder="Eklemek istediğiniz notlar..."><?php echo clean($formData['customer_note']); ?></textarea>
                        </div>
                        
                        <!-- Kupon Bölümü -->
                        <div class="coupon-section">
                            <div class="coupon-title">
                                <i class="fas fa-ticket-alt"></i> Kupon Kodu
                            </div>
                            
                            <div class="coupon-input-group">
                                <input type="text" name="coupon_code" id="couponInput" class="form-control" 
                                       placeholder="Kupon kodunuz varsa girin" 
                                       value="<?php echo clean($formData['coupon_code']); ?>"
                                       maxlength="50" autocomplete="off">
                                <button type="button" class="coupon-apply-btn" id="couponApplyBtn" onclick="applyCoupon()">
                                    <i class="fas fa-check"></i> Uygula
                                </button>
                            </div>
                            
                            <div class="coupon-result" id="couponResult">
                                <i class="fas fa-check-circle"></i>
                                <span class="coupon-result-text" id="couponResultText"></span>
                                <button type="button" class="coupon-remove-btn" onclick="removeCoupon()" title="Kuponu Kaldır">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        </div>
                        
                        <!-- Banka Hesapları (Sadece Havale seçiliyse) -->
                        <div class="bank-section <?php echo $formData['payment_method'] !== 'bank_transfer' ? 'hidden' : ''; ?>" id="bankSection">
                            <h3 class="bank-section-title">
                                <i class="fas fa-university"></i> Banka Hesaplarımız
                            </h3>
                            
                            <div class="bank-amount-info">
                                <span class="bank-amount-label">Gönderilecek Tutar:</span>
                                <span class="bank-amount-value" id="bankAmountDisplay"><?php echo formatMoney($subtotalWithKdv); ?></span>
                            </div>
                            
                            <div class="bank-list">
                                <?php foreach ($bankAccounts as $bank): ?>
                                <div class="bank-item">
                                    <div class="bank-item-header">
                                        <div class="bank-logo"><?php echo strtoupper(substr($bank['bank_name'], 0, 2)); ?></div>
                                        <div class="bank-name"><?php echo clean($bank['bank_name']); ?></div>
                                    </div>
                                    <div class="bank-details">
                                        <div class="bank-row">
                                            <span class="bank-row-label">Hesap Sahibi</span>
                                            <span class="bank-row-value"><?php echo clean($bank['account_holder']); ?></span>
                                            <button type="button" class="btn-copy" onclick="copyText('<?php echo clean($bank['account_holder']); ?>', this)">
                                                <i class="fas fa-copy"></i>
                                            </button>
                                        </div>
                                        <div class="bank-row">
                                            <span class="bank-row-label">IBAN</span>
                                            <span class="bank-row-value"><?php echo clean($bank['iban']); ?></span>
                                            <button type="button" class="btn-copy" onclick="copyText('<?php echo str_replace(' ', '', $bank['iban']); ?>', this)">
                                                <i class="fas fa-copy"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        
                        <!-- Dekont Yükleme (Sadece Havale seçiliyse) -->
                        <div class="upload-section <?php echo $formData['payment_method'] !== 'bank_transfer' ? 'hidden' : ''; ?>" id="uploadSection">
                            <label class="form-label">Dekont Yükle (Opsiyonel)</label>
                            <div class="upload-area" id="uploadArea">
                                <div class="upload-icon"><i class="fas fa-cloud-upload-alt"></i></div>
                                <div class="upload-text">Dekont yüklemek için tıklayın</div>
                                <div class="upload-hint">JPG, PNG, GIF veya PDF - Max 5MB</div>
                                <input type="file" name="payment_proof" class="upload-input" id="uploadInput" accept=".jpg,.jpeg,.png,.gif,.pdf">
                            </div>
                            <div class="upload-preview" id="uploadPreview">
                                <i class="fas fa-file"></i>
                                <div class="upload-preview-info">
                                    <div class="upload-preview-name" id="uploadFileName"></div>
                                    <div class="upload-preview-size" id="uploadFileSize"></div>
                                </div>
                                <i class="fas fa-times upload-preview-remove" onclick="removeUpload()"></i>
                            </div>
                            <div class="form-hint"><i class="fas fa-bolt"></i> Dekont yüklerseniz siparişiniz daha hızlı onaylanır</div>
                        </div>
                        
                        <!-- iyzico Bilgi (Sadece iyzico seçiliyse) -->
                        <div class="iyzico-section <?php echo $formData['payment_method'] !== 'iyzico' ? 'hidden' : ''; ?>" id="iyzicoSection">
                            <div class="iyzico-info-box">
                                <p><i class="fas fa-shield-alt"></i> Kart bilgileriniz iyzico güvencesi altında işlenir. Bilgileriniz sunucularımızda saklanmaz.</p>
                                <div class="iyzico-logos">
                                    <span><i class="fab fa-cc-visa"></i> VISA</span>
                                    <span><i class="fab fa-cc-mastercard"></i> MasterCard</span>
                                    <span><i class="fas fa-credit-card"></i> Troy</span>
                                </div>
                            </div>
                        </div>
                        
                        <button type="submit" class="btn-submit d-lg-none" style="margin-top: 25px;" id="submitBtnMobile">
                            <i class="fas fa-check-circle me-2"></i> <span id="submitBtnMobileText">Siparişi Tamamla</span>
                        </button>
                    </form>
                </div>
                
                <!-- Özet -->
                <div class="summary-card">
                    <h3 class="summary-title"><i class="fas fa-shopping-cart me-2"></i>Sipariş Özeti</h3>
                    
                    <div class="summary-package">
                        <div class="summary-package-icon" style="background: <?php echo $package['category_color']; ?>">
                            <i class="<?php echo $package['category_icon']; ?>"></i>
                        </div>
                        <div class="summary-package-info">
                            <h4><?php echo clean($package['name']); ?></h4>
                            <span><?php echo clean($package['category_name']); ?></span>
                        </div>
                    </div>
                    
                    <?php if (!empty($features)): ?>
                    <ul class="summary-features">
                        <?php foreach ($features as $feature): ?>
                        <li><i class="fas fa-check"></i> <?php echo clean($feature); ?></li>
                        <?php endforeach; ?>
                    </ul>
                    <?php endif; ?>
                    
                    <?php if (!empty($package['delivery_time'])): ?>
                    <div class="summary-delivery">
                        <i class="fas fa-clock"></i>
                        <span>Teslimat: <strong><?php echo clean($package['delivery_time']); ?></strong></span>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Fiyat Özeti -->
                    <div class="summary-pricing">
                        <div class="summary-row base-price">
                            <span>Paket Fiyatı</span>
                            <span><?php echo formatMoney($basePrice); ?></span>
                        </div>
                        
                        <div class="summary-row kdv <?php echo !$kdvEnabled ? 'hidden' : ''; ?>" id="kdvRow">
                            <span>KDV (%<?php echo $kdvRate; ?>)</span>
                            <span id="kdvDisplay"><?php echo formatMoney($kdvAmount); ?></span>
                        </div>
                        
                        <div class="summary-row subtotal <?php echo !$kdvEnabled ? 'hidden' : ''; ?>" id="subtotalRow">
                            <span>Ara Toplam</span>
                            <span id="subtotalDisplay"><?php echo formatMoney($subtotalWithKdv); ?></span>
                        </div>
                        
                        <div class="summary-row discount" id="discountRow">
                            <span>Kupon İndirimi</span>
                            <span class="discount-value">
                                <span id="discountText"></span>
                                -<span id="discountDisplay">0,00₺</span>
                            </span>
                        </div>
                        
                        <div class="summary-row total">
                            <span class="label">Toplam</span>
                            <span class="value" id="totalDisplay"><?php echo formatMoney($subtotalWithKdv); ?></span>
                        </div>
                    </div>
                    
                    <button type="submit" form="paymentForm" class="btn-submit d-none d-lg-block" id="submitBtn">
                        <i class="fas fa-check-circle me-2"></i> <span id="submitBtnText">Siparişi Tamamla</span>
                    </button>
                    
                    <div class="secure-badge">
                        <i class="fas fa-shield-alt"></i> Güvenli Ödeme
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</section>
<script>
// ==================== DEĞİŞKENLER ====================
var basePrice = <?php echo $basePrice; ?>;
var kdvEnabled = <?php echo $kdvEnabled ? 'true' : 'false'; ?>;
var kdvRate = <?php echo $kdvRate; ?>;
var kdvAmount = <?php echo $kdvAmount; ?>;
var subtotalWithKdv = <?php echo $subtotalWithKdv; ?>;
var currencySymbol = '<?php echo $settings->get("currency_symbol", "₺"); ?>';
var iyzicoEnabled = <?php echo $iyzicoEnabled ? 'true' : 'false'; ?>;

var currentDiscount = 0;
var couponApplied = false;
var selectedPaymentMethod = '<?php echo $formData['payment_method']; ?>';

// ==================== PARA FORMATI ====================
function formatMoney(amount) {
    return currencySymbol + parseFloat(amount).toFixed(2).replace('.', ',');
}

// ==================== KOPYALAMA ====================
function copyText(text, btn) {
    navigator.clipboard.writeText(text).then(function() {
        btn.classList.add('copied');
        btn.innerHTML = '<i class="fas fa-check"></i>';
        setTimeout(function() {
            btn.classList.remove('copied');
            btn.innerHTML = '<i class="fas fa-copy"></i>';
        }, 2000);
    });
}

// ==================== ÖDEME YÖNTEMİ SEÇİMİ ====================
function selectPaymentMethod(method) {
    var item = document.querySelector('.payment-method-item[data-method="' + method + '"]');
    if (item && item.classList.contains('disabled')) {
        return;
    }
    
    selectedPaymentMethod = method;
    document.getElementById('paymentMethodInput').value = method;
    
    document.querySelectorAll('.payment-method-item').forEach(function(el) {
        el.classList.remove('active');
    });
    
    if (item) {
        item.classList.add('active');
    }
    
    var bankSection = document.getElementById('bankSection');
    var uploadSection = document.getElementById('uploadSection');
    var iyzicoSection = document.getElementById('iyzicoSection');
    
    if (method === 'bank_transfer') {
        bankSection.classList.remove('hidden');
        uploadSection.classList.remove('hidden');
        if (iyzicoSection) iyzicoSection.classList.add('hidden');
        updateSubmitButton('Siparişi Tamamla', 'fas fa-check-circle');
    } else if (method === 'iyzico') {
        bankSection.classList.add('hidden');
        uploadSection.classList.add('hidden');
        if (iyzicoSection) iyzicoSection.classList.remove('hidden');
        updateSubmitButton('Ödemeye Geç', 'fas fa-credit-card');
    }
}

// ==================== SUBMIT BUTON GÜNCELLEME ====================
function updateSubmitButton(text, icon) {
    var btnText = document.getElementById('submitBtnText');
    var btnTextMobile = document.getElementById('submitBtnMobileText');
    
    if (btnText) btnText.innerHTML = text;
    if (btnTextMobile) btnTextMobile.innerHTML = text;
    
    var btn = document.getElementById('submitBtn');
    var btnMobile = document.getElementById('submitBtnMobile');
    
    if (btn) {
        btn.innerHTML = '<i class="' + icon + ' me-2"></i> <span id="submitBtnText">' + text + '</span>';
    }
    if (btnMobile) {
        btnMobile.innerHTML = '<i class="' + icon + ' me-2"></i> <span id="submitBtnMobileText">' + text + '</span>';
    }
}

// ==================== KUPON FONKSİYONLARI ====================
function applyCoupon() {
    var input = document.getElementById('couponInput');
    var btn = document.getElementById('couponApplyBtn');
    
    var code = input.value.trim().toUpperCase();
    
    if (!code) {
        showCouponResult(false, 'Kupon kodu girin.');
        return;
    }
    
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner"></span> Kontrol...';
    
    var formData = new FormData();
    formData.append('ajax_coupon_check', '1');
    formData.append('coupon_code', code);
    
    fetch(window.location.href, {
        method: 'POST',
        body: formData
    })
    .then(function(response) { return response.json(); })
    .then(function(data) {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-check"></i> Uygula';
        
        if (data.success) {
            couponApplied = true;
            currentDiscount = data.discount;
            
            showCouponResult(true, data.message + ' (' + data.discount_text + ')');
            
            input.readOnly = true;
            input.style.opacity = '0.7';
            btn.style.display = 'none';
            
            updatePrices(data.discount, data.discount_formatted, data.final_total_formatted);
        } else {
            showCouponResult(false, data.message);
        }
    })
    .catch(function(error) {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-check"></i> Uygula';
        showCouponResult(false, 'Bir hata oluştu. Tekrar deneyin.');
    });
}

function showCouponResult(success, message) {
    var result = document.getElementById('couponResult');
    var resultText = document.getElementById('couponResultText');
    var icon = result.querySelector('i:first-child');
    
    result.classList.remove('success', 'error');
    result.classList.add('show', success ? 'success' : 'error');
    
    icon.className = success ? 'fas fa-check-circle' : 'fas fa-exclamation-circle';
    resultText.textContent = message;
    
    result.querySelector('.coupon-remove-btn').style.display = success ? 'block' : 'none';
    
    if (!success) {
        setTimeout(function() {
            result.classList.remove('show');
        }, 3000);
    }
}

function removeCoupon() {
    var input = document.getElementById('couponInput');
    var btn = document.getElementById('couponApplyBtn');
    var result = document.getElementById('couponResult');
    
    couponApplied = false;
    currentDiscount = 0;
    
    input.value = '';
    input.readOnly = false;
    input.style.opacity = '1';
    btn.style.display = 'flex';
    
    result.classList.remove('show');
    
    resetPrices();
}

function updatePrices(discount, discountFormatted, finalTotalFormatted) {
    var discountRow = document.getElementById('discountRow');
    var discountDisplay = document.getElementById('discountDisplay');
    var totalDisplay = document.getElementById('totalDisplay');
    var bankAmountDisplay = document.getElementById('bankAmountDisplay');
    
    discountRow.classList.add('show');
    discountDisplay.textContent = discountFormatted;
    
    totalDisplay.textContent = finalTotalFormatted;
    
    if (bankAmountDisplay) {
        bankAmountDisplay.textContent = finalTotalFormatted;
    }
}

function resetPrices() {
    var discountRow = document.getElementById('discountRow');
    var totalDisplay = document.getElementById('totalDisplay');
    var bankAmountDisplay = document.getElementById('bankAmountDisplay');
    
    var originalTotal = formatMoney(subtotalWithKdv);
    
    discountRow.classList.remove('show');
    
    totalDisplay.textContent = originalTotal;
    if (bankAmountDisplay) {
        bankAmountDisplay.textContent = originalTotal;
    }
}

// Kupon input - Enter tuşu ve büyük harf
var couponInput = document.getElementById('couponInput');
if (couponInput) {
    couponInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            if (!couponApplied) {
                applyCoupon();
            }
        }
    });
    
    couponInput.addEventListener('input', function() {
        this.value = this.value.toUpperCase();
    });
}

// ==================== DOSYA YÜKLEME ====================
var uploadArea = document.getElementById('uploadArea');
var uploadInput = document.getElementById('uploadInput');
var uploadPreview = document.getElementById('uploadPreview');
var uploadFileName = document.getElementById('uploadFileName');
var uploadFileSize = document.getElementById('uploadFileSize');

if (uploadArea && uploadInput) {
    uploadArea.addEventListener('click', function() { uploadInput.click(); });
    
    uploadInput.addEventListener('change', function() {
        if (uploadInput.files.length) {
            var file = uploadInput.files[0];
            uploadFileName.textContent = file.name;
            uploadFileSize.textContent = (file.size / 1024 / 1024).toFixed(2) + ' MB';
            uploadPreview.classList.add('show');
            uploadArea.style.display = 'none';
        }
    });
}

function removeUpload() {
    if (uploadInput) uploadInput.value = '';
    if (uploadPreview) uploadPreview.classList.remove('show');
    if (uploadArea) uploadArea.style.display = 'block';
}

// ==================== FORM SUBMIT ====================
var paymentForm = document.getElementById('paymentForm');
if (paymentForm) {
    paymentForm.addEventListener('submit', function(e) {
        var btns = document.querySelectorAll('.btn-submit');
        
        var loadingText = 'İşleniyor...';
        if (selectedPaymentMethod === 'iyzico') {
            loadingText = 'Ödeme sayfasına yönlendiriliyorsunuz...';
        }
        
        btns.forEach(function(btn) {
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner"></span> ' + loadingText;
        });
    });
}

// ==================== SAYFA YÜKLENDİĞİNDE ====================
document.addEventListener('DOMContentLoaded', function() {
    if (document.getElementById('paymentMethodInput')) {
        selectPaymentMethod(selectedPaymentMethod);
    }
});
</script>

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