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

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

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

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

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

$demoMode = isDemoMode();

// Slug oluşturma
function createSlug($text) {
    $text = mb_strtolower($text, 'UTF-8');
    $tr = ['ş'=>'s','ğ'=>'g','ü'=>'u','ı'=>'i','ö'=>'o','ç'=>'c','Ş'=>'s','Ğ'=>'g','Ü'=>'u','İ'=>'i','Ö'=>'o','Ç'=>'c'];
    $text = strtr($text, $tr);
    $text = preg_replace('/[^a-z0-9\-]/', '-', $text);
    $text = preg_replace('/-+/', '-', $text);
    return trim($text, '-');
}

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

$hasParentSupport = hasParentColumn($db);

// POST İşlemleri
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($demoMode) {
        setFlash('error', '🔒 Demo modunda kategori işlemleri yapılamaz.');
        redirect(SITE_URL . '/admin/kategoriler.php');
        exit;
    }
    
    if (!hash_equals($csrfToken, $_POST['csrf_token'] ?? '')) {
        setFlash('error', 'Güvenlik hatası.');
        redirect(SITE_URL . '/admin/kategoriler.php');
        exit;
    }
    
    $action = $_POST['action'];
    
    try {
        switch ($action) {
            case 'add':
                $name = trim($_POST['name'] ?? '');
                $description = trim($_POST['description'] ?? '');
                $icon = trim($_POST['icon'] ?? 'fas fa-folder');
                $color = trim($_POST['color'] ?? '#6366f1');
                $sortOrder = (int)($_POST['sort_order'] ?? 0);
                $isActive = isset($_POST['is_active']) ? 1 : 0;
                $parentId = $hasParentSupport ? (int)($_POST['parent_id'] ?? 0) : 0;
                
                if (empty($name)) throw new Exception('Kategori adı zorunludur.');
                
                $slug = createSlug($name);
                
                if ($hasParentSupport && $parentId > 0) {
                    $ps = $db->prepare("SELECT slug FROM categories WHERE id = ?");
                    $ps->execute([$parentId]);
                    $parentSlug = $ps->fetchColumn();
                    if ($parentSlug) $slug = $parentSlug . '-' . $slug;
                }
                
                $cs = $db->prepare("SELECT id FROM categories WHERE slug = ?");
                $cs->execute([$slug]);
                if ($cs->fetch()) $slug = $slug . '-' . time();
                
                if ($sortOrder <= 0) {
                    $sortOrder = ($db->query("SELECT MAX(sort_order) FROM categories")->fetchColumn() ?? 0) + 1;
                }
                
                if (!preg_match('/^#[0-9A-Fa-f]{6}$/', $color)) $color = '#6366f1';
                
                if ($hasParentSupport) {
                    $pv = $parentId > 0 ? $parentId : null;
                    $stmt = $db->prepare("INSERT INTO categories (name, slug, description, icon, color, sort_order, is_active, parent_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
                    $stmt->execute([$name, $slug, $description, $icon, $color, $sortOrder, $isActive, $pv]);
                } else {
                    $stmt = $db->prepare("INSERT INTO categories (name, slug, description, icon, color, sort_order, is_active, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
                    $stmt->execute([$name, $slug, $description, $icon, $color, $sortOrder, $isActive]);
                }
                
                setFlash('success', ($hasParentSupport && $parentId > 0 ? 'Alt kategori' : 'Kategori') . ' eklendi.');
                break;
                
            case 'update':
                $catId = (int)($_POST['category_id'] ?? 0);
                $name = trim($_POST['name'] ?? '');
                $description = trim($_POST['description'] ?? '');
                $icon = trim($_POST['icon'] ?? 'fas fa-folder');
                $color = trim($_POST['color'] ?? '#6366f1');
                $sortOrder = (int)($_POST['sort_order'] ?? 0);
                $isActive = isset($_POST['is_active']) ? 1 : 0;
                $parentId = $hasParentSupport ? (int)($_POST['parent_id'] ?? 0) : 0;
                
                if ($catId <= 0) throw new Exception('Geçersiz kategori.');
                if (empty($name)) throw new Exception('Kategori adı zorunludur.');
                if ($parentId === $catId) throw new Exception('Kategori kendisinin alt kategorisi olamaz.');
                
                if ($hasParentSupport) {
                    $cc = $db->prepare("SELECT COUNT(*) FROM categories WHERE parent_id = ?");
                    $cc->execute([$catId]);
                    if ($cc->fetchColumn() > 0 && $parentId > 0) {
                        throw new Exception('Alt kategorileri olan kategori başka birinin alt kategorisi yapılamaz.');
                    }
                }
                
                if (!preg_match('/^#[0-9A-Fa-f]{6}$/', $color)) $color = '#6366f1';
                
                if ($hasParentSupport) {
                    $pv = $parentId > 0 ? $parentId : null;
                    $stmt = $db->prepare("UPDATE categories SET name=?, description=?, icon=?, color=?, sort_order=?, is_active=?, parent_id=? WHERE id=?");
                    $stmt->execute([$name, $description, $icon, $color, $sortOrder, $isActive, $pv, $catId]);
                } else {
                    $stmt = $db->prepare("UPDATE categories SET name=?, description=?, icon=?, color=?, sort_order=?, is_active=? WHERE id=?");
                    $stmt->execute([$name, $description, $icon, $color, $sortOrder, $isActive, $catId]);
                }
                
                setFlash('success', 'Kategori güncellendi.');
                break;
                
            case 'delete':
                $catId = (int)($_POST['category_id'] ?? 0);
                if ($catId <= 0) throw new Exception('Geçersiz kategori.');
                
                if ($hasParentSupport) {
                    $cc = $db->prepare("SELECT COUNT(*) FROM categories WHERE parent_id = ?");
                    $cc->execute([$catId]);
                    if ($cc->fetchColumn() > 0) throw new Exception('Alt kategorileri olan kategori silinemez.');
                }
                
                $cp = $db->prepare("SELECT COUNT(*) FROM packages WHERE category_id = ?");
                $cp->execute([$catId]);
                if ($cp->fetchColumn() > 0) throw new Exception('Paket içeren kategori silinemez.');
                
                $db->prepare("DELETE FROM categories WHERE id = ?")->execute([$catId]);
                setFlash('success', 'Kategori silindi.');
                break;
        }
    } catch (Exception $e) {
        setFlash('error', $e->getMessage());
    }
    
    redirect(SITE_URL . '/admin/kategoriler.php');
    exit;
}

// Kategorileri çek
try {
    if ($hasParentSupport) {
        $allCategories = $db->query("
            SELECT c.*, 
                   (SELECT COUNT(*) FROM packages WHERE category_id = c.id) as package_count,
                   (SELECT COUNT(*) FROM packages WHERE category_id = c.id AND is_active = 1) as active_package_count,
                   (SELECT COUNT(*) FROM categories c2 WHERE c2.parent_id = c.id) as subcategory_count
            FROM categories c 
            ORDER BY COALESCE(c.parent_id, 0), c.sort_order, c.id
        ")->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $allCategories = $db->query("
            SELECT c.*, 
                   (SELECT COUNT(*) FROM packages WHERE category_id = c.id) as package_count,
                   (SELECT COUNT(*) FROM packages WHERE category_id = c.id AND is_active = 1) as active_package_count,
                   0 as subcategory_count
            FROM categories c 
            ORDER BY c.sort_order, c.id
        ")->fetchAll(PDO::FETCH_ASSOC);
    }
    
    $categories = [];
    $subcategories = [];
    
    foreach ($allCategories as $cat) {
        $pid = isset($cat['parent_id']) ? (int)$cat['parent_id'] : 0;
        if ($pid == 0) {
            $cat['children'] = [];
            $categories[$cat['id']] = $cat;
        } else {
            $subcategories[] = $cat;
        }
    }
    
    foreach ($subcategories as $sub) {
        $pid = (int)$sub['parent_id'];
        if (isset($categories[$pid])) {
            $categories[$pid]['children'][] = $sub;
        }
    }
    
    $categories = array_values($categories);
} catch (PDOException $e) {
    $categories = [];
    $allCategories = [];
}

$mainCategories = [];
foreach ($allCategories as $c) {
    if (empty($c['parent_id']) || $c['parent_id'] == 0) {
        $mainCategories[] = $c;
    }
}

$stats = [
    'total' => count($allCategories),
    'main' => count($mainCategories),
    'sub' => count($allCategories) - count($mainCategories),
    'active' => count(array_filter($allCategories, fn($c) => $c['is_active'] == 1)),
    'packages' => array_sum(array_column($allCategories, 'package_count'))
];

$iconGroups = [
    'Sosyal Medya' => [
        ['icon' => 'fab fa-instagram', 'name' => 'Instagram', 'color' => '#E4405F'],
        ['icon' => 'fab fa-tiktok', 'name' => 'TikTok', 'color' => '#010101'],
        ['icon' => 'fab fa-youtube', 'name' => 'YouTube', 'color' => '#FF0000'],
        ['icon' => 'fab fa-twitter', 'name' => 'Twitter', 'color' => '#1DA1F2'],
        ['icon' => 'fab fa-facebook-f', 'name' => 'Facebook', 'color' => '#1877F2'],
        ['icon' => 'fab fa-telegram', 'name' => 'Telegram', 'color' => '#0088cc'],
        ['icon' => 'fab fa-whatsapp', 'name' => 'WhatsApp', 'color' => '#25D366'],
        ['icon' => 'fab fa-discord', 'name' => 'Discord', 'color' => '#5865F2'],
        ['icon' => 'fab fa-twitch', 'name' => 'Twitch', 'color' => '#9146FF'],
        ['icon' => 'fab fa-spotify', 'name' => 'Spotify', 'color' => '#1DB954'],
        ['icon' => 'fab fa-linkedin', 'name' => 'LinkedIn', 'color' => '#0A66C2'],
        ['icon' => 'fab fa-pinterest', 'name' => 'Pinterest', 'color' => '#E60023'],
    ],
    'Hizmetler' => [
        ['icon' => 'fas fa-user-plus', 'name' => 'Takipçi', 'color' => '#10b981'],
        ['icon' => 'fas fa-heart', 'name' => 'Beğeni', 'color' => '#ef4444'],
        ['icon' => 'fas fa-eye', 'name' => 'İzlenme', 'color' => '#8b5cf6'],
        ['icon' => 'fas fa-comment', 'name' => 'Yorum', 'color' => '#3b82f6'],
        ['icon' => 'fas fa-share', 'name' => 'Paylaşım', 'color' => '#06b6d4'],
        ['icon' => 'fas fa-thumbs-up', 'name' => 'Like', 'color' => '#3b82f6'],
        ['icon' => 'fas fa-play', 'name' => 'Oynatma', 'color' => '#ef4444'],
        ['icon' => 'fas fa-users', 'name' => 'Üye', 'color' => '#6366f1'],
        ['icon' => 'fas fa-star', 'name' => 'Yıldız', 'color' => '#eab308'],
        ['icon' => 'fas fa-crown', 'name' => 'Premium', 'color' => '#f59e0b'],
        ['icon' => 'fas fa-check-circle', 'name' => 'Onay', 'color' => '#10b981'],
        ['icon' => 'fas fa-retweet', 'name' => 'Retweet', 'color' => '#1DA1F2'],
    ],
    'Genel' => [
        ['icon' => 'fas fa-folder', 'name' => 'Klasör', 'color' => '#f59e0b'],
        ['icon' => 'fas fa-box', 'name' => 'Kutu', 'color' => '#8b5cf6'],
        ['icon' => 'fas fa-globe', 'name' => 'Dünya', 'color' => '#3b82f6'],
        ['icon' => 'fas fa-flag', 'name' => 'Bayrak', 'color' => '#ef4444'],
        ['icon' => 'fas fa-rocket', 'name' => 'Roket', 'color' => '#ef4444'],
        ['icon' => 'fas fa-bolt', 'name' => 'Şimşek', 'color' => '#eab308'],
        ['icon' => 'fas fa-fire', 'name' => 'Ateş', 'color' => '#f97316'],
        ['icon' => 'fas fa-gem', 'name' => 'Elmas', 'color' => '#8b5cf6'],
        ['icon' => 'fas fa-gift', 'name' => 'Hediye', 'color' => '#ec4899'],
        ['icon' => 'fas fa-trophy', 'name' => 'Kupa', 'color' => '#eab308'],
        ['icon' => 'fas fa-tags', 'name' => 'Etiket', 'color' => '#8b5cf6'],
        ['icon' => 'fas fa-layer-group', 'name' => 'Katman', 'color' => '#6366f1'],
    ],
];

$adminPageTitle = 'Kategori Yönetimi';
require_once __DIR__ . '/header.php';
?>

<style>
.demo-banner{background:linear-gradient(135deg,rgba(245,158,11,0.15),rgba(239,68,68,0.15));border:1px solid rgba(245,158,11,0.3);border-radius:12px;padding:15px 20px;margin-bottom:20px;display:flex;align-items:center;gap:12px}
.demo-banner i{font-size:24px;color:#f59e0b}
.demo-banner-text h4{margin:0 0 4px;font-size:14px;font-weight:600;color:#f59e0b}
.demo-banner-text p{margin:0;font-size:12px;color:var(--text-secondary)}
.page-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:25px;flex-wrap:wrap;gap:15px}
.page-header h2{font-size:18px;font-weight:700;margin:0;display:flex;align-items:center;gap:10px}
.page-header h2 i{color:var(--primary)}
.stats-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:15px;margin-bottom:25px}
.stat-card{background:var(--bg-card);border:1px solid var(--border-color);border-radius:14px;padding:18px;display:flex;align-items:center;gap:14px}
.stat-card .icon{width:46px;height:46px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:18px}
.stat-card .icon.primary{background:rgba(var(--primary-rgb),0.15);color:var(--primary)}
.stat-card .icon.success{background:rgba(16,185,129,0.15);color:#10b981}
.stat-card .icon.info{background:rgba(59,130,246,0.15);color:#3b82f6}
.stat-card .icon.warning{background:rgba(245,158,11,0.15);color:#f59e0b}
.stat-card .icon.purple{background:rgba(139,92,246,0.15);color:#8b5cf6}
.stat-card .info .value{font-size:24px;font-weight:800;line-height:1;margin-bottom:4px}
.stat-card .info .label{font-size:12px;color:var(--text-secondary)}
.category-list{display:flex;flex-direction:column;gap:16px}
.main-category-card{background:var(--bg-card);border:1px solid var(--border-color);border-radius:16px;overflow:hidden}
.main-category-card.inactive{opacity:0.6}
.main-category-header{padding:20px;display:flex;align-items:center;gap:15px;cursor:pointer;transition:background 0.2s}
.main-category-header:hover{background:var(--bg-hover)}
.category-icon{width:56px;height:56px;border-radius:14px;display:flex;align-items:center;justify-content:center;font-size:26px;flex-shrink:0}
.category-info{flex:1;min-width:0}
.category-name{font-size:17px;font-weight:700;margin:0 0 4px;display:flex;align-items:center;gap:10px}
.badge{font-size:10px;padding:3px 8px;border-radius:6px;font-weight:600}
.badge-main{background:rgba(var(--primary-rgb),0.15);color:var(--primary)}
.badge-sub{background:rgba(139,92,246,0.15);color:#8b5cf6}
.status-dot{width:8px;height:8px;border-radius:50%}
.status-dot.active{background:#10b981;box-shadow:0 0 8px rgba(16,185,129,0.5)}
.status-dot.inactive{background:#6b7280}
.category-meta{display:flex;align-items:center;gap:15px;font-size:13px;color:var(--text-secondary)}
.category-meta span{display:flex;align-items:center;gap:5px}
.category-actions-header{display:flex;align-items:center;gap:8px}
.expand-toggle{width:36px;height:36px;border-radius:10px;background:var(--bg-hover);border:none;color:var(--text-secondary);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all 0.3s}
.expand-toggle:hover{background:rgba(var(--primary-rgb),0.15);color:var(--primary)}
.expand-toggle i{transition:transform 0.3s}
.expand-toggle.open i{transform:rotate(180deg)}
.action-btn{width:36px;height:36px;border-radius:10px;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all 0.2s;font-size:14px}
.action-btn.edit{background:rgba(59,130,246,0.15);color:#3b82f6}
.action-btn.edit:hover{background:#3b82f6;color:#fff}
.action-btn.add-sub{background:rgba(16,185,129,0.15);color:#10b981}
.action-btn.add-sub:hover{background:#10b981;color:#fff}
.action-btn.delete{background:rgba(239,68,68,0.15);color:#ef4444}
.action-btn.delete:hover{background:#ef4444;color:#fff}
.subcategories-container{display:none;border-top:1px solid var(--border-color);background:var(--bg-dark)}
.subcategories-container.open{display:block}
.subcategory-list{padding:15px 20px 15px 90px}
.subcategory-item{display:flex;align-items:center;gap:12px;padding:14px 16px;background:var(--bg-card);border:1px solid var(--border-color);border-radius:12px;margin-bottom:10px;transition:all 0.2s}
.subcategory-item:last-child{margin-bottom:0}
.subcategory-item:hover{border-color:rgba(var(--primary-rgb),0.3);transform:translateX(5px)}
.subcategory-item.inactive{opacity:0.5}
.subcategory-icon{width:40px;height:40px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:18px}
.subcategory-info{flex:1;min-width:0}
.subcategory-name{font-size:14px;font-weight:600;margin:0 0 3px;display:flex;align-items:center;gap:8px}
.subcategory-meta{font-size:12px;color:var(--text-secondary)}
.subcategory-actions{display:flex;gap:6px}
.subcategory-actions .action-btn{width:32px;height:32px;font-size:12px}
.add-subcategory-btn{display:flex;align-items:center;justify-content:center;gap:8px;padding:12px;background:transparent;border:2px dashed var(--border-color);border-radius:12px;color:var(--text-secondary);font-size:13px;cursor:pointer;margin-top:10px;transition:all 0.2s}
.add-subcategory-btn:hover{border-color:var(--primary);color:var(--primary);background:rgba(var(--primary-rgb),0.05)}
.empty-state{text-align:center;padding:60px 20px;background:var(--bg-card);border:1px solid var(--border-color);border-radius:16px}
.empty-state i{font-size:60px;color:var(--text-muted);opacity:0.3;margin-bottom:20px}
.empty-state h4{font-size:18px;margin-bottom:10px}
.empty-state p{color:var(--text-secondary);margin-bottom:25px}
.modal-content{background:var(--bg-card);border:1px solid var(--border-color);border-radius:16px;color:var(--text-primary)}
.modal-header{border-bottom:1px solid var(--border-color);padding:20px 24px}
.modal-title{font-size:18px;font-weight:700;display:flex;align-items:center;gap:10px}
.modal-title i{color:var(--primary)}
.modal-body{padding:24px}
.modal-footer{border-top:1px solid var(--border-color);padding:16px 24px;gap:10px}
.form-group{margin-bottom:20px}
.form-label{display:block;font-size:13px;font-weight:600;margin-bottom:8px}
.form-label .required{color:#ef4444}
.form-control,.form-select{width:100%;padding:12px 16px;background:var(--bg-dark);border:1px solid var(--border-color);border-radius:10px;color:var(--text-primary);font-size:14px;transition:all 0.2s}
.form-control:focus{border-color:var(--primary);box-shadow:0 0 0 3px rgba(var(--primary-rgb),0.15);outline:none}
.form-control::placeholder{color:var(--text-muted)}
textarea.form-control{min-height:80px;resize:vertical}
.form-hint{font-size:12px;color:var(--text-secondary);margin-top:6px}
.form-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:20px}
.parent-select-box{display:flex;flex-direction:column;gap:8px;max-height:180px;overflow-y:auto;background:var(--bg-dark);border:1px solid var(--border-color);border-radius:10px;padding:10px}
.parent-option{display:flex;align-items:center;gap:10px;padding:10px 12px;border-radius:8px;cursor:pointer;border:2px solid transparent;transition:all 0.2s}
.parent-option:hover{background:var(--bg-hover)}
.parent-option.selected{background:rgba(var(--primary-rgb),0.1);border-color:var(--primary)}
.parent-option input{display:none}
.parent-option-icon{width:32px;height:32px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:14px}
.parent-option-info{flex:1}
.parent-option-info strong{display:block;font-size:13px}
.parent-option-info span{font-size:11px;color:var(--text-secondary)}
.parent-option-check{width:18px;height:18px;border:2px solid var(--border-color);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:9px;color:transparent}
.parent-option.selected .parent-option-check{background:var(--primary);border-color:var(--primary);color:#fff}
.icon-picker-box{background:var(--bg-dark);border:1px solid var(--border-color);border-radius:12px;overflow:hidden}
.icon-custom-input{display:flex;gap:10px;padding:12px;border-bottom:1px solid var(--border-color);background:var(--bg-hover)}
.icon-custom-input input{flex:1;padding:10px 14px;background:var(--bg-dark);border:1px solid var(--border-color);border-radius:8px;color:var(--text-primary);font-size:13px}
.icon-custom-input input:focus{border-color:var(--primary);outline:none}
.icon-preview-box{width:42px;height:42px;background:var(--bg-card);border:1px solid var(--border-color);border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:18px;color:var(--primary)}
.icon-tabs{display:flex;gap:5px;padding:10px 12px;border-bottom:1px solid var(--border-color);overflow-x:auto}
.icon-tab{padding:8px 14px;background:transparent;border:none;border-radius:8px;color:var(--text-secondary);font-size:12px;font-weight:500;cursor:pointer;white-space:nowrap}
.icon-tab:hover{background:var(--bg-hover);color:var(--text-primary)}
.icon-tab.active{background:rgba(var(--primary-rgb),0.15);color:var(--primary)}
.icon-grid{display:grid;grid-template-columns:repeat(6,1fr);gap:8px;max-height:180px;overflow-y:auto;padding:12px}
.icon-item{aspect-ratio:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:4px;padding:8px 4px;border-radius:10px;cursor:pointer;border:2px solid transparent}
.icon-item:hover{background:var(--bg-hover)}
.icon-item.selected{border-color:var(--primary);background:rgba(var(--primary-rgb),0.1)}
.icon-item i{font-size:20px}
.icon-item span{font-size:8px;color:var(--text-secondary);text-align:center}
.color-row{display:flex;gap:10px;align-items:center}
.color-picker{width:50px;height:44px;padding:0;border:2px solid var(--border-color);border-radius:10px;cursor:pointer;overflow:hidden}
.color-picker::-webkit-color-swatch-wrapper{padding:0}
.color-picker::-webkit-color-swatch{border:none;border-radius:8px}
.color-presets{display:flex;gap:6px;flex-wrap:wrap;margin-top:10px}
.color-preset{width:24px;height:24px;border-radius:50%;cursor:pointer;border:2px solid transparent;transition:transform 0.2s}
.color-preset:hover{transform:scale(1.15)}
.toggle-box{display:flex;align-items:center;gap:12px;padding:15px;background:var(--bg-hover);border-radius:12px;cursor:pointer}
.toggle-box input{width:20px;height:20px;accent-color:var(--primary);cursor:pointer}
.toggle-box label{cursor:pointer;flex:1}
.toggle-box label strong{display:block;font-size:14px;margin-bottom:2px}
.toggle-box label span{font-size:12px;color:var(--text-secondary)}
.preview-box{background:var(--bg-hover);border-radius:12px;padding:20px;margin-top:20px}
.preview-box h5{font-size:13px;color:var(--text-secondary);margin:0 0 15px;display:flex;align-items:center;gap:8px}
.preview-card{background:var(--bg-card);border:1px solid var(--border-color);border-radius:12px;padding:15px;display:flex;align-items:center;gap:12px}
.preview-icon{width:48px;height:48px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:22px}
.preview-info h4{font-size:15px;font-weight:600;margin:0 0 3px}
.preview-info span{font-size:12px;color:var(--text-secondary)}
@media(max-width:768px){.form-grid{grid-template-columns:1fr}.icon-grid{grid-template-columns:repeat(5,1fr)}.subcategory-list{padding-left:20px}.stats-row{grid-template-columns:repeat(2,1fr)}}
</style>
<?php if ($demoMode): ?>
<div class="demo-banner">
    <i class="fas fa-shield-alt"></i>
    <div class="demo-banner-text">
        <h4>Demo Modu Aktif</h4>
        <p>Demo modunda kategori işlemleri yapılamaz.</p>
    </div>
</div>
<?php endif; ?>

<div class="page-header">
    <h2><i class="fas fa-folder-tree"></i> Kategori Yönetimi</h2>
    <?php if ($demoMode): ?>
    <button class="btn-primary-custom" disabled style="opacity:0.5"><i class="fas fa-lock"></i> Demo Mod</button>
    <?php else: ?>
    <button class="btn-primary-custom" onclick="openAddModal(0)"><i class="fas fa-plus"></i> Yeni Kategori</button>
    <?php endif; ?>
</div>

<div class="stats-row">
    <div class="stat-card">
        <div class="icon primary"><i class="fas fa-folder"></i></div>
        <div class="info"><div class="value"><?php echo $stats['total']; ?></div><div class="label">Toplam</div></div>
    </div>
    <div class="stat-card">
        <div class="icon info"><i class="fas fa-folder-open"></i></div>
        <div class="info"><div class="value"><?php echo $stats['main']; ?></div><div class="label">Ana</div></div>
    </div>
    <?php if ($hasParentSupport): ?>
    <div class="stat-card">
        <div class="icon purple"><i class="fas fa-sitemap"></i></div>
        <div class="info"><div class="value"><?php echo $stats['sub']; ?></div><div class="label">Alt</div></div>
    </div>
    <?php endif; ?>
    <div class="stat-card">
        <div class="icon success"><i class="fas fa-check-circle"></i></div>
        <div class="info"><div class="value"><?php echo $stats['active']; ?></div><div class="label">Aktif</div></div>
    </div>
    <div class="stat-card">
        <div class="icon warning"><i class="fas fa-box"></i></div>
        <div class="info"><div class="value"><?php echo $stats['packages']; ?></div><div class="label">Paket</div></div>
    </div>
</div>

<div class="category-list">
    <?php if (empty($categories)): ?>
    <div class="empty-state">
        <i class="fas fa-folder-open"></i>
        <h4>Henüz kategori eklenmemiş</h4>
        <p>Paketlerinizi düzenlemek için kategori ekleyin</p>
        <?php if (!$demoMode): ?>
        <button class="btn-primary-custom" onclick="openAddModal(0)"><i class="fas fa-plus"></i> İlk Kategoriyi Ekle</button>
        <?php endif; ?>
    </div>
    <?php else: ?>
    
    <?php foreach ($categories as $cat): ?>
    <div class="main-category-card <?php echo $cat['is_active'] ? '' : 'inactive'; ?>" data-id="<?php echo $cat['id']; ?>">
        <div class="main-category-header">
            <div class="category-icon" style="background:<?php echo $cat['color']; ?>20;color:<?php echo $cat['color']; ?>">
                <i class="<?php echo $cat['icon'] ?: 'fas fa-folder'; ?>"></i>
            </div>
            <div class="category-info">
                <h3 class="category-name">
                    <?php echo htmlspecialchars($cat['name']); ?>
                    <span class="badge badge-main">Ana</span>
                    <span class="status-dot <?php echo $cat['is_active'] ? 'active' : 'inactive'; ?>"></span>
                </h3>
                <div class="category-meta">
                    <span><i class="fas fa-box"></i> <?php echo $cat['package_count']; ?> Paket</span>
                    <?php if ($hasParentSupport): ?>
                    <span><i class="fas fa-sitemap"></i> <?php echo $cat['subcategory_count']; ?> Alt</span>
                    <?php endif; ?>
                </div>
            </div>
            <div class="category-actions-header">
                <?php if (!$demoMode): ?>
                    <?php if ($hasParentSupport): ?>
                    <button class="action-btn add-sub" onclick="event.stopPropagation();openAddModal(<?php echo $cat['id']; ?>)" title="Alt Kategori Ekle"><i class="fas fa-plus"></i></button>
                    <?php endif; ?>
                    <button class="action-btn edit" onclick="event.stopPropagation();editCategory(<?php echo $cat['id']; ?>)" title="Düzenle"><i class="fas fa-edit"></i></button>
                    <?php if ($cat['package_count'] == 0 && $cat['subcategory_count'] == 0): ?>
                    <button class="action-btn delete" onclick="event.stopPropagation();deleteCategory(<?php echo $cat['id']; ?>,'<?php echo addslashes($cat['name']); ?>')" title="Sil"><i class="fas fa-trash"></i></button>
                    <?php endif; ?>
                <?php endif; ?>
                <?php if (!empty($cat['children'])): ?>
                <button class="expand-toggle" onclick="event.stopPropagation();toggleSub(<?php echo $cat['id']; ?>)" id="toggle-<?php echo $cat['id']; ?>"><i class="fas fa-chevron-down"></i></button>
                <?php endif; ?>
            </div>
        </div>
        
        <?php if (!empty($cat['children'])): ?>
        <div class="subcategories-container" id="sub-<?php echo $cat['id']; ?>">
            <div class="subcategory-list">
                <?php foreach ($cat['children'] as $sub): ?>
                <div class="subcategory-item <?php echo $sub['is_active'] ? '' : 'inactive'; ?>">
                    <div class="subcategory-icon" style="background:<?php echo $sub['color']; ?>20;color:<?php echo $sub['color']; ?>">
                        <i class="<?php echo $sub['icon'] ?: 'fas fa-folder'; ?>"></i>
                    </div>
                    <div class="subcategory-info">
                        <h4 class="subcategory-name">
                            <?php echo htmlspecialchars($sub['name']); ?>
                            <span class="status-dot <?php echo $sub['is_active'] ? 'active' : 'inactive'; ?>"></span>
                        </h4>
                        <div class="subcategory-meta"><i class="fas fa-box"></i> <?php echo $sub['package_count']; ?> Paket</div>
                    </div>
                    <?php if (!$demoMode): ?>
                    <div class="subcategory-actions">
                        <button class="action-btn edit" onclick="editCategory(<?php echo $sub['id']; ?>)" title="Düzenle"><i class="fas fa-edit"></i></button>
                        <?php if ($sub['package_count'] == 0): ?>
                        <button class="action-btn delete" onclick="deleteCategory(<?php echo $sub['id']; ?>,'<?php echo addslashes($sub['name']); ?>')" title="Sil"><i class="fas fa-trash"></i></button>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
                
                <?php if (!$demoMode): ?>
                <button class="add-subcategory-btn" onclick="openAddModal(<?php echo $cat['id']; ?>)"><i class="fas fa-plus"></i> Alt Kategori Ekle</button>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
    <?php endforeach; ?>
    
    <?php endif; ?>
</div>

<!-- Modal -->
<div class="modal fade" id="categoryModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST" id="categoryForm">
                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                <input type="hidden" name="action" id="formAction" value="add">
                <input type="hidden" name="category_id" id="formCatId" value="">
                <input type="hidden" name="icon" id="formIcon" value="fab fa-instagram">
                <input type="hidden" name="parent_id" id="formParentId" value="0">
                
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle"><i class="fas fa-plus-circle"></i> Yeni Kategori</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                
                <div class="modal-body">
                    <?php if ($hasParentSupport): ?>
                    <div class="form-group" id="parentGroup">
                        <label class="form-label">Üst Kategori</label>
                        <div class="parent-select-box">
                            <label class="parent-option selected" data-val="0" onclick="selectParent(0)">
                                <input type="radio" name="parent_radio" value="0" checked>
                                <div class="parent-option-icon" style="background:rgba(var(--primary-rgb),0.15);color:var(--primary)"><i class="fas fa-home"></i></div>
                                <div class="parent-option-info"><strong>Ana Kategori</strong><span>Bağımsız kategori</span></div>
                                <div class="parent-option-check"><i class="fas fa-check"></i></div>
                            </label>
                            <?php foreach ($mainCategories as $mc): ?>
                            <label class="parent-option" data-val="<?php echo $mc['id']; ?>" data-catid="<?php echo $mc['id']; ?>" onclick="selectParent(<?php echo $mc['id']; ?>)">
                                <input type="radio" name="parent_radio" value="<?php echo $mc['id']; ?>">
                                <div class="parent-option-icon" style="background:<?php echo $mc['color']; ?>20;color:<?php echo $mc['color']; ?>"><i class="<?php echo $mc['icon'] ?: 'fas fa-folder'; ?>"></i></div>
                                <div class="parent-option-info"><strong><?php echo htmlspecialchars($mc['name']); ?></strong><span><?php echo $mc['subcategory_count']; ?> alt kategori</span></div>
                                <div class="parent-option-check"><i class="fas fa-check"></i></div>
                            </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <div class="form-grid">
                        <div class="form-group">
                            <label class="form-label">Kategori Adı <span class="required">*</span></label>
                            <input type="text" name="name" id="formName" class="form-control" placeholder="Örn: Instagram Takipçi" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Sıralama</label>
                            <input type="number" name="sort_order" id="formSort" class="form-control" value="0" min="0">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Açıklama</label>
                        <textarea name="description" id="formDesc" class="form-control" rows="2" placeholder="Kategori açıklaması..."></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">İkon</label>
                        <div class="icon-picker-box">
                            <div class="icon-custom-input">
                                <input type="text" id="iconCustom" placeholder="Özel: fas fa-star" oninput="setCustomIcon(this.value)">
                                <div class="icon-preview-box" id="iconPreview"><i class="fab fa-instagram"></i></div>
                            </div>
                            <div class="icon-tabs">
                                <?php $first = true; foreach ($iconGroups as $gName => $gIcons): ?>
                                <button type="button" class="icon-tab <?php echo $first ? 'active' : ''; ?>" onclick="showIconGroup('<?php echo addslashes($gName); ?>')"><?php echo $gName; ?></button>
                                <?php $first = false; endforeach; ?>
                            </div>
                            <div class="icon-grid" id="iconGrid"></div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Renk</label>
                        <div class="color-row">
                            <input type="color" name="color" id="formColor" class="color-picker" value="#E4405F">
                            <input type="text" id="formColorText" class="form-control" value="#E4405F" maxlength="7" style="flex:1" oninput="syncColor(this.value)">
                        </div>
                        <div class="color-presets">
                            <?php foreach (['#E4405F','#000000','#FF0000','#1DA1F2','#1877F2','#0088cc','#25D366','#1DB954','#9146FF','#6366f1','#8b5cf6','#10b981','#f59e0b','#ef4444'] as $pc): ?>
                            <div class="color-preset" style="background:<?php echo $pc; ?>" onclick="setColor('<?php echo $pc; ?>')"></div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <div class="toggle-box">
                            <input type="checkbox" name="is_active" id="formActive" checked>
                            <label for="formActive"><strong>Aktif</strong><span>Kategori sitede görüntülensin</span></label>
                        </div>
                    </div>
                    
                    <div class="preview-box">
                        <h5><i class="fas fa-eye"></i> Önizleme</h5>
                        <div class="preview-card">
                            <div class="preview-icon" id="prevIcon" style="background:#E4405F20;color:#E4405F"><i class="fab fa-instagram"></i></div>
                            <div class="preview-info"><h4 id="prevName">Kategori Adı</h4><span id="prevDesc">Açıklama</span></div>
                        </div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn-secondary-custom" data-bs-dismiss="modal">İptal</button>
                    <button type="submit" class="btn-primary-custom" id="submitBtn"><i class="fas fa-plus"></i> Ekle</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
var csrfToken = '<?php echo $csrfToken; ?>';
var demoMode = <?php echo $demoMode ? 'true' : 'false'; ?>;
var hasParentSupport = <?php echo $hasParentSupport ? 'true' : 'false'; ?>;
var iconGroups = <?php echo json_encode($iconGroups, JSON_UNESCAPED_UNICODE); ?>;
var allCats = <?php echo json_encode($allCategories, JSON_UNESCAPED_UNICODE); ?>;
var currentIcon = 'fab fa-instagram';
var modal = null;

document.addEventListener('DOMContentLoaded', function() {
    modal = new bootstrap.Modal(document.getElementById('categoryModal'));
    showIconGroup('Sosyal Medya');
});

function toggleSub(id) {
    var container = document.getElementById('sub-' + id);
    var toggle = document.getElementById('toggle-' + id);
    if (!container) return;
    container.classList.toggle('open');
    if (toggle) toggle.classList.toggle('open');
}

function openAddModal(parentId) {
    if (demoMode) return;
    
    document.getElementById('formAction').value = 'add';
    document.getElementById('formCatId').value = '';
    document.getElementById('formName').value = '';
    document.getElementById('formDesc').value = '';
    document.getElementById('formSort').value = '0';
    document.getElementById('formActive').checked = true;
    document.getElementById('formColor').value = '#E4405F';
    document.getElementById('formColorText').value = '#E4405F';
    document.getElementById('iconCustom').value = '';
    
    selectIcon('fab fa-instagram');
    setColor('#E4405F');
    
    if (hasParentSupport) {
        document.getElementById('formParentId').value = parentId;
        selectParent(parentId);
        document.getElementById('parentGroup').style.display = 'block';
        document.querySelectorAll('.parent-option[data-catid]').forEach(function(opt) {
            opt.style.display = 'flex';
        });
    }
    
    document.getElementById('modalTitle').innerHTML = '<i class="fas fa-plus-circle"></i> ' + (parentId > 0 ? 'Alt Kategori Ekle' : 'Yeni Kategori');
    document.getElementById('submitBtn').innerHTML = '<i class="fas fa-plus"></i> Ekle';
    
    updatePreview();
    modal.show();
}

function editCategory(id) {
    if (demoMode) return;
    
    var cat = allCats.find(function(c) { return c.id == id; });
    if (!cat) return;
    
    document.getElementById('formAction').value = 'update';
    document.getElementById('formCatId').value = cat.id;
    document.getElementById('formName').value = cat.name;
    document.getElementById('formDesc').value = cat.description || '';
    document.getElementById('formSort').value = cat.sort_order;
    document.getElementById('formActive').checked = cat.is_active == 1;
    
    var color = cat.color || '#6366f1';
    document.getElementById('formColor').value = color;
    document.getElementById('formColorText').value = color.toUpperCase();
    
    var icon = cat.icon || 'fas fa-folder';
    document.getElementById('iconCustom').value = icon;
    selectIcon(icon);
    setColor(color);
    
    if (hasParentSupport) {
        var parentId = cat.parent_id || 0;
        document.getElementById('formParentId').value = parentId;
        selectParent(parentId);
        
        if (cat.subcategory_count > 0) {
            document.getElementById('parentGroup').style.display = 'none';
        } else {
            document.getElementById('parentGroup').style.display = 'block';
            document.querySelectorAll('.parent-option[data-catid]').forEach(function(opt) {
                opt.style.display = (opt.dataset.catid == cat.id) ? 'none' : 'flex';
            });
        }
    }
    
    document.getElementById('modalTitle').innerHTML = '<i class="fas fa-edit"></i> Kategori Düzenle';
    document.getElementById('submitBtn').innerHTML = '<i class="fas fa-save"></i> Kaydet';
    
    updatePreview();
    modal.show();
}

function selectParent(val) {
    document.getElementById('formParentId').value = val;
    document.querySelectorAll('.parent-option').forEach(function(opt) {
        opt.classList.toggle('selected', opt.dataset.val == val);
        if (opt.dataset.val == val) opt.querySelector('input').checked = true;
    });
}

function deleteCategory(id, name) {
    if (demoMode) return;
    
    Swal.fire({
        title: 'Kategoriyi Sil',
        html: '<strong>"' + name + '"</strong> silinecek.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#64748b',
        confirmButtonText: 'Sil',
        cancelButtonText: 'İptal',
        background: '#1e293b',
        color: '#f8fafc'
    }).then(function(result) {
        if (result.isConfirmed) {
            var form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = '<input type="hidden" name="csrf_token" value="' + csrfToken + '"><input type="hidden" name="action" value="delete"><input type="hidden" name="category_id" value="' + id + '">';
            document.body.appendChild(form);
            form.submit();
        }
    });
}

function showIconGroup(groupName) {
    document.querySelectorAll('.icon-tab').forEach(function(tab) {
        tab.classList.toggle('active', tab.textContent.trim() === groupName);
    });
    
    var icons = iconGroups[groupName] || [];
    var html = '';
    icons.forEach(function(ico) {
        var sel = (ico.icon === currentIcon) ? 'selected' : '';
        html += '<div class="icon-item ' + sel + '" onclick="selectIcon(\'' + ico.icon + '\')">';
        html += '<i class="' + ico.icon + '" style="color:' + ico.color + '"></i>';
        html += '<span>' + ico.name + '</span></div>';
    });
    document.getElementById('iconGrid').innerHTML = html;
}

function selectIcon(icon) {
    currentIcon = icon;
    document.getElementById('formIcon').value = icon;
    document.getElementById('iconPreview').innerHTML = '<i class="' + icon + '"></i>';
    document.getElementById('iconCustom').value = icon;
    
    document.querySelectorAll('.icon-item').forEach(function(item) {
        var itemIcon = item.querySelector('i');
        item.classList.toggle('selected', itemIcon && itemIcon.className === icon);
    });
    
    updatePreview();
}

function setCustomIcon(val) {
    if (val.trim()) selectIcon(val.trim());
}

function setColor(color) {
    document.getElementById('formColor').value = color;
    document.getElementById('formColorText').value = color.toUpperCase();
    updatePreview();
}

function syncColor(val) {
    if (val.charAt(0) !== '#') val = '#' + val;
    if (/^#[0-9A-Fa-f]{6}$/.test(val)) {
        document.getElementById('formColor').value = val;
        updatePreview();
    }
}

document.getElementById('formColor').addEventListener('input', function() {
    document.getElementById('formColorText').value = this.value.toUpperCase();
    updatePreview();
});

document.getElementById('formName').addEventListener('input', updatePreview);
document.getElementById('formDesc').addEventListener('input', updatePreview);

function updatePreview() {
    var name = document.getElementById('formName').value || 'Kategori Adı';
    var desc = document.getElementById('formDesc').value || 'Açıklama';
    var color = document.getElementById('formColor').value;
    
    document.getElementById('prevName').textContent = name;
    document.getElementById('prevDesc').textContent = desc;
    
    var prevIcon = document.getElementById('prevIcon');
    prevIcon.style.background = color + '20';
    prevIcon.style.color = color;
    prevIcon.innerHTML = '<i class="' + currentIcon + '"></i>';
}
</script>

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