<?php
/**
 * SMM Paket Satış Scripti - Paket Düzenle
 * Alt Kategori Desteği ile
 * @version 1.1.0
 */

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

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

$packageId = (int)($_GET['id'] ?? 0);

if ($packageId <= 0) {
    setFlash('error', 'Geçersiz paket.');
    redirect(SITE_URL . '/admin/paketler.php');
    exit;
}

// Paketi çek
try {
    $stmt = $db->prepare("SELECT * FROM packages WHERE id = ?");
    $stmt->execute([$packageId]);
    $package = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$package) {
        setFlash('error', 'Paket bulunamadı.');
        redirect(SITE_URL . '/admin/paketler.php');
        exit;
    }
} catch (PDOException $e) {
    setFlash('error', 'Veritabanı hatası.');
    redirect(SITE_URL . '/admin/paketler.php');
    exit;
}

// parent_id sütunu var mı kontrol
function hasParentColumn($db) {
    try {
        $result = $db->query("SHOW COLUMNS FROM categories LIKE 'parent_id'")->fetch();
        return !empty($result);
    } catch (PDOException $e) {
        return false;
    }
}

$hasParentSupport = hasParentColumn($db);

// Kategorileri çek (hiyerarşik)
try {
    if ($hasParentSupport) {
        // Ana kategoriler
        $categories = $db->query("
            SELECT c.*, 
                   (SELECT COUNT(*) FROM categories c2 WHERE c2.parent_id = c.id) as subcategory_count
            FROM categories c 
            WHERE c.is_active = 1 AND (c.parent_id IS NULL OR c.parent_id = 0)
            ORDER BY c.sort_order, c.name
        ")->fetchAll(PDO::FETCH_ASSOC);
        
        // Alt kategorileri çek
        $allSubcategories = $db->query("
            SELECT * FROM categories 
            WHERE is_active = 1 AND parent_id IS NOT NULL AND parent_id > 0
            ORDER BY sort_order, name
        ")->fetchAll(PDO::FETCH_ASSOC);
        
        // Alt kategorileri parent_id'ye göre grupla
        $subcategoriesByParent = [];
        foreach ($allSubcategories as $sub) {
            $subcategoriesByParent[$sub['parent_id']][] = $sub;
        }
        
        // Paketin mevcut kategorisinin parent'ını bul
        $currentCategoryId = $package['category_id'];
        $currentParentId = 0;
        $currentSubcategoryId = 0;
        
        // Mevcut kategori bir alt kategori mi kontrol et
        foreach ($allSubcategories as $sub) {
            if ($sub['id'] == $currentCategoryId) {
                $currentParentId = $sub['parent_id'];
                $currentSubcategoryId = $currentCategoryId;
                break;
            }
        }
        
        // Alt kategori değilse, ana kategori olarak ayarla
        if ($currentParentId == 0) {
            $currentParentId = $currentCategoryId;
            $currentSubcategoryId = 0;
        }
    } else {
        $categories = $db->query("SELECT * FROM categories WHERE is_active = 1 ORDER BY sort_order")->fetchAll(PDO::FETCH_ASSOC);
        $subcategoriesByParent = [];
        $currentParentId = $package['category_id'];
        $currentSubcategoryId = 0;
    }
} catch (PDOException $e) {
    $categories = [];
    $subcategoriesByParent = [];
    $currentParentId = $package['category_id'];
    $currentSubcategoryId = 0;
}

// API sağlayıcılarını çek
try {
    $providers = $db->query("SELECT * FROM api_providers WHERE status = 'active' ORDER BY name")->fetchAll();
} catch (PDOException $e) {
    $providers = [];
}

// Seçili değerler (GET > POST > Package)
$selectedProviderId = (int)($_GET['provider'] ?? $_POST['api_provider_id'] ?? $package['api_provider_id'] ?? 0);
$selectedApiCategory = $_GET['api_category'] ?? $_POST['api_category'] ?? '';
$selectedServiceId = $_GET['service'] ?? $_POST['api_service_id'] ?? $package['api_service_id'] ?? '';

// Paket türü belirleme
$isAutoPackage = !empty($package['api_provider_id']);
$packageType = 'manual';

if (isset($_POST['package_type'])) {
    $packageType = $_POST['package_type'];
} elseif (isset($_GET['type'])) {
    $packageType = $_GET['type'];
} elseif ($selectedProviderId > 0 || $isAutoPackage) {
    $packageType = 'auto';
}

// API servislerini ve kategorilerini çek
$apiServices = [];
$apiCategories = [];
$totalServicesCount = 0;

if ($selectedProviderId > 0) {
    try {
        // Önce tüm kategorileri çek (DISTINCT ile)
        $stmt = $db->prepare("
            SELECT DISTINCT category 
            FROM api_services 
            WHERE provider_id = ? 
            ORDER BY category ASC
        ");
        $stmt->execute([$selectedProviderId]);
        $catResults = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($catResults as $row) {
            $apiCategories[] = $row['category'] ?: 'Diğer';
        }
        
        // Toplam servis sayısı
        $stmt = $db->prepare("SELECT COUNT(*) FROM api_services WHERE provider_id = ?");
        $stmt->execute([$selectedProviderId]);
        $totalServicesCount = $stmt->fetchColumn();
        
        // Eğer kategori seçilmemişse ve mevcut servis varsa, o servisin kategorisini bul
        if ($selectedApiCategory === '' && $selectedServiceId) {
            $stmt = $db->prepare("SELECT category FROM api_services WHERE provider_id = ? AND service_id = ?");
            $stmt->execute([$selectedProviderId, $selectedServiceId]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($result) {
                $selectedApiCategory = $result['category'] ?: 'Diğer';
            }
        }
        
        // Seçili kategorideki servisleri çek
        if ($selectedApiCategory !== '') {
            $stmt = $db->prepare("
                SELECT service_id, name, category, type, rate, min, max 
                FROM api_services 
                WHERE provider_id = ? AND (category = ? OR (category IS NULL AND ? = 'Diğer') OR (category = '' AND ? = 'Diğer'))
                ORDER BY service_id ASC
            ");
            $stmt->execute([$selectedProviderId, $selectedApiCategory, $selectedApiCategory, $selectedApiCategory]);
            $apiServices = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        
    } catch (PDOException $e) {
        $apiServices = [];
        $apiCategories = [];
    }
}

// Seçili sağlayıcının bilgileri
$selectedProvider = null;
foreach ($providers as $p) {
    if ($p['id'] == $selectedProviderId) {
        $selectedProvider = $p;
        break;
    }
}
$selectedMultiplier = $selectedProvider['rate_multiplier'] ?? 1.5;
$providerCurrency = $selectedProvider['currency'] ?? 'USD';

// Para birimi sembolleri
$currencySymbols = [
    'TRY' => '₺',
    'USD' => '$',
    'EUR' => '€',
    'GBP' => '£'
];
$providerCurrencySymbol = $currencySymbols[$providerCurrency] ?? $providerCurrency;

// Seçili servisin bilgileri
$selectedService = null;
if ($selectedServiceId) {
    foreach ($apiServices as $s) {
        if ($s['service_id'] == $selectedServiceId) {
            $selectedService = $s;
            break;
        }
    }
}

// Site para birimi ve kuru
$siteCurrency = 'TRY';
$siteCurrencySymbol = '₺';
if (isset($settings) && method_exists($settings, 'get')) {
    $siteCurrency = $settings->get('currency', 'TRY');
    $siteCurrencySymbol = $settings->get('currency_symbol', '₺');
}

// Döviz kuru hesaplama
$exchangeRate = 1;
if ($providerCurrency !== $siteCurrency) {
    if ($providerCurrency === 'USD' && $siteCurrency === 'TRY') {
        $exchangeRate = isset($settings) ? $settings->get('usd_rate', 32.50) : 32.50;
    } elseif ($providerCurrency === 'EUR' && $siteCurrency === 'TRY') {
        $exchangeRate = isset($settings) ? $settings->get('eur_rate', 35.00) : 35.00;
    }
}

// Mevcut features'ı parse et
$currentFeatures = json_decode($package['features'] ?? '[]', true);
$featuresText = is_array($currentFeatures) ? implode("\n", $currentFeatures) : '';

// Form verileri (POST > Package)
$formData = [
    'package_type' => $packageType,
    'category_id' => $_POST['category_id'] ?? $currentParentId,
    'subcategory_id' => $_POST['subcategory_id'] ?? $currentSubcategoryId,
    'name' => $_POST['name'] ?? $package['name'],
    'description' => $_POST['description'] ?? $package['description'],
    'price' => $_POST['price'] ?? $package['price'],
    'old_price' => $_POST['old_price'] ?? $package['old_price'],
    'quantity' => $_POST['quantity'] ?? $package['quantity'],
    'delivery_time' => $_POST['delivery_time'] ?? $package['delivery_time'],
    'features' => $_POST['features'] ?? $featuresText,
    'required_field_label' => $_POST['required_field_label'] ?? $package['required_field_label'],
    'required_field_placeholder' => $_POST['required_field_placeholder'] ?? $package['required_field_placeholder'],
    'required_field_hint' => $_POST['required_field_hint'] ?? $package['required_field_hint'],
    'is_featured' => isset($_POST['save_package']) ? (isset($_POST['is_featured']) ? 1 : 0) : $package['is_featured'],
    'is_popular' => isset($_POST['save_package']) ? (isset($_POST['is_popular']) ? 1 : 0) : $package['is_popular'],
    'is_active' => isset($_POST['save_package']) ? (isset($_POST['is_active']) ? 1 : 0) : $package['is_active'],
    'sort_order' => $_POST['sort_order'] ?? $package['sort_order'],
    'api_provider_id' => $selectedProviderId,
    'api_category' => $selectedApiCategory,
    'api_service_id' => $selectedServiceId
];

// Form gönderildi - Kaydet
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_package'])) {
    $type = $formData['package_type'];
    $categoryId = (int)$formData['category_id'];
    $subcategoryId = (int)$formData['subcategory_id'];
    $name = trim($formData['name']);
    $description = trim($formData['description']);
    $price = (float)$formData['price'];
    $oldPrice = !empty($formData['old_price']) ? (float)$formData['old_price'] : null;
    $quantity = (int)$formData['quantity'];
    $deliveryTime = trim($formData['delivery_time']);
    $features = array_filter(array_map('trim', explode("\n", $formData['features'])));
    $isFeatured = $formData['is_featured'];
    $isPopular = $formData['is_popular'];
    $isActive = $formData['is_active'];
    $sortOrder = (int)$formData['sort_order'];
    
    $requiredFieldLabel = trim($formData['required_field_label']);
    $requiredFieldPlaceholder = trim($formData['required_field_placeholder']);
    $requiredFieldHint = trim($formData['required_field_hint']);
    
    $apiProviderId = null;
    $apiServiceId = null;
    
    if ($type === 'auto') {
        $apiProviderId = $selectedProviderId ?: null;
        $apiServiceId = $selectedServiceId ?: null;
    }
    
    // Alt kategori seçildiyse onu kullan, yoksa ana kategoriyi kullan
    $finalCategoryId = ($subcategoryId > 0) ? $subcategoryId : $categoryId;
    
    // Validasyon
    if (empty($name)) $errors[] = 'Paket adı gerekli.';
    if ($categoryId <= 0) $errors[] = 'Kategori seçin.';
    if ($price <= 0) $errors[] = 'Geçerli bir fiyat girin.';
    if ($type === 'auto' && empty($apiProviderId)) $errors[] = 'API sağlayıcı seçin.';
    if ($type === 'auto' && empty($apiServiceId)) $errors[] = 'API servisi seçin.';
    
    if (empty($errors)) {
        try {
            $stmt = $db->prepare("
                UPDATE packages SET
                    category_id = ?, name = ?, description = ?, features = ?, price = ?, old_price = ?,
                    quantity = ?, delivery_time = ?, required_field_label = ?, required_field_placeholder = ?,
                    required_field_hint = ?, is_featured = ?, is_popular = ?, is_active = ?, sort_order = ?,
                    api_provider_id = ?, api_service_id = ?, updated_at = NOW()
                WHERE id = ?
            ");
            
            $stmt->execute([
                $finalCategoryId, $name, $description, json_encode($features, JSON_UNESCAPED_UNICODE),
                $price, $oldPrice, $quantity, $deliveryTime, $requiredFieldLabel,
                $requiredFieldPlaceholder, $requiredFieldHint, $isFeatured, $isPopular,
                $isActive, $sortOrder, $apiProviderId, $apiServiceId, $packageId
            ]);
            
            setFlash('success', 'Paket başarıyla güncellendi.');
            redirect(SITE_URL . '/admin/paketler.php');
            exit;
            
        } catch (PDOException $e) {
            $errors[] = 'Veritabanı hatası: ' . $e->getMessage();
        }
    }
}

// Para formatı fonksiyonu
function formatPrice($amount, $decimals = 2) {
    return number_format((float)$amount, $decimals, ',', '.');
}

// Paket istatistikleri
$packageStats = [
    'total_orders' => 0,
    'total_revenue' => 0,
    'created_at' => $package['created_at'],
    'updated_at' => $package['updated_at']
];

try {
    $stmt = $db->prepare("SELECT COUNT(*) as total, SUM(amount) as revenue FROM orders WHERE package_id = ?");
    $stmt->execute([$packageId]);
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($stats) {
        $packageStats['total_orders'] = (int)$stats['total'];
        $packageStats['total_revenue'] = (float)$stats['revenue'];
    }
} catch (PDOException $e) {
    // İstatistik çekilemezse sorun değil
}

$adminPageTitle = 'Paket Düzenle: ' . $package['name'];
require_once __DIR__ . '/header.php';
?>

<style>
.page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 25px;
    flex-wrap: wrap;
    gap: 15px;
}

.page-header-left {
    display: flex;
    align-items: center;
    gap: 15px;
}

.page-header-info h1 {
    font-size: 18px;
    font-weight: 700;
    margin: 0 0 5px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.page-header-info h1 i { color: var(--primary); }

.page-header-badges {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.header-badge {
    padding: 4px 10px;
    border-radius: 6px;
    font-size: 11px;
    font-weight: 600;
}

.header-badge.id {
    background: var(--bg-hover);
    color: var(--text-secondary);
}

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

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

.header-badge.auto {
    background: rgba(139, 92, 246, 0.15);
    color: #8b5cf6;
}

.header-badge.manual {
    background: rgba(59, 130, 246, 0.15);
    color: #3b82f6;
}

/* Package Stats Card */
.package-stats-card {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 16px;
    padding: 20px;
    margin-bottom: 25px;
}

.package-stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
}

.package-stat-item {
    text-align: center;
    padding: 15px;
    background: var(--bg-hover);
    border-radius: 12px;
}

.package-stat-icon {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 10px;
    font-size: 18px;
}

.package-stat-value {
    font-size: 20px;
    font-weight: 700;
    margin-bottom: 4px;
}

.package-stat-label {
    font-size: 12px;
    color: var(--text-secondary);
}

/* Form Card */
.form-card {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 16px;
    overflow: hidden;
    margin-bottom: 25px;
}

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

.form-card-header i { color: var(--primary); }
.form-card-header h3 { font-size: 16px; font-weight: 600; margin: 0; }
.form-card-body { padding: 25px; }

.form-row {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
}

.form-row.three { grid-template-columns: repeat(3, 1fr); }

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

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

.form-label .required { color: #ef4444; margin-left: 2px; }

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

.form-control, .form-select { width: 100%; }

textarea.form-control { min-height: 100px; resize: vertical; }

/* Subcategory Select */
.subcategory-select-wrapper {
    margin-top: 15px;
    padding: 15px;
    background: rgba(139, 92, 246, 0.05);
    border: 1px solid rgba(139, 92, 246, 0.2);
    border-radius: 10px;
    display: none;
}

.subcategory-select-wrapper.show {
    display: block;
}

.subcategory-select-wrapper label {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 13px;
    font-weight: 500;
    margin-bottom: 8px;
    color: #8b5cf6;
}

.subcategory-select-wrapper label i {
    font-size: 14px;
}

/* Package Type Selector */
.type-selector {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
    margin-bottom: 25px;
}

.type-option {
    background: var(--bg-hover);
    border: 2px solid var(--border-color);
    border-radius: 12px;
    padding: 20px;
    cursor: pointer;
    transition: all 0.3s;
    text-align: center;
}

.type-option:hover { border-color: rgba(var(--primary-rgb), 0.5); }

.type-option.active {
    border-color: var(--primary);
    background: rgba(var(--primary-rgb), 0.1);
}

.type-option input { display: none; }

.type-option-icon {
    width: 60px;
    height: 60px;
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 26px;
    margin: 0 auto 15px;
}

.type-option.manual .type-option-icon {
    background: rgba(16, 185, 129, 0.15);
    color: #10b981;
}

.type-option.auto .type-option-icon {
    background: rgba(139, 92, 246, 0.15);
    color: #8b5cf6;
}

.type-option-title { font-size: 16px; font-weight: 700; margin-bottom: 5px; }
.type-option-desc { font-size: 12px; color: var(--text-secondary); }

/* API Section */
.api-section {
    display: none;
    background: rgba(139, 92, 246, 0.05);
    border: 1px solid rgba(139, 92, 246, 0.2);
    border-radius: 12px;
    padding: 20px;
}

.api-section.show { display: block; }

.api-section-title {
    font-size: 14px;
    font-weight: 600;
    color: #8b5cf6;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 8px;
}

/* Service Info Box */
.service-info-box {
    background: rgba(59, 130, 246, 0.1);
    border: 1px solid rgba(59, 130, 246, 0.2);
    border-radius: 10px;
    padding: 15px;
    margin-top: 15px;
}

.service-info-box h5 {
    font-size: 13px;
    font-weight: 600;
    color: #3b82f6;
    margin: 0 0 12px;
    display: flex;
    align-items: center;
    gap: 6px;
}

.service-info-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
}

.service-info-item {
    background: rgba(255,255,255,0.05);
    padding: 10px 12px;
    border-radius: 8px;
}

.service-info-item label {
    font-size: 11px;
    color: var(--text-secondary);
    display: block;
    margin-bottom: 3px;
}

.service-info-item span {
    font-size: 14px;
    font-weight: 600;
    color: var(--text-primary);
}

.service-info-item span.price { color: #10b981; }
.service-info-item span.api-price { color: #f59e0b; }

/* Alert Box */
.alert-box {
    border-radius: 10px;
    padding: 15px;
    margin-top: 15px;
    display: flex;
    align-items: flex-start;
    gap: 12px;
    font-size: 13px;
}

.alert-box i { font-size: 18px; margin-top: 2px; }

.alert-box.warning {
    background: rgba(245, 158, 11, 0.1);
    border: 1px solid rgba(245, 158, 11, 0.3);
    color: #f59e0b;
}

.alert-box.info {
    background: rgba(59, 130, 246, 0.1);
    border: 1px solid rgba(59, 130, 246, 0.3);
    color: #3b82f6;
}

.alert-box.success {
    background: rgba(16, 185, 129, 0.1);
    border: 1px solid rgba(16, 185, 129, 0.3);
    color: #10b981;
}

.alert-box a { color: inherit; text-decoration: underline; }

/* Step Indicator */
.api-steps {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
}

.api-step {
    flex: 1;
    text-align: center;
    padding: 12px;
    background: var(--bg-hover);
    border-radius: 8px;
    font-size: 12px;
    color: var(--text-secondary);
    position: relative;
}

.api-step.active {
    background: rgba(139, 92, 246, 0.2);
    color: #8b5cf6;
    font-weight: 600;
}

.api-step.completed {
    background: rgba(16, 185, 129, 0.2);
    color: #10b981;
}

.api-step-number {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background: var(--border-color);
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    margin-bottom: 5px;
}

.api-step.active .api-step-number {
    background: #8b5cf6;
    color: #fff;
}

.api-step.completed .api-step-number {
    background: #10b981;
    color: #fff;
}

/* Provider Info Badge */
.provider-info-badge {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    background: rgba(139, 92, 246, 0.1);
    padding: 8px 12px;
    border-radius: 8px;
    font-size: 12px;
    margin-top: 10px;
}

.provider-info-badge i { color: #8b5cf6; }

/* Current API Info */
.current-api-info {
    background: rgba(16, 185, 129, 0.1);
    border: 1px solid rgba(16, 185, 129, 0.2);
    border-radius: 10px;
    padding: 15px;
    margin-bottom: 20px;
}

.current-api-info h5 {
    font-size: 13px;
    font-weight: 600;
    color: #10b981;
    margin: 0 0 10px;
    display: flex;
    align-items: center;
    gap: 6px;
}

.current-api-info p {
    font-size: 12px;
    color: var(--text-secondary);
    margin: 0;
}

.current-api-info strong {
    color: var(--text-primary);
}

/* Checkbox / Switch */
.form-check-custom {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 15px;
    background: var(--bg-hover);
    border-radius: 10px;
    cursor: pointer;
    transition: all 0.2s;
}

.form-check-custom:hover { background: rgba(var(--primary-rgb), 0.1); }

.form-check-custom input {
    width: 20px;
    height: 20px;
    accent-color: var(--primary);
    cursor: pointer;
}

.form-check-custom-label { flex: 1; }
.form-check-custom-label span { display: block; font-size: 14px; font-weight: 500; }
.form-check-custom-label small { font-size: 12px; color: var(--text-secondary); }

/* Error Box */
.error-box {
    background: rgba(239, 68, 68, 0.1);
    border: 1px solid rgba(239, 68, 68, 0.3);
    border-radius: 12px;
    padding: 15px 20px;
    margin-bottom: 25px;
}

.error-box ul { margin: 0; padding-left: 20px; }
.error-box li { color: #ef4444; font-size: 13px; margin-bottom: 5px; }

/* Form Actions */
.form-actions {
    display: flex;
    gap: 15px;
    padding-top: 20px;
    border-top: 1px solid var(--border-color);
    margin-top: 25px;
}

.btn-danger-custom {
    background: rgba(239, 68, 68, 0.15);
    color: #ef4444;
    border: none;
    padding: 12px 24px;
    border-radius: 10px;
    font-weight: 600;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: all 0.2s;
    margin-left: auto;
}

.btn-danger-custom:hover {
    background: #ef4444;
    color: #fff;
}

@media (max-width: 991px) {
    .package-stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 768px) {
    .form-row, .form-row.three { grid-template-columns: 1fr; }
    .type-selector { grid-template-columns: 1fr; }
    .api-steps { flex-direction: column; }
    .service-info-grid { grid-template-columns: 1fr; }
    .package-stats-grid { grid-template-columns: 1fr; }
    .form-actions { flex-direction: column; }
    .form-actions .btn-primary-custom,
    .form-actions .btn-secondary-custom,
    .form-actions .btn-danger-custom { 
        width: 100%; 
        justify-content: center;
        margin-left: 0;
    }
    .page-header { flex-direction: column; align-items: flex-start; }
}
</style>

<div class="page-header">
    <div class="page-header-left">
        <div class="page-header-info">
            <h1>
                <i class="fas fa-edit"></i>
                Paket Düzenle
            </h1>
            <div class="page-header-badges">
                <span class="header-badge id">ID: <?php echo $package['id']; ?></span>
                <span class="header-badge <?php echo $package['is_active'] ? 'active' : 'inactive'; ?>">
                    <?php echo $package['is_active'] ? 'Aktif' : 'Pasif'; ?>
                </span>
                <span class="header-badge <?php echo $isAutoPackage ? 'auto' : 'manual'; ?>">
                    <?php echo $isAutoPackage ? 'Otomatik' : 'Manuel'; ?>
                </span>
            </div>
        </div>
    </div>
    <a href="<?php echo SITE_URL; ?>/admin/paketler.php" class="btn-secondary-custom">
        <i class="fas fa-arrow-left"></i> Geri Dön
    </a>
</div>

<!-- Package Stats -->
<div class="package-stats-card">
    <div class="package-stats-grid">
        <div class="package-stat-item">
            <div class="package-stat-icon" style="background: rgba(59, 130, 246, 0.15); color: #3b82f6;">
                <i class="fas fa-shopping-cart"></i>
            </div>
            <div class="package-stat-value"><?php echo number_format($packageStats['total_orders']); ?></div>
            <div class="package-stat-label">Toplam Sipariş</div>
        </div>
        <div class="package-stat-item">
            <div class="package-stat-icon" style="background: rgba(16, 185, 129, 0.15); color: #10b981;">
                <i class="fas fa-lira-sign"></i>
            </div>
            <div class="package-stat-value"><?php echo $siteCurrencySymbol . formatPrice($packageStats['total_revenue']); ?></div>
            <div class="package-stat-label">Toplam Gelir</div>
        </div>
        <div class="package-stat-item">
            <div class="package-stat-icon" style="background: rgba(139, 92, 246, 0.15); color: #8b5cf6;">
                <i class="fas fa-calendar-plus"></i>
            </div>
            <div class="package-stat-value"><?php echo date('d.m.Y', strtotime($packageStats['created_at'])); ?></div>
            <div class="package-stat-label">Oluşturulma</div>
        </div>
        <div class="package-stat-item">
            <div class="package-stat-icon" style="background: rgba(245, 158, 11, 0.15); color: #f59e0b;">
                <i class="fas fa-clock"></i>
            </div>
            <div class="package-stat-value"><?php echo $packageStats['updated_at'] ? date('d.m.Y', strtotime($packageStats['updated_at'])) : '-'; ?></div>
            <div class="package-stat-label">Son Güncelleme</div>
        </div>
    </div>
</div>

<?php if (!empty($errors)): ?>
<div class="error-box">
    <ul>
        <?php foreach ($errors as $error): ?>
            <li><?php echo clean($error); ?></li>
        <?php endforeach; ?>
    </ul>
</div>
<?php endif; ?>

<form method="POST" id="packageForm">
    <!-- Gizli alanlar -->
    <input type="hidden" name="package_type" id="packageTypeInput" value="<?php echo $packageType; ?>">
    
    <!-- Package Type -->
    <div class="form-card">
        <div class="form-card-header">
            <i class="fas fa-cog"></i>
            <h3>Paket Türü</h3>
        </div>
        <div class="form-card-body">
            <div class="type-selector">
                <label class="type-option manual <?php echo $packageType === 'manual' ? 'active' : ''; ?>" onclick="selectType('manual')">
                    <input type="radio" name="package_type_radio" value="manual" <?php echo $packageType === 'manual' ? 'checked' : ''; ?>>
                    <div class="type-option-icon">
                        <i class="fas fa-hand-paper"></i>
                    </div>
                    <div class="type-option-title">Manuel Paket</div>
                    <div class="type-option-desc">Siparişleri kendiniz işleyeceksiniz</div>
                </label>
                <label class="type-option auto <?php echo $packageType === 'auto' ? 'active' : ''; ?>" onclick="selectType('auto')">
                    <input type="radio" name="package_type_radio" value="auto" <?php echo $packageType === 'auto' ? 'checked' : ''; ?>>
                    <div class="type-option-icon">
                        <i class="fas fa-robot"></i>
                    </div>
                    <div class="type-option-title">Otomatik Paket</div>
                    <div class="type-option-desc">API üzerinden otomatik işlenecek</div>
                </label>
            </div>
            
            <!-- API Selection -->
            <div class="api-section <?php echo $packageType === 'auto' ? 'show' : ''; ?>" id="apiSection">
                <div class="api-section-title">
                    <i class="fas fa-plug"></i>
                    API Bağlantısı
                </div>
                
                <?php if ($isAutoPackage && $package['api_service_id']): ?>
                <!-- Mevcut API Bilgisi -->
                <div class="current-api-info">
                    <h5><i class="fas fa-link"></i> Mevcut Bağlantı</h5>
                    <p>
                        Bu paket şu an 
                        <strong><?php 
                            foreach ($providers as $p) {
                                if ($p['id'] == $package['api_provider_id']) {
                                    echo clean($p['name']);
                                    break;
                                }
                            }
                        ?></strong> 
                        sağlayıcısının 
                        <strong>#<?php echo $package['api_service_id']; ?></strong> 
                        numaralı servisine bağlı.
                    </p>
                </div>
                <?php endif; ?>
                
                <!-- Step Indicator -->
                <div class="api-steps">
                    <div class="api-step <?php echo $selectedProviderId ? 'completed' : 'active'; ?>">
                        <div class="api-step-number"><?php echo $selectedProviderId ? '✓' : '1'; ?></div>
                        <div>Sağlayıcı Seç</div>
                    </div>
                    <div class="api-step <?php echo $selectedProviderId ? ($selectedApiCategory ? 'completed' : 'active') : ''; ?>">
                        <div class="api-step-number"><?php echo $selectedApiCategory ? '✓' : '2'; ?></div>
                        <div>Kategori Seç</div>
                    </div>
                    <div class="api-step <?php echo $selectedApiCategory ? ($selectedServiceId ? 'completed' : 'active') : ''; ?>">
                        <div class="api-step-number"><?php echo $selectedServiceId ? '✓' : '3'; ?></div>
                        <div>Servis Seç</div>
                    </div>
                </div>
                
                <!-- Step 1: Provider -->
                <div class="form-group">
                    <label class="form-label">1. API Sağlayıcı<span class="required">*</span></label>
                    <select name="api_provider_id" id="apiProvider" class="form-select" onchange="changeProvider(this.value)">
                        <option value="">-- Sağlayıcı Seçin --</option>
                        <?php foreach ($providers as $provider): ?>
                            <option value="<?php echo $provider['id']; ?>" 
                                    data-multiplier="<?php echo $provider['rate_multiplier']; ?>"
                                    data-currency="<?php echo $provider['currency']; ?>"
                                    <?php echo $selectedProviderId == $provider['id'] ? 'selected' : ''; ?>>
                                <?php echo clean($provider['name']); ?> 
                                (<?php echo formatPrice($provider['balance']); ?> <?php echo $provider['currency']; ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <?php if ($selectedProvider): ?>
                        <div class="provider-info-badge">
                            <i class="fas fa-info-circle"></i>
                            <span>Para Birimi: <strong><?php echo $providerCurrency; ?></strong></span>
                            <span>|</span>
                            <span>Çarpan: <strong><?php echo formatPrice($selectedMultiplier, 2); ?>x</strong></span>
                            <span>|</span>
                            <span>Servis: <strong><?php echo number_format($totalServicesCount); ?></strong></span>
                        </div>
                    <?php endif; ?>
                </div>
                
                <?php if ($selectedProviderId): ?>
                    <?php if (empty($apiCategories)): ?>
                        <div class="alert-box warning">
                            <i class="fas fa-exclamation-triangle"></i>
                            <div>
                                Bu sağlayıcıda henüz servis yok. 
                                <a href="<?php echo SITE_URL; ?>/admin/api-saglayicilar.php">API Sağlayıcıları</a> 
                                sayfasından "Servisler" butonuna tıklayarak servisleri çekin.
                            </div>
                        </div>
                    <?php else: ?>
                        <!-- Step 2: API Category -->
                        <div class="form-group">
                            <label class="form-label">2. API Kategorisi<span class="required">*</span></label>
                            <select name="api_category" id="apiCategory" class="form-select" onchange="changeCategory(this.value)">
                                <option value="">-- Kategori Seçin (<?php echo count($apiCategories); ?> kategori) --</option>
                                <?php foreach ($apiCategories as $cat): ?>
                                    <option value="<?php echo clean($cat); ?>" <?php echo $selectedApiCategory === $cat ? 'selected' : ''; ?>>
                                        <?php echo clean($cat); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <?php if ($selectedApiCategory): ?>
                            <!-- Step 3: Service -->
                            <div class="form-group" style="margin-bottom: 0;">
                                <label class="form-label">3. Servis<span class="required">*</span></label>
                                <?php if (empty($apiServices)): ?>
                                    <div class="alert-box warning">
                                        <i class="fas fa-info-circle"></i>
                                        <div>Bu kategoride servis bulunamadı.</div>
                                    </div>
                                <?php else: ?>
                                    <select name="api_service_id" id="apiService" class="form-select" onchange="selectService(this.value)">
                                        <option value="">-- Servis Seçin (<?php echo count($apiServices); ?> servis) --</option>
                                        <?php foreach ($apiServices as $service): ?>
                                            <option value="<?php echo $service['service_id']; ?>"
                                                    data-name="<?php echo clean($service['name']); ?>"
                                                    data-rate="<?php echo $service['rate']; ?>"
                                                    data-min="<?php echo $service['min']; ?>"
                                                    data-max="<?php echo $service['max']; ?>"
                                                    <?php echo $selectedServiceId == $service['service_id'] ? 'selected' : ''; ?>>
                                                [<?php echo $service['service_id']; ?>] <?php echo clean($service['name']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    
                                    <?php if ($selectedService): ?>
                                    <!-- Service Info Box -->
                                    <?php
                                    $apiRate = (float)$selectedService['rate'];
                                    $minQty = (int)$selectedService['min'];
                                    $maxQty = (int)$selectedService['max'];
                                    $convertedRate = $apiRate * $exchangeRate;
                                    $rateWithMultiplier = $convertedRate * $selectedMultiplier;
                                    $calculatedPrice = ($rateWithMultiplier / 1000) * $minQty;
                                    ?>
                                    <div class="service-info-box" id="serviceInfoBox">
                                        <h5><i class="fas fa-calculator"></i> Fiyat Hesaplama</h5>
                                        <div class="service-info-grid">
                                            <div class="service-info-item">
                                                <label>API Fiyatı (1000 adet)</label>
                                                <span class="api-price"><?php echo $providerCurrencySymbol . formatPrice($apiRate, 4); ?></span>
                                            </div>
                                            <div class="service-info-item">
                                                <label>Fiyat Çarpanı</label>
                                                <span><?php echo formatPrice($selectedMultiplier, 2); ?>x</span>
                                            </div>
                                            <div class="service-info-item">
                                                <label>Minimum Miktar</label>
                                                <span><?php echo number_format($minQty, 0, ',', '.'); ?></span>
                                            </div>
                                            <div class="service-info-item">
                                                <label>Maksimum Miktar</label>
                                                <span><?php echo number_format($maxQty, 0, ',', '.'); ?></span>
                                            </div>
                                            <?php if ($providerCurrency !== $siteCurrency): ?>
                                            <div class="service-info-item">
                                                <label>Döviz Kuru (<?php echo $providerCurrency; ?> → <?php echo $siteCurrency; ?>)</label>
                                                <span><?php echo $siteCurrencySymbol . formatPrice($exchangeRate, 2); ?></span>
                                            </div>
                                            <div class="service-info-item">
                                                <label>Çevrilmiş Fiyat (1000 adet)</label>
                                                <span><?php echo $siteCurrencySymbol . formatPrice($convertedRate, 4); ?></span>
                                            </div>
                                            <?php endif; ?>
                                            <div class="service-info-item">
                                                <label>Çarpanlı Fiyat (1000 adet)</label>
                                                <span><?php echo $siteCurrencySymbol . formatPrice($rateWithMultiplier, 4); ?></span>
                                            </div>
                                            <div class="service-info-item">
                                                <label>Önerilen Satış Fiyatı (Min. <?php echo number_format($minQty, 0, ',', '.'); ?> adet)</label>
                                                <span class="price"><?php echo $siteCurrencySymbol . formatPrice($calculatedPrice, 2); ?></span>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="alert-box info">
                        <i class="fas fa-info-circle"></i>
                        <div>Servisleri görmek için önce bir API sağlayıcı seçin.</div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Basic Info -->
    <div class="form-card">
        <div class="form-card-header">
            <i class="fas fa-info-circle"></i>
            <h3>Temel Bilgiler</h3>
        </div>
        <div class="form-card-body">
            <div class="form-row">
                <div class="form-group">
                    <label class="form-label">Kategori<span class="required">*</span></label>
                    <select name="category_id" id="categorySelect" class="form-select" required onchange="onCategoryChange(this.value)">
                        <option value="">-- Kategori Seçin --</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>" 
                                    data-has-sub="<?php echo isset($subcategoriesByParent[$cat['id']]) ? '1' : '0'; ?>"
                                    <?php echo $formData['category_id'] == $cat['id'] ? 'selected' : ''; ?>>
                                <?php echo clean($cat['name']); ?>
                                <?php if ($hasParentSupport && isset($cat['subcategory_count']) && $cat['subcategory_count'] > 0): ?>
                                    (<?php echo $cat['subcategory_count']; ?> alt kategori)
                                <?php endif; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    
                    <?php if ($hasParentSupport && !empty($subcategoriesByParent)): ?>
                    <!-- Alt Kategori Seçimi -->
                    <div class="subcategory-select-wrapper <?php echo ($formData['subcategory_id'] > 0 || isset($subcategoriesByParent[$formData['category_id']])) ? 'show' : ''; ?>" id="subcategoryWrapper">
                        <label><i class="fas fa-sitemap"></i> Alt Kategori (Opsiyonel)</label>
                        <select name="subcategory_id" id="subcategorySelect" class="form-select">
                            <option value="">-- Alt Kategori Seçin (Opsiyonel) --</option>
                            <?php if (isset($subcategoriesByParent[$formData['category_id']])): ?>
                                <?php foreach ($subcategoriesByParent[$formData['category_id']] as $sub): ?>
                                    <option value="<?php echo $sub['id']; ?>" <?php echo $formData['subcategory_id'] == $sub['id'] ? 'selected' : ''; ?>>
                                        <?php echo clean($sub['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                        <div class="form-hint">Alt kategori seçmezseniz paket ana kategoride görünür.</div>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="form-group">
                    <label class="form-label">Paket Adı<span class="required">*</span></label>
                    <input type="text" name="name" id="packageName" class="form-control" value="<?php echo clean($formData['name']); ?>" required>
                </div>
            </div>
            
            <div class="form-group">
                <label class="form-label">Açıklama</label>
                <textarea name="description" class="form-control"><?php echo clean($formData['description']); ?></textarea>
            </div>
            
            <div class="form-group">
                <label class="form-label">Özellikler</label>
                <textarea name="features" class="form-control" rows="4"><?php echo clean($formData['features']); ?></textarea>
                <div class="form-hint">Her satıra bir özellik yazın.</div>
            </div>
        </div>
    </div>

    <!-- Pricing -->
    <div class="form-card">
        <div class="form-card-header">
            <i class="fas fa-tag"></i>
            <h3>Fiyat ve Miktar</h3>
        </div>
        <div class="form-card-body">
            <div class="form-row three">
                <div class="form-group">
                    <label class="form-label">Satış Fiyatı (<?php echo $siteCurrencySymbol; ?>)<span class="required">*</span></label>
                    <input type="number" name="price" id="packagePrice" class="form-control" step="0.01" min="0.01" value="<?php echo $formData['price']; ?>" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Eski Fiyat (<?php echo $siteCurrencySymbol; ?>)</label>
                    <input type="number" name="old_price" class="form-control" step="0.01" min="0" value="<?php echo $formData['old_price']; ?>">
                    <div class="form-hint">İndirim göstermek için</div>
                </div>
                <div class="form-group">
                    <label class="form-label">Miktar</label>
                    <input type="number" name="quantity" id="packageQuantity" class="form-control" min="1" value="<?php echo $formData['quantity']; ?>">
                    <div class="form-hint">Takipçi, beğeni vb. sayısı</div>
                </div>
            </div>
            
            <div class="form-group">
                <label class="form-label">Teslimat Süresi</label>
                <input type="text" name="delivery_time" class="form-control" value="<?php echo clean($formData['delivery_time']); ?>">
            </div>
        </div>
    </div>

    <!-- Custom Field -->
    <div class="form-card">
        <div class="form-card-header">
            <i class="fas fa-edit"></i>
            <h3>Sipariş Formu Ayarları</h3>
        </div>
        <div class="form-card-body">
            <div class="form-hint" style="margin-bottom: 20px;">
                <i class="fas fa-info-circle"></i>
                Müşterinin sipariş verirken dolduracağı alan ayarları.
            </div>
            
            <div class="form-group">
                <label class="form-label">Alan Başlığı</label>
                <input type="text" name="required_field_label" class="form-control" placeholder="Örn: Instagram Kullanıcı Adı" value="<?php echo clean($formData['required_field_label']); ?>">
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label class="form-label">Placeholder</label>
                    <input type="text" name="required_field_placeholder" class="form-control" placeholder="Örn: @kullaniciadi" value="<?php echo clean($formData['required_field_placeholder']); ?>">
                </div>
                <div class="form-group">
                    <label class="form-label">İpucu Metni</label>
                    <input type="text" name="required_field_hint" class="form-control" placeholder="Örn: Hesabınızın gizli olmadığından emin olun" value="<?php echo clean($formData['required_field_hint']); ?>">
                </div>
            </div>
        </div>
    </div>

    <!-- Options -->
    <div class="form-card">
        <div class="form-card-header">
            <i class="fas fa-sliders-h"></i>
            <h3>Seçenekler</h3>
        </div>
        <div class="form-card-body">
            <div class="form-row">
                <label class="form-check-custom">
                    <input type="checkbox" name="is_active" value="1" <?php echo $formData['is_active'] ? 'checked' : ''; ?>>
                    <div class="form-check-custom-label">
                        <span>Aktif</span>
                        <small>Paket sitede görüntülensin</small>
                    </div>
                </label>
                <label class="form-check-custom">
                    <input type="checkbox" name="is_featured" value="1" <?php echo $formData['is_featured'] ? 'checked' : ''; ?>>
                    <div class="form-check-custom-label">
                        <span>Öne Çıkan</span>
                        <small>Öne çıkan olarak işaretle</small>
                    </div>
                </label>
            </div>
            
            <div class="form-row" style="margin-top: 15px;">
                <label class="form-check-custom">
                    <input type="checkbox" name="is_popular" value="1" <?php echo $formData['is_popular'] ? 'checked' : ''; ?>>
                    <div class="form-check-custom-label">
                        <span>Popüler</span>
                        <small>Popüler rozeti göster</small>
                    </div>
                </label>
                <div class="form-group" style="margin: 0;">
                    <label class="form-label">Sıralama</label>
                    <input type="number" name="sort_order" class="form-control" value="<?php echo (int)$formData['sort_order']; ?>" min="0">
                </div>
            </div>
        </div>
    </div>

    <!-- Actions -->
    <div class="form-actions">
        <button type="submit" name="save_package" value="1" class="btn-primary-custom">
            <i class="fas fa-save"></i> Değişiklikleri Kaydet
        </button>
        <a href="<?php echo SITE_URL; ?>/admin/paketler.php" class="btn-secondary-custom">
            <i class="fas fa-times"></i> İptal
        </a>
        <button type="button" class="btn-danger-custom" onclick="deletePackage()">
            <i class="fas fa-trash"></i> Paketi Sil
        </button>
    </div>
</form>

<script>
const SITE_URL = '<?php echo SITE_URL; ?>';
const PACKAGE_ID = <?php echo $packageId; ?>;
const MULTIPLIER = <?php echo $selectedMultiplier; ?>;
const EXCHANGE_RATE = <?php echo $exchangeRate; ?>;

// Alt kategoriler verisi
const subcategoriesByParent = <?php echo json_encode($subcategoriesByParent, JSON_UNESCAPED_UNICODE); ?>;
const selectedSubcategoryId = '<?php echo $formData['subcategory_id']; ?>';

// Sayfa yüklendiğinde
document.addEventListener('DOMContentLoaded', function() {
    const packageType = document.getElementById('packageTypeInput').value;
    if (packageType === 'auto') {
        document.getElementById('apiSection').classList.add('show');
    }
    
    // Seçili kategori varsa alt kategorileri yükle
    const categorySelect = document.getElementById('categorySelect');
    if (categorySelect && categorySelect.value) {
        onCategoryChange(categorySelect.value);
    }
});

// Kategori değiştiğinde alt kategorileri göster
function onCategoryChange(categoryId) {
    const wrapper = document.getElementById('subcategoryWrapper');
    const subcategorySelect = document.getElementById('subcategorySelect');
    
    if (!wrapper || !subcategorySelect) return;
    
    // Alt kategorileri temizle
    subcategorySelect.innerHTML = '<option value="">-- Alt Kategori Seçin (Opsiyonel) --</option>';
    
    // Bu kategorinin alt kategorileri var mı?
    if (categoryId && subcategoriesByParent[categoryId] && subcategoriesByParent[categoryId].length > 0) {
        const subs = subcategoriesByParent[categoryId];
        
        subs.forEach(function(sub) {
            const option = document.createElement('option');
            option.value = sub.id;
            option.textContent = sub.name;
            if (sub.id == selectedSubcategoryId) {
                option.selected = true;
            }
            subcategorySelect.appendChild(option);
        });
        
        wrapper.classList.add('show');
    } else {
        wrapper.classList.remove('show');
    }
}

// Paket türü seçimi
function selectType(type) {
    document.querySelectorAll('.type-option').forEach(el => el.classList.remove('active'));
    document.querySelector('.type-option.' + type).classList.add('active');
    document.querySelector('.type-option.' + type + ' input').checked = true;
    document.getElementById('packageTypeInput').value = type;
    
    if (type === 'auto') {
        document.getElementById('apiSection').classList.add('show');
    } else {
        document.getElementById('apiSection').classList.remove('show');
    }
}

// Sağlayıcı değiştiğinde
function changeProvider(providerId) {
    if (providerId) {
        window.location.href = SITE_URL + '/admin/paket-duzenle.php?id=' + PACKAGE_ID + '&type=auto&provider=' + providerId;
    } else {
        window.location.href = SITE_URL + '/admin/paket-duzenle.php?id=' + PACKAGE_ID + '&type=auto';
    }
}

// Kategori değiştiğinde
function changeCategory(category) {
    const providerId = document.getElementById('apiProvider').value;
    if (providerId && category) {
        window.location.href = SITE_URL + '/admin/paket-duzenle.php?id=' + PACKAGE_ID + '&type=auto&provider=' + providerId + '&api_category=' + encodeURIComponent(category);
    } else if (providerId) {
        window.location.href = SITE_URL + '/admin/paket-duzenle.php?id=' + PACKAGE_ID + '&type=auto&provider=' + providerId;
    }
}

// Servis seçildiğinde
function selectService(serviceId) {
    const serviceSelect = document.getElementById('apiService');
    if (!serviceSelect || !serviceId) return;
    
    const selected = serviceSelect.options[serviceSelect.selectedIndex];
    const name = selected.dataset.name || '';
    const rate = parseFloat(selected.dataset.rate) || 0;
    const min = parseInt(selected.dataset.min) || 100;
    
    // Fiyat hesapla
    const convertedRate = rate * EXCHANGE_RATE;
    const rateWithMultiplier = convertedRate * MULTIPLIER;
    const calculatedPrice = (rateWithMultiplier / 1000) * min;
    
    // Alanları doldur
    document.getElementById('packageName').value = name;
    document.getElementById('packageQuantity').value = min;
    document.getElementById('packagePrice').value = calculatedPrice.toFixed(2);
    
    // Sayfa yenile
    const providerId = document.getElementById('apiProvider').value;
    const category = document.getElementById('apiCategory').value;
    window.location.href = SITE_URL + '/admin/paket-duzenle.php?id=' + PACKAGE_ID + '&type=auto&provider=' + providerId + '&api_category=' + encodeURIComponent(category) + '&service=' + serviceId;
}

// Paketi sil
function deletePackage() {
    Swal.fire({
        title: 'Paketi silmek istediğinize emin misiniz?',
        text: '"<?php echo addslashes($package['name']); ?>" paketi kalıcı olarak silinecek!',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#64748b',
        confirmButtonText: 'Evet, Sil!',
        cancelButtonText: 'İptal',
        background: '#1e293b',
        color: '#f8fafc'
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = SITE_URL + '/admin/paketler.php?sil=' + PACKAGE_ID;
        }
    });
}
</script>

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