<?php
/**
 * SMM Paket Satış Scripti - Paket Yönetimi
 * Alt Kategori Desteği ile
 * @version 1.1.0
 */

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

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

// Silme işlemi
if (isset($_GET['sil']) && is_numeric($_GET['sil'])) {
    try {
        $db->prepare("DELETE FROM packages WHERE id = ?")->execute([$_GET['sil']]);
        setFlash('success', 'Paket silindi.');
    } catch (PDOException $e) {
        setFlash('error', 'Silme hatası: ' . $e->getMessage());
    }
    redirect(SITE_URL . '/admin/paketler.php');
    exit;
}

// Durum deği��tirme
if (isset($_GET['durum']) && is_numeric($_GET['durum'])) {
    try {
        $stmt = $db->prepare("UPDATE packages SET is_active = NOT is_active WHERE id = ?");
        $stmt->execute([$_GET['durum']]);
        setFlash('success', 'Paket durumu güncellendi.');
    } catch (PDOException $e) {
        setFlash('error', 'Güncelleme 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);

// Filtreler
$categoryFilter = (int)($_GET['category'] ?? 0);
$subcategoryFilter = (int)($_GET['subcategory'] ?? 0);
$statusFilter = $_GET['status'] ?? '';
$typeFilter = $_GET['type'] ?? '';
$searchQuery = trim($_GET['q'] ?? '');

// Tüm kategorileri çek (parent bilgisiyle birlikte)
try {
    if ($hasParentSupport) {
        // Tüm kategorileri çek
        $allCategoriesQuery = $db->query("SELECT * FROM categories ORDER BY parent_id, sort_order, name");
        $allCategoriesRaw = $allCategoriesQuery->fetchAll(PDO::FETCH_ASSOC);
        
        // Kategorileri ID'ye göre indexle
        $categoriesById = [];
        foreach ($allCategoriesRaw as $cat) {
            $categoriesById[$cat['id']] = $cat;
        }
        
        // Ana kategoriler (filtre için)
        $mainCategories = array_filter($allCategoriesRaw, function($c) {
            return empty($c['parent_id']) || $c['parent_id'] == 0;
        });
        
        // Alt kategorileri parent'a göre grupla
        $subcategoriesByParent = [];
        foreach ($allCategoriesRaw as $cat) {
            if (!empty($cat['parent_id']) && $cat['parent_id'] > 0) {
                $subcategoriesByParent[$cat['parent_id']][] = $cat;
            }
        }
    } else {
        $allCategoriesRaw = $db->query("SELECT * FROM categories WHERE is_active = 1 ORDER BY sort_order")->fetchAll(PDO::FETCH_ASSOC);
        $categoriesById = [];
        foreach ($allCategoriesRaw as $cat) {
            $categoriesById[$cat['id']] = $cat;
        }
        $mainCategories = $allCategoriesRaw;
        $subcategoriesByParent = [];
    }
} catch (PDOException $e) {
    $allCategoriesRaw = [];
    $categoriesById = [];
    $mainCategories = [];
    $subcategoriesByParent = [];
}

// Paketleri çek
try {
    $where = "1=1";
    $params = [];
    
    // Alt kategori filtresi varsa onu kullan
    if ($subcategoryFilter > 0) {
        $where .= " AND p.category_id = ?";
        $params[] = $subcategoryFilter;
    } elseif ($categoryFilter > 0) {
        // Ana kategori filtresi - ana kategori ve alt kategorilerini de dahil et
        if ($hasParentSupport && isset($subcategoriesByParent[$categoryFilter])) {
            $catIds = [$categoryFilter];
            foreach ($subcategoriesByParent[$categoryFilter] as $sub) {
                $catIds[] = $sub['id'];
            }
            $placeholders = implode(',', array_fill(0, count($catIds), '?'));
            $where .= " AND p.category_id IN ($placeholders)";
            $params = array_merge($params, $catIds);
        } else {
            $where .= " AND p.category_id = ?";
            $params[] = $categoryFilter;
        }
    }
    
    if ($statusFilter !== '') {
        $where .= " AND p.is_active = ?";
        $params[] = $statusFilter === 'active' ? 1 : 0;
    }
    
    if ($typeFilter === 'manual') {
        $where .= " AND p.api_provider_id IS NULL";
    } elseif ($typeFilter === 'auto') {
        $where .= " AND p.api_provider_id IS NOT NULL";
    }
    
    if ($searchQuery) {
        $where .= " AND (p.name LIKE ? OR p.description LIKE ?)";
        $params[] = "%{$searchQuery}%";
        $params[] = "%{$searchQuery}%";
    }
    
    $sql = "
        SELECT p.*, c.name as category_name, c.icon as category_icon, c.color as category_color,
               " . ($hasParentSupport ? "c.parent_id as category_parent_id," : "") . "
               ap.name as api_provider_name
        FROM packages p
        LEFT JOIN categories c ON p.category_id = c.id
        LEFT JOIN api_providers ap ON p.api_provider_id = ap.id
        WHERE $where
        ORDER BY p.is_active DESC, p.is_featured DESC, c.sort_order ASC, p.sort_order ASC
    ";
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $packages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // İstatistikler
    $totalPackages = count($packages);
    $activePackages = count(array_filter($packages, fn($p) => $p['is_active']));
    $manualPackages = count(array_filter($packages, fn($p) => empty($p['api_provider_id'])));
    $autoPackages = count(array_filter($packages, fn($p) => !empty($p['api_provider_id'])));
    
} catch (PDOException $e) {
    $packages = [];
    $totalPackages = $activePackages = $manualPackages = $autoPackages = 0;
}

// Kategori yolunu oluştur (Ana Kategori → Alt Kategori)
function getCategoryPath($categoryId, $categoriesById, $hasParentSupport) {
    if (!isset($categoriesById[$categoryId])) {
        return ['name' => 'Kategorisiz', 'path' => 'Kategorisiz', 'icon' => 'fas fa-box', 'color' => '#6366f1'];
    }
    
    $category = $categoriesById[$categoryId];
    $path = $category['name'];
    $icon = $category['icon'] ?: 'fas fa-folder';
    $color = $category['color'] ?: '#6366f1';
    
    // Parent varsa yolu oluştur
    if ($hasParentSupport && !empty($category['parent_id']) && isset($categoriesById[$category['parent_id']])) {
        $parent = $categoriesById[$category['parent_id']];
        $path = $parent['name'] . ' → ' . $category['name'];
        // Parent'ın ikonunu ve rengini kullan (opsiyonel - alt kategorininki de kullanılabilir)
        $icon = $parent['icon'] ?: 'fas fa-folder';
        $color = $parent['color'] ?: '#6366f1';
    }
    
    return [
        'name' => $category['name'],
        'path' => $path,
        'icon' => $icon,
        'color' => $color,
        'is_subcategory' => $hasParentSupport && !empty($category['parent_id'])
    ];
}

$adminPageTitle = 'Paketler';
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-title {
    font-size: 18px;
    font-weight: 700;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 10px;
}

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

.header-actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

/* Stats */
.stats-row {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 15px;
    margin-bottom: 25px;
}

.stat-mini {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    padding: 18px;
    display: flex;
    align-items: center;
    gap: 15px;
}

.stat-mini-icon {
    width: 45px;
    height: 45px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
}

.stat-mini-info h4 {
    font-size: 22px;
    font-weight: 700;
    margin: 0 0 2px;
}

.stat-mini-info span {
    font-size: 12px;
    color: var(--text-secondary);
}

/* Filters */
.filters-card {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 14px;
    padding: 20px;
    margin-bottom: 20px;
}

.filters-row {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    align-items: flex-end;
}

.filter-group {
    flex: 1;
    min-width: 150px;
}

.filter-group label {
    display: block;
    font-size: 12px;
    color: var(--text-secondary);
    margin-bottom: 6px;
}

.filter-group.search {
    flex: 2;
}

/* Subcategory Filter */
.subcategory-filter {
    display: none;
}

.subcategory-filter.show {
    display: block;
}

/* Packages Grid */
.packages-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 20px;
}

.package-card {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 16px;
    overflow: hidden;
    transition: all 0.3s;
    position: relative;
}

.package-card:hover {
    border-color: rgba(var(--primary-rgb), 0.3);
    transform: translateY(-5px);
    box-shadow: 0 15px 40px rgba(0,0,0,0.2);
}

.package-card.inactive {
    opacity: 0.6;
}

.package-badges {
    position: absolute;
    top: 15px;
    right: 15px;
    display: flex;
    flex-direction: column;
    gap: 5px;
    z-index: 5;
}

.package-badge {
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 10px;
    font-weight: 600;
    text-transform: uppercase;
}

.badge-featured {
    background: var(--gradient);
    color: #fff;
}

.badge-popular {
    background: linear-gradient(135deg, #f59e0b, #d97706);
    color: #fff;
}

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

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

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

.package-header {
    padding: 20px;
    display: flex;
    align-items: flex-start;
    gap: 15px;
}

.package-icon {
    width: 55px;
    height: 55px;
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    color: #fff;
    flex-shrink: 0;
}

.package-info {
    flex: 1;
    min-width: 0;
}

.package-category {
    font-size: 11px;
    color: var(--text-secondary);
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 4px;
    display: flex;
    align-items: center;
    gap: 5px;
}

.package-category .category-path {
    display: flex;
    align-items: center;
    gap: 4px;
}

.package-category .category-arrow {
    color: var(--text-muted);
    font-size: 9px;
}

.package-category .subcategory-badge {
    background: rgba(139, 92, 246, 0.15);
    color: #8b5cf6;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 9px;
    margin-left: 5px;
}

.package-name {
    font-size: 16px;
    font-weight: 700;
    margin: 0 0 5px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.package-desc {
    font-size: 12px;
    color: var(--text-secondary);
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.package-body {
    padding: 0 20px 20px;
}

.package-details {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    margin-bottom: 15px;
}

.package-detail {
    background: var(--bg-hover);
    padding: 10px 12px;
    border-radius: 8px;
}

.package-detail-label {
    font-size: 10px;
    color: var(--text-secondary);
    text-transform: uppercase;
    margin-bottom: 3px;
}

.package-detail-value {
    font-size: 14px;
    font-weight: 600;
}

.package-detail-value.price {
    color: #10b981;
}

.package-api-info {
    background: rgba(139, 92, 246, 0.1);
    border: 1px solid rgba(139, 92, 246, 0.2);
    border-radius: 8px;
    padding: 10px 12px;
    margin-bottom: 15px;
    font-size: 11px;
    color: #8b5cf6;
    display: flex;
    align-items: center;
    gap: 8px;
}

.package-api-info i {
    font-size: 14px;
}

.package-stats {
    display: flex;
    gap: 15px;
    padding: 12px 0;
    border-top: 1px solid var(--border-color);
    margin-bottom: 15px;
}

.package-stat {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    color: var(--text-secondary);
}

.package-stat i {
    font-size: 11px;
}

.package-actions {
    display: flex;
    gap: 8px;
}

.package-actions .btn {
    flex: 1;
    padding: 10px;
    border-radius: 8px;
    font-size: 12px;
    font-weight: 600;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    border: none;
    cursor: pointer;
    transition: all 0.2s;
}

.btn-edit {
    background: rgba(59, 130, 246, 0.15);
    color: #3b82f6;
}

.btn-edit:hover {
    background: #3b82f6;
    color: #fff;
}

.btn-toggle {
    background: rgba(245, 158, 11, 0.15);
    color: #f59e0b;
}

.btn-toggle:hover {
    background: #f59e0b;
    color: #fff;
}

.btn-delete {
    background: rgba(239, 68, 68, 0.15);
    color: #ef4444;
}

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

/* Empty State */
.empty-state {
    text-align: center;
    padding: 80px 20px;
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 16px;
}

.empty-state i {
    font-size: 60px;
    color: var(--primary);
    opacity: 0.3;
    margin-bottom: 20px;
}

.empty-state h3 {
    font-size: 20px;
    margin-bottom: 10px;
}

.empty-state p {
    color: var(--text-secondary);
    margin-bottom: 25px;
}

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

@media (max-width: 576px) {
    .stats-row {
        grid-template-columns: 1fr;
    }
    
    .packages-grid {
        grid-template-columns: 1fr;
    }
    
    .filters-row {
        flex-direction: column;
    }
    
    .filter-group {
        width: 100%;
    }
    
    .header-actions {
        width: 100%;
    }
    
    .header-actions .btn-primary-custom {
        flex: 1;
    }
}
</style>

<div class="page-header">
    <h1 class="page-header-title">
        <i class="fas fa-box"></i>
        Paketler
    </h1>
    <div class="header-actions">
        <a href="<?php echo SITE_URL; ?>/admin/paket-ekle.php" class="btn-primary-custom">
            <i class="fas fa-plus"></i> Yeni Paket Ekle
        </a>
    </div>
</div>

<!-- Stats -->
<div class="stats-row">
    <div class="stat-mini">
        <div class="stat-mini-icon" style="background: rgba(59,130,246,0.15); color: #3b82f6;">
            <i class="fas fa-box"></i>
        </div>
        <div class="stat-mini-info">
            <h4><?php echo $totalPackages; ?></h4>
            <span>Toplam Paket</span>
        </div>
    </div>
    <div class="stat-mini">
        <div class="stat-mini-icon" style="background: rgba(16,185,129,0.15); color: #10b981;">
            <i class="fas fa-check-circle"></i>
        </div>
        <div class="stat-mini-info">
            <h4><?php echo $activePackages; ?></h4>
            <span>Aktif Paket</span>
        </div>
    </div>
    <div class="stat-mini">
        <div class="stat-mini-icon" style="background: rgba(245,158,11,0.15); color: #f59e0b;">
            <i class="fas fa-hand-paper"></i>
        </div>
        <div class="stat-mini-info">
            <h4><?php echo $manualPackages; ?></h4>
            <span>Manuel Paket</span>
        </div>
    </div>
    <div class="stat-mini">
        <div class="stat-mini-icon" style="background: rgba(139,92,246,0.15); color: #8b5cf6;">
            <i class="fas fa-robot"></i>
        </div>
        <div class="stat-mini-info">
            <h4><?php echo $autoPackages; ?></h4>
            <span>Otomatik Paket</span>
        </div>
    </div>
</div>

<!-- Filters -->
<div class="filters-card">
    <form method="GET" id="filterForm" class="filters-row">
        <div class="filter-group">
            <label>Kategori</label>
            <select name="category" id="categoryFilter" class="form-select" onchange="onCategoryFilterChange()">
                <option value="">Tüm Kategoriler</option>
                <?php foreach ($mainCategories as $cat): ?>
                    <option value="<?php echo $cat['id']; ?>" 
                            data-has-sub="<?php echo isset($subcategoriesByParent[$cat['id']]) ? '1' : '0'; ?>"
                            <?php echo $categoryFilter == $cat['id'] ? 'selected' : ''; ?>>
                        <?php echo clean($cat['name']); ?>
                        <?php if ($hasParentSupport && isset($subcategoriesByParent[$cat['id']])): ?>
                            (<?php echo count($subcategoriesByParent[$cat['id']]); ?> alt)
                        <?php endif; ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <?php if ($hasParentSupport && !empty($subcategoriesByParent)): ?>
        <div class="filter-group subcategory-filter <?php echo ($categoryFilter > 0 && isset($subcategoriesByParent[$categoryFilter])) ? 'show' : ''; ?>" id="subcategoryFilterGroup">
            <label>Alt Kategori</label>
            <select name="subcategory" id="subcategoryFilter" class="form-select" onchange="this.form.submit()">
                <option value="">Tüm Alt Kategoriler</option>
                <?php if ($categoryFilter > 0 && isset($subcategoriesByParent[$categoryFilter])): ?>
                    <?php foreach ($subcategoriesByParent[$categoryFilter] as $sub): ?>
                        <option value="<?php echo $sub['id']; ?>" <?php echo $subcategoryFilter == $sub['id'] ? 'selected' : ''; ?>>
                            <?php echo clean($sub['name']); ?>
                        </option>
                    <?php endforeach; ?>
                <?php endif; ?>
            </select>
        </div>
        <?php endif; ?>
        
        <div class="filter-group">
            <label>Durum</label>
            <select name="status" class="form-select" onchange="this.form.submit()">
                <option value="">Tümü</option>
                <option value="active" <?php echo $statusFilter === 'active' ? 'selected' : ''; ?>>Aktif</option>
                <option value="inactive" <?php echo $statusFilter === 'inactive' ? 'selected' : ''; ?>>Pasif</option>
            </select>
        </div>
        <div class="filter-group">
            <label>Tür</label>
            <select name="type" class="form-select" onchange="this.form.submit()">
                <option value="">Tümü</option>
                <option value="manual" <?php echo $typeFilter === 'manual' ? 'selected' : ''; ?>>Manuel</option>
                <option value="auto" <?php echo $typeFilter === 'auto' ? 'selected' : ''; ?>>Otomatik (API)</option>
            </select>
        </div>
        <div class="filter-group search">
            <label>Ara</label>
            <input type="text" name="q" class="form-control" placeholder="Paket adı ara..." value="<?php echo clean($searchQuery); ?>">
        </div>
        <div class="filter-group" style="flex: 0;">
            <label>&nbsp;</label>
            <button type="submit" class="btn-primary-custom" style="width: 100%; padding: 12px 20px;">
                <i class="fas fa-search"></i>
            </button>
        </div>
    </form>
</div>

<!-- Packages -->
<?php if (empty($packages)): ?>
    <div class="empty-state">
        <i class="fas fa-box-open"></i>
        <h3>Henüz paket eklenmemiş</h3>
        <p>Satışa başlamak için ilk paketinizi ekleyin.</p>
        <a href="<?php echo SITE_URL; ?>/admin/paket-ekle.php" class="btn-primary-custom">
            <i class="fas fa-plus me-2"></i> İlk Paketi Ekle
        </a>
    </div>
<?php else: ?>
    <div class="packages-grid">
        <?php foreach ($packages as $package): ?>
        <?php 
            // Kategori yolunu al
            $catInfo = getCategoryPath($package['category_id'], $categoriesById, $hasParentSupport);
        ?>
        <div class="package-card <?php echo !$package['is_active'] ? 'inactive' : ''; ?>">
            <div class="package-badges">
                <?php if ($package['is_featured']): ?>
                    <span class="package-badge badge-featured">Öne Çıkan</span>
                <?php endif; ?>
                <?php if ($package['is_popular']): ?>
                    <span class="package-badge badge-popular">Popüler</span>
                <?php endif; ?>
                <?php if ($package['api_provider_id']): ?>
                    <span class="package-badge badge-auto">Otomatik</span>
                <?php else: ?>
                    <span class="package-badge badge-manual">Manuel</span>
                <?php endif; ?>
                <?php if (!$package['is_active']): ?>
                    <span class="package-badge badge-inactive">Pasif</span>
                <?php endif; ?>
            </div>
            
            <div class="package-header">
                <div class="package-icon" style="background: <?php echo $catInfo['color']; ?>;">
                    <i class="<?php echo $catInfo['icon']; ?>"></i>
                </div>
                <div class="package-info">
                    <div class="package-category">
                        <?php echo clean($catInfo['path']); ?>
                        <?php if (!empty($catInfo['is_subcategory'])): ?>
                            <span class="subcategory-badge">Alt</span>
                        <?php endif; ?>
                    </div>
                    <h3 class="package-name"><?php echo clean($package['name']); ?></h3>
                    <p class="package-desc"><?php echo clean($package['description'] ?? ''); ?></p>
                </div>
            </div>
            
            <div class="package-body">
                <div class="package-details">
                    <div class="package-detail">
                        <div class="package-detail-label">Fiyat</div>
                        <div class="package-detail-value price"><?php echo formatMoney($package['price']); ?></div>
                    </div>
                    <div class="package-detail">
                        <div class="package-detail-label">Miktar</div>
                        <div class="package-detail-value"><?php echo number_format($package['quantity'] ?? 0); ?></div>
                    </div>
                    <?php if ($package['old_price']): ?>
                    <div class="package-detail">
                        <div class="package-detail-label">Eski Fiyat</div>
                        <div class="package-detail-value" style="text-decoration: line-through; color: var(--text-secondary);">
                            <?php echo formatMoney($package['old_price']); ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    <div class="package-detail">
                        <div class="package-detail-label">Teslimat</div>
                        <div class="package-detail-value"><?php echo clean($package['delivery_time'] ?? '-'); ?></div>
                    </div>
                </div>
                
                <?php if ($package['api_provider_id']): ?>
                <div class="package-api-info">
                    <i class="fas fa-plug"></i>
                    <span>
                        <strong><?php echo clean($package['api_provider_name']); ?></strong>
                        - Servis #<?php echo clean($package['api_service_id']); ?>
                    </span>
                </div>
                <?php endif; ?>
                
                <div class="package-stats">
                    <div class="package-stat">
                        <i class="fas fa-shopping-cart"></i>
                        <span><?php echo $package['total_sales'] ?? 0; ?> satış</span>
                    </div>
                    <div class="package-stat">
                        <i class="fas fa-sort"></i>
                        <span>Sıra: <?php echo $package['sort_order']; ?></span>
                    </div>
                </div>
                
                <div class="package-actions">
                    <a href="<?php echo SITE_URL; ?>/admin/paket-duzenle.php?id=<?php echo $package['id']; ?>" class="btn btn-edit">
                        <i class="fas fa-edit"></i> Düzenle
                    </a>
                    <a href="?durum=<?php echo $package['id']; ?>" class="btn btn-toggle">
                        <i class="fas fa-<?php echo $package['is_active'] ? 'eye-slash' : 'eye'; ?>"></i>
                        <?php echo $package['is_active'] ? 'Pasif' : 'Aktif'; ?>
                    </a>
                    <button class="btn btn-delete" onclick="deletePackage(<?php echo $package['id']; ?>, '<?php echo clean(addslashes($package['name'])); ?>')">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

<script>
// Alt kategoriler verisi
const subcategoriesByParent = <?php echo json_encode($subcategoriesByParent, JSON_UNESCAPED_UNICODE); ?>;

function onCategoryFilterChange() {
    const categorySelect = document.getElementById('categoryFilter');
    const subcategoryGroup = document.getElementById('subcategoryFilterGroup');
    const subcategorySelect = document.getElementById('subcategoryFilter');
    
    if (!subcategoryGroup || !subcategorySelect) {
        document.getElementById('filterForm').submit();
        return;
    }
    
    const categoryId = categorySelect.value;
    
    // Alt kategoriyi sıfırla
    subcategorySelect.innerHTML = '<option value="">Tüm Alt Kategoriler</option>';
    
    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;
            subcategorySelect.appendChild(option);
        });
        subcategoryGroup.classList.add('show');
    } else {
        subcategoryGroup.classList.remove('show');
    }
    
    // Formu gönder
    document.getElementById('filterForm').submit();
}

function deletePackage(id, name) {
    Swal.fire({
        title: 'Paketi silmek istediğinize emin misiniz?',
        text: `"${name}" paketi 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 = '?sil=' + id;
        }
    });
}
</script>

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