<?php
// DOSYA: katalog.php
// SÜRÜM: FİDE BAHÇESİ V-PREMIUM MAX (SONSUZ KAYDIRMA, MİNİMAL KATEGORİ, HESABIM SPA, KULLANICI PROFİLİ)

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

function fatalErrorHandler() {
    $error = error_get_last();
    if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        echo '<div style="background:#fee2e2;border:3px solid #ef4444;color:#991b1b;padding:20px;margin:20px;border-radius:12px;font-family:monospace;z-index:999999;">';
        echo '<h3 style="margin:0 0 10px;">💥 PHP HATASI</h3>';
        echo '<b>Dosya:</b> ' . htmlspecialchars($error['file']) . '<br>';
        echo '<b>Satır:</b> ' . $error['line'] . '<br>';
        echo '<b>Hata:</b> ' . htmlspecialchars($error['message']) . '<br>';
        echo '</div>';
    }
}
register_shutdown_function('fatalErrorHandler');

try {

if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once 'includes/db.php';
if (!isset($db) && isset($conn)) { $db = $conn; }

// ═══ KULLANICI BİLGİLERİ (GELİŞTİRİLDİ) ═══
$is_logged_in = isset($_SESSION['user_id']) || isset($_SESSION['customer_id']);
$user_name = '';
$user_phone = '';
$initials = 'Mİ'; // Varsayılan Misafir baş harfi

if ($is_logged_in) {
    try {
        $uid = $_SESSION['user_id'] ?? $_SESSION['customer_id'];
        $u_stmt = $db->prepare("SELECT name, phone FROM users WHERE id = ? LIMIT 1");
        $u_stmt->execute([$uid]);
        $u_row = $u_stmt->fetch(PDO::FETCH_ASSOC);
        if ($u_row) { 
            $user_name = trim($u_row['name']); 
            $user_phone = $u_row['phone'] ?? '';
            
            // İsimden baş harfleri çıkarma (Örn: Mustafa Gürocak -> MG)
            $name_parts = explode(' ', $user_name);
            $first_letter = mb_substr($name_parts[0], 0, 1, 'UTF-8');
            $last_letter = count($name_parts) > 1 ? mb_substr(end($name_parts), 0, 1, 'UTF-8') : '';
            $initials = mb_strtoupper($first_letter . $last_letter, 'UTF-8');
        }
    } catch(Exception $e) {}
}

// ═══ KATEGORİLER ═══
$categories = [];
try {
    $categories = $db->query("SELECT * FROM categories WHERE status = 1 ORDER BY sort_order ASC, name ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {}

// ═══ ÜRÜNLER ═══
$products = [];
try {
    $products = $db->query("
        SELECT p.id, p.name, p.slug, p.main_image, p.price, p.discount_price, p.short_description, p.category_id, p.stock,
        (SELECT AVG(rating) FROM product_reviews WHERE product_id = p.id AND status = 1) AS rating
        FROM products p 
        WHERE p.status = 1 
        ORDER BY p.id DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {}

// ═══ MAKALELER (BLOG) ═══
$articles = [];
try {
    $articles = $db->query("SELECT * FROM origami_blogs WHERE status = 1 ORDER BY id DESC LIMIT 20")->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) { 
    try { $articles = $db->query("SELECT * FROM articles WHERE status = 1 ORDER BY created_at DESC LIMIT 20")->fetchAll(PDO::FETCH_ASSOC); } catch(Exception $e2) {}
}

// ═══ YENİ ÜRÜNLER (Sağ sidebar için son 4 ürün) ═══
$new_products = array_slice($products, 0, 4);

// ═══ SEPET VERİLERİ (KESİN ÇÖZÜM) ═══
$cart_items = [];
$cart_count = 0;
$cart_total = 0;

if (!empty($_SESSION['cart']) && is_array($_SESSION['cart'])) {
    $cart_ids = [];
    $cart_quantities = [];
    
    foreach ($_SESSION['cart'] as $key => $item) {
        $pid = 0;
        if (is_array($item) && isset($item['product_id'])) { $pid = (int)$item['product_id']; } 
        elseif (is_array($item) && isset($item['id'])) { $pid = (int)$item['id']; } 
        elseif (is_numeric($key)) { $pid = (int)$key; }

        $qty = 1;
        if (is_array($item) && isset($item['quantity'])) { $qty = (int)$item['quantity']; } 
        elseif (is_array($item) && isset($item['qty'])) { $qty = (int)$item['qty']; } 
        elseif (is_numeric($item)) { $qty = (int)$item; }

        if ($pid > 0 && $qty > 0) {
            $cart_ids[] = $pid;
            $cart_quantities[$pid] = $qty;
        }
    }
    
    if (!empty($cart_ids)) {
        $placeholders = implode(',', array_fill(0, count($cart_ids), '?'));
        try {
            $stmt = $db->prepare("SELECT id, name, main_image, price, discount_price FROM products WHERE id IN ($placeholders)");
            $stmt->execute($cart_ids);
            $db_cart_products = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            foreach ($db_cart_products as $cp) {
                $pid = $cp['id'];
                $qty = $cart_quantities[$pid] ?? 1;
                $price = ($cp['discount_price'] > 0 && $cp['discount_price'] < $cp['price']) ? $cp['discount_price'] : $cp['price'];
                
                $cart_count += $qty;
                $cart_total += ($price * $qty);
                
                $cart_items[] = [
                    'id' => $pid,
                    'name' => $cp['name'],
                    'price' => $price,
                    'quantity' => $qty,
                    'image' => $cp['main_image']
                ];
            }
        } catch(Exception $e) {}
    }
}

function fixAppImg($path) {
    if(empty($path)) return '/assets/images/no-image.jpg';
    if(strpos($path, 'http') === 0) return $path;
    return '/' . ltrim($path, '/');
}

require_once 'includes/header.php';

} catch(Exception $e) {
    echo '<div style="background:#fee2e2;border:3px solid #ef4444;color:#991b1b;padding:20px;margin:20px;border-radius:12px;font-family:monospace;">';
    echo '<h3>💥 SİSTEM HATASI</h3>';
    echo htmlspecialchars($e->getMessage());
    echo '</div>';
    die();
}
?>

<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
    :root {
        --bg-app: #f4f7fc;
        --bg-panel: #ffffff;
        --text-dark: #1e293b;
        --text-muted: #64748b;
        --primary: #10b981;
        --primary-light: #d1fae5;
        --primary-dark: #059669;
        --accent: #f59e0b;
        --accent-purple: #8b5cf6;
        --danger: #ef4444;
        --radius-lg: 24px;
        --radius-md: 16px;
        --radius-sm: 12px;
        --shadow-soft: 0 4px 20px rgba(0,0,0,0.03);
        --shadow-card: 0 4px 15px rgba(0,0,0,0.04);
    }

    * { box-sizing: border-box; }

    body {
        background-color: var(--bg-app);
        font-family: 'Outfit', sans-serif;
        color: var(--text-dark);
        margin: 0;
        padding-bottom: 80px;
        -webkit-tap-highlight-color: transparent;
        zoom: 0.95; 
    }

    /* SweetAlert Z-Index Kesin Çözüm */
    .swal2-container { z-index: 999999999 !important; }

    /* ─── ANA LAYOUT ─── */
    .app-container {
        display: flex;
        max-width: 1550px;
        margin: 30px auto;
        gap: 30px;
        padding: 0 20px;
        align-items: flex-start;
    }

    /* ─── SOL SIDEBAR ─── */
    .app-sidebar {
        width: 240px;
        background: var(--bg-panel);
        border-radius: var(--radius-lg);
        padding: 25px 15px;
        box-shadow: var(--shadow-soft);
        display: flex;
        flex-direction: column;
        gap: 8px;
        position: sticky;
        top: 100px;
        flex-shrink: 0;
    }

    /* KULLANICI PROFİL KARTI (YENİ TASARIM) */
    .user-profile-card {
        text-align: center;
        padding-bottom: 20px;
        margin-bottom: 10px;
        border-bottom: 1px solid #f1f5f9;
    }
    .user-avatar-circle {
        width: 60px; height: 60px; border-radius: 50%;
        background: var(--primary); color: white;
        display: flex; align-items: center; justify-content: center;
        font-size: 1.5rem; font-weight: 800; margin: 0 auto 10px;
        box-shadow: 0 5px 15px rgba(16,185,129,0.3);
    }
    .user-profile-card h4 { font-size: 1rem; font-weight: 800; margin: 0 0 2px; color: var(--text-dark);}
    .user-profile-card span { font-size: 0.75rem; color: var(--text-muted); font-weight: 600; display: block;}
    .welcome-text-small { font-size: 0.7rem; color: var(--primary); font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px; display: block;}

    .sidebar-nav { display: flex; flex-direction: column; gap: 4px; }
    .nav-item {
        display: flex; align-items: center; gap: 12px;
        padding: 12px 15px; border-radius: var(--radius-sm);
        font-weight: 700; font-size: 0.9rem;
        color: var(--text-muted); text-decoration: none;
        transition: all 0.25s ease; cursor: pointer;
        border: none; background: none; width: 100%; text-align: left;
        font-family: 'Outfit', sans-serif;
    }
    .nav-item i { font-size: 1.1rem; width: 22px; text-align: center; }
    .nav-item:hover { background: #f8fafc; color: var(--text-dark); }
    .nav-item.active {
        background: var(--primary);
        color: white;
        box-shadow: 0 4px 15px rgba(16,185,129,0.3);
    }
    .nav-item .badge-count {
        margin-left: auto; background: var(--danger); color: white;
        font-size: 0.7rem; padding: 2px 8px; border-radius: 12px; font-weight: 800;
    }

    .sidebar-promo {
        margin-top: 20px;
        background: linear-gradient(135deg, #eff6ff, #dbeafe);
        padding: 15px; border-radius: var(--radius-md);
        text-align: center;
    }
    .sidebar-promo i { font-size: 1.8rem; color: #3b82f6; margin-bottom: 8px; }
    .sidebar-promo h5 { font-size: 0.9rem; font-weight: 800; margin: 0 0 4px; color: #1e3a8a; }
    .sidebar-promo p { font-size: 0.75rem; color: #3b82f6; margin: 0; font-weight: 600; }

    /* ─── ORTA ANA ALAN ─── */
    .app-main { 
        flex: 1; 
        min-width: 0; 
        background: var(--bg-panel);
        border-radius: var(--radius-lg);
        padding: 30px;
        box-shadow: var(--shadow-soft);
    }

    .main-header {
        display: flex; justify-content: space-between; align-items: center;
        margin-bottom: 30px; flex-wrap: wrap; gap: 15px;
    }
    .main-header h1 {
        font-size: 2rem; font-weight: 900; margin: 0;
        color: var(--text-dark);
        display: flex; align-items: center; gap: 10px;
        letter-spacing: -0.5px;
    }
    .search-box { position: relative; width: 100%; max-width: 400px; }
    .search-box input {
        width: 100%; background: #f8fafc; border: 2px solid transparent;
        padding: 14px 20px 14px 45px; border-radius: var(--radius-md);
        font-family: 'Outfit'; font-weight: 500; font-size: 0.95rem;
        color: var(--text-dark); outline: none; transition: 0.3s;
    }
    .search-box input:focus { background: white; border-color: var(--primary-light); box-shadow: 0 4px 15px rgba(16,185,129,0.1); }
    .search-box i {
        position: absolute; left: 16px; top: 50%; transform: translateY(-50%);
        color: var(--text-muted); font-size: 1.1rem;
    }

    /* ─── SEKMELER (SPA İÇERİĞİ) ─── */
    .spa-section { display: none; }
    .spa-section.active { display: block; animation: fadeIn 0.4s ease; }
    @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }

    /* ─── KATEGORİ GRİD (MİNİMAL, KARE, SIĞAN TASARIM DÜZELTİLDİ) ─── */
    .cat-grid {
        display: flex;
        flex-wrap: wrap; /* Sağa uzamayıp alta geçmesini sağlar */
        gap: 12px;
        margin-bottom: 30px;
        justify-content: flex-start;
    }

    .cat-square {
        display: flex; flex-direction: column; align-items: center; justify-content: center;
        width: 85px; height: 85px; border-radius: 18px; gap: 6px;
        background: #f8fafc; border: 1px solid #e2e8f0;
        cursor: pointer; transition: 0.3s; text-align: center;
        text-decoration: none; color: var(--text-dark);
        box-shadow: 0 2px 8px rgba(0,0,0,0.02);
    }
    .cat-square i { font-size: 1.5rem; color: var(--text-muted); transition: 0.3s; }
    .cat-square span { 
        font-size: 0.72rem; font-weight: 700; line-height: 1.15; padding: 0 4px;
        display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;
    }
    
    .cat-square:hover { background: white; transform: translateY(-3px); box-shadow: 0 6px 15px rgba(0,0,0,0.05); border-color: #cbd5e1; }
    .cat-square:hover i { color: var(--primary); }
    
    .cat-square.active {
        background: var(--primary-light); color: var(--text-dark); border-color: var(--primary);
        box-shadow: 0 4px 12px rgba(16,185,129,0.15);
    }
    .cat-square.active i { color: var(--primary); }

    /* ─── ÜRÜN TOOLBAR ─── */
    .prod-toolbar {
        display: flex; justify-content: space-between; align-items: center;
        margin-bottom: 20px; flex-wrap: wrap; gap: 10px;
        border-bottom: 2px solid #f1f5f9; padding-bottom: 15px;
    }
    .prod-toolbar h2 {
        font-size: 1.3rem; font-weight: 800; margin: 0;
        display: flex; align-items: center; gap: 8px; color: var(--text-dark);
    }
    .toolbar-right { display: flex; align-items: center; gap: 8px; }
    .view-toggle {
        width: 36px; height: 36px; border-radius: 10px;
        border: none; background: #f1f5f9; color: var(--text-muted);
        font-size: 1rem; display: flex; align-items: center;
        justify-content: center; cursor: pointer; transition: 0.2s;
    }
    .view-toggle:hover, .view-toggle.active { background: var(--text-dark); color: white; }
    .limit-sel {
        background: #f1f5f9; border: none; padding: 8px 12px;
        border-radius: 10px; font-family: 'Outfit'; font-weight: 700;
        font-size: 0.85rem; color: var(--text-dark); outline: none; cursor: pointer;
    }

    /* ─── ÜRÜN GRID ─── */
    .products-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
        gap: 20px;
    }
    .products-grid .p-card {
        background: #f8fafc; border-radius: var(--radius-md);
        padding: 20px; display: flex; flex-direction: column;
        position: relative; transition: 0.3s;
        border: 1px solid transparent;
        text-decoration: none; color: var(--text-dark);
        margin-top: 45px;
    }
    .products-grid .p-card:hover {
        background: white; border-color: #e2e8f0; box-shadow: 0 15px 35px rgba(0,0,0,0.06); transform: translateY(-5px);
    }
    .products-grid .p-img-wrap {
        width: 120px; height: 120px; margin: -55px auto 15px;
        border-radius: 50%; background: white;
        box-shadow: 0 10px 20px rgba(0,0,0,0.08);
        overflow: hidden; display: flex; align-items: center;
        justify-content: center; border: 4px solid white;
    }
    .products-grid .p-img-wrap img { width: 100%; height: 100%; object-fit: cover; }
    .products-grid .p-name {
        font-size: 1rem; font-weight: 800; text-align: center;
        margin-bottom: 6px; line-height: 1.25;
        display: -webkit-box; -webkit-line-clamp: 2;
        -webkit-box-orient: vertical; overflow: hidden;
    }
    .products-grid .p-desc {
        font-size: 0.8rem; color: var(--text-muted); text-align: center;
        margin-bottom: 15px; line-height: 1.4;
        display: -webkit-box; -webkit-line-clamp: 2;
        -webkit-box-orient: vertical; overflow: hidden;
    }
    .products-grid .p-foot {
        display: flex; justify-content: space-between; align-items: center;
        margin-top: auto;
    }
    .products-grid .p-price { font-size: 1.3rem; font-weight: 900; }
    .btn-cart-add {
        width: 42px; height: 42px; border-radius: 50%;
        background: var(--text-dark); color: white; border: none;
        font-size: 1.1rem; display: flex; align-items: center;
        justify-content: center; cursor: pointer; transition: 0.3s;
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }
    .btn-cart-add:hover { background: var(--primary); transform: scale(1.1) rotate(90deg); box-shadow: 0 6px 15px rgba(16,185,129,0.3);}

    /* ─── ÜRÜN LİSTE ─── */
    .products-list { display: flex; flex-direction: column; gap: 15px; }
    .products-list .p-card {
        background: #f8fafc; border-radius: var(--radius-md);
        padding: 15px; display: flex; align-items: center; gap: 18px;
        transition: 0.3s; border: 1px solid transparent;
        text-decoration: none; color: var(--text-dark);
        margin-top: 0;
    }
    .products-list .p-card:hover { background: white; border-color: #e2e8f0; box-shadow: 0 10px 25px rgba(0,0,0,0.05); transform: translateX(5px); }
    .products-list .p-img-wrap {
        width: 85px; height: 85px; border-radius: 16px; background: white; overflow: hidden; flex-shrink: 0; box-shadow: 0 4px 12px rgba(0,0,0,0.05); margin: 0; border: none;
    }
    .products-list .p-img-wrap img { width: 100%; height: 100%; object-fit: cover; }
    .products-list .p-info { flex: 1; min-width: 0; }
    .products-list .p-name { font-size: 1rem; font-weight: 800; text-align: left; margin-bottom: 4px; display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; overflow: hidden; }
    .products-list .p-desc { font-size: 0.8rem; color: var(--text-muted); text-align: left; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; margin-bottom:0;}
    .products-list .p-foot { display: flex; align-items: center; gap: 15px; flex-shrink: 0; margin-top:0;}
    .products-list .p-price { font-size: 1.3rem; font-weight: 900; min-width: 80px; text-align: right; }

    /* ─── BLOG (MAKALELER) BÖLÜMÜ ─── */
    .blog-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
        gap: 20px;
    }
    .blog-card {
        background: #f8fafc; border-radius: var(--radius-md);
        overflow: hidden; transition: 0.3s;
        border: 1px solid transparent; text-decoration: none; color: var(--text-dark);
        display: flex; flex-direction: column; box-shadow: var(--shadow-card);
    }
    .blog-card:hover { border-color: #e2e8f0; box-shadow: 0 12px 30px rgba(0,0,0,0.08); transform: translateY(-4px); }
    .blog-card-img { width: 100%; height: 160px; object-fit: cover; }
    .blog-card-body { padding: 20px; flex: 1; display: flex; flex-direction: column; }
    .blog-card-body h3 { font-size: 1.05rem; font-weight: 800; margin: 0 0 10px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; line-height:1.3;}
    .blog-card-body p { font-size: 0.85rem; color: var(--text-muted); line-height: 1.5; margin: 0 0 15px; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; flex: 1; }
    .blog-card-date { font-size: 0.75rem; color: var(--text-muted); font-weight: 600; display: flex; align-items: center; gap: 6px; }

    /* ─── ORTA SEPET ALANI (SPA) ─── */
    .center-cart-wrapper {
        background: white; border-radius: var(--radius-md); padding: 30px;
        border: 1px solid #f1f5f9; box-shadow: 0 10px 30px rgba(0,0,0,0.02);
    }
    .center-cart-item {
        display: flex; align-items: center; gap: 20px; padding: 15px 0; border-bottom: 1px solid #f1f5f9;
    }
    .center-cart-item:last-child { border-bottom: none; }
    .center-cart-img {
        width: 80px; height: 80px; border-radius: 16px; object-fit: cover; box-shadow: 0 4px 10px rgba(0,0,0,0.05); border: 1px solid #f8fafc;
    }
    .center-cart-info { flex: 1; }
    .center-cart-info h4 { font-size: 1.1rem; font-weight: 800; margin: 0 0 5px; color: var(--text-dark); }
    .center-cart-info .price { font-size: 1rem; font-weight: 800; color: var(--primary); }
    
    .center-cart-actions { display: flex; align-items: center; gap: 20px; }
    .qty-controls { display: flex; align-items: center; gap: 10px; background: #f8fafc; padding: 5px; border-radius: 12px; border: 1px solid #e2e8f0; }
    .qty-controls button { width: 35px; height: 35px; border-radius: 8px; border: none; background: white; font-weight: 800; cursor: pointer; transition: 0.2s; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
    .qty-controls button:hover { background: var(--primary); color: white; }
    .qty-controls span { font-weight: 800; font-size: 1rem; min-width: 30px; text-align: center; }
    .remove-btn { background: #fee2e2; color: var(--danger); border: none; width: 40px; height: 40px; border-radius: 12px; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: 0.2s; }
    .remove-btn:hover { background: var(--danger); color: white; }

    /* ─── HESABIM ALANI (SPA) ─── */
    .account-card { background: white; border-radius: var(--radius-md); padding: 30px; border: 1px solid #f1f5f9; box-shadow: 0 10px 30px rgba(0,0,0,0.02); text-align: center; transition: 0.3s;}
    .account-card:hover { transform: translateY(-5px); box-shadow: 0 15px 35px rgba(0,0,0,0.05); border-color: #e2e8f0;}

    /* ─── SAĞ SIDEBAR (SEPET + PROMO YAPIŞKAN) ─── */
    .app-right {
        width: 320px;
        display: flex;
        flex-direction: column;
        gap: 20px;
        flex-shrink: 0;
        position: sticky;
        top: 100px;
        height: fit-content; /* YAPIŞKANLIK İÇİN ZORUNLU */
        max-height: calc(100vh - 120px);
        overflow-y: auto;
        scrollbar-width: none;
    }
    .app-right::-webkit-scrollbar { display: none; }

    /* Sağ Sepet Paneli */
    .cart-panel { background: var(--bg-panel); border-radius: var(--radius-lg); padding: 25px; box-shadow: var(--shadow-soft); }
    .cart-panel-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 2px solid #f1f5f9; }
    .cart-panel-header h3 { font-size: 1.1rem; font-weight: 800; margin: 0; display: flex; align-items: center; gap: 8px; color: var(--text-dark);}
    .cart-panel-header .cart-count-badge { background: var(--danger); color: white; font-size: 0.75rem; padding: 3px 10px; border-radius: 12px; font-weight: 800; }
    
    .cart-empty { text-align: center; padding: 30px 0; color: var(--text-muted); }
    .cart-empty i { font-size: 2.5rem; margin-bottom: 12px; opacity: 0.3; }
    .cart-empty p { font-size: 0.9rem; font-weight: 600; margin: 0; }

    .cart-item-row { display: flex; align-items: center; gap: 12px; padding: 12px 0; border-bottom: 1px solid #f8fafc; }
    .cart-item-row:last-child { border-bottom: none; }
    .cart-item-img { width: 50px; height: 50px; border-radius: 12px; overflow: hidden; flex-shrink: 0; background: #f8fafc; border: 1px solid #e2e8f0;}
    .cart-item-img img { width: 100%; height: 100%; object-fit: cover; }
    .cart-item-info { flex: 1; min-width: 0; }
    .cart-item-info h5 { font-size: 0.85rem; font-weight: 800; margin: 0 0 3px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--text-dark);}
    .cart-item-info span { font-size: 0.8rem; color: var(--text-muted); font-weight: 600; }

    .cart-summary { margin-top: 20px; padding-top: 20px; border-top: 2px dashed #e2e8f0; }
    .cart-summary-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
    .cart-summary-row span { font-size: 0.85rem; color: var(--text-muted); font-weight: 600; }
    .cart-summary-row strong { font-size: 0.95rem; font-weight: 800; color: var(--text-dark);}
    .cart-summary-row.total span { font-size: 1.1rem; color: var(--text-dark); font-weight: 800; }
    .cart-summary-row.total strong { font-size: 1.4rem; color: var(--primary); font-weight: 900; }

    .btn-checkout { width: 100%; padding: 16px; border: none; border-radius: 16px; background: var(--primary); color: white; font-family: 'Outfit'; font-size: 1.05rem; font-weight: 800; cursor: pointer; transition: 0.3s; margin-top: 15px; box-shadow: 0 6px 20px rgba(16,185,129,0.3); display:flex; align-items:center; justify-content:center; gap:8px; text-decoration:none;}
    .btn-checkout:hover { transform: translateY(-3px); background: var(--primary-dark); color:white; box-shadow: 0 8px 25px rgba(16,185,129,0.4);}

    /* Promo Kart (Büyütüldü ve Düzeltildi) */
    .promo-banner { background: linear-gradient(135deg, var(--accent-purple), #7c3aed); border-radius: var(--radius-lg); padding: 30px; color: white; position: relative; overflow: hidden; box-shadow: 0 10px 30px rgba(139,92,246,0.25); text-decoration: none; display: block; min-height: 150px;}
    .promo-banner h3 { font-size: 1.8rem; font-weight: 900; margin: 0 0 8px; }
    .promo-banner p { font-size: 0.95rem; font-weight: 500; opacity: 0.9; margin: 0; }
    .promo-banner img { position: absolute; right: -20px; bottom: -10px; top: auto; width: 130px; filter: drop-shadow(-5px 5px 15px rgba(0,0,0,0.4)); transform: rotate(-10deg); }

    /* Yeni Ürünler Listesi */
    .new-products-section { background: var(--bg-panel); border-radius: var(--radius-lg); padding: 25px; box-shadow: var(--shadow-soft); }
    .new-products-section h3 { font-size: 1.1rem; font-weight: 800; margin: 0 0 15px; display: flex; align-items: center; gap: 8px; color: var(--text-dark); border-bottom: 2px solid #f1f5f9; padding-bottom: 12px;}
    .new-products-section h3 i { color: var(--accent); }

    .new-prod-item { display: flex; align-items: center; gap: 12px; padding: 12px 0; border-bottom: 1px solid #f8fafc; text-decoration: none; color: var(--text-dark); transition: 0.2s; }
    .new-prod-item:last-child { border-bottom: none; padding-bottom: 0; }
    .new-prod-item:hover { transform: translateX(5px); }
    .new-prod-img { width: 55px; height: 55px; border-radius: 12px; overflow: hidden; flex-shrink: 0; background: white; border: 1px solid #e2e8f0; }
    .new-prod-img img { width: 100%; height: 100%; object-fit: cover; }
    .new-prod-info { flex: 1; min-width: 0; }
    .new-prod-info h4 { font-size: 0.85rem; font-weight: 700; margin: 0 0 3px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--text-dark);}
    .new-prod-info span { font-size: 0.95rem; color: var(--primary); font-weight: 800; }
    .new-prod-badge { font-size: 0.6rem; background: #fef3c7; color: var(--accent); padding: 3px 8px; border-radius: 8px; font-weight: 800; flex-shrink: 0; }

    /* ─── MOBİL BOTTOM NAV ─── */
    .mobile-bottom-nav { display: none; position: fixed; bottom: 0; left: 0; right: 0; background: var(--bg-panel); box-shadow: 0 -4px 25px rgba(0,0,0,0.08); z-index: 9999; padding: 8px 0 max(8px, env(safe-area-inset-bottom)); border-radius: 25px 25px 0 0; }
    .mobile-bottom-nav-inner { display: flex; justify-content: space-around; align-items: center; max-width: 500px; margin: 0 auto; }
    .mob-nav-btn { display: flex; flex-direction: column; align-items: center; gap: 4px; padding: 6px 10px; border: none; background: none; color: var(--text-muted); font-size: 0.65rem; font-weight: 700; cursor: pointer; transition: 0.2s; position: relative; text-decoration: none; font-family: 'Outfit', sans-serif; }
    .mob-nav-btn i { font-size: 1.3rem; }
    .mob-nav-btn.active { color: var(--primary); }
    .mob-nav-btn .mob-badge { position: absolute; top: -2px; right: 2px; background: var(--danger); color: white; font-size: 0.55rem; padding: 2px 6px; border-radius: 10px; font-weight: 800; }

    /* ─── RESPONSIVE ─── */
    @media (max-width: 1200px) { .app-right { display: none; } }
    @media (max-width: 991px) {
        .app-sidebar { display: none; }
        .mobile-bottom-nav { display: block; }
        .app-container { margin: 10px auto; padding: 0 10px; gap: 12px; flex-direction: column;}
        .app-main { padding: 20px 15px; border-radius: 20px; width: 100%;}
        .main-header { padding: 0; margin-bottom: 20px; box-shadow: none; background: transparent; flex-direction:column; align-items:flex-start;}
        .search-box { max-width: 100%; }
        .products-grid { grid-template-columns: repeat(2, 1fr); gap: 12px; }
        .products-grid .p-card { padding: 12px; margin-top: 35px; }
        .products-grid .p-img-wrap { width: 85px; height: 85px; margin-top: -45px; }
        .products-grid .p-name { font-size: 0.85rem; }
        .products-grid .p-price { font-size: 1.05rem; }
        .btn-cart-add { width: 34px; height: 34px; font-size: 0.85rem; }
        /* Mobilde kareler sarılsın diye özellikleri koruyoruz */
        .cat-grid { gap: 8px; justify-content: center;}
        .cat-square { width: 75px; height: 75px; flex: 0 0 auto; border-radius: 14px;}
        .cat-square i { font-size: 1.2rem; }
        .cat-square span { font-size: 0.65rem;}
        .prod-toolbar h2 { font-size: 1rem; }
        body { padding-bottom: 90px; }
        .blog-grid { grid-template-columns: repeat(2, 1fr); gap: 12px; }
    }
    @media (max-width: 480px) {
        .products-grid { grid-template-columns: repeat(2, 1fr); gap: 10px; }
        .products-grid .p-img-wrap { width: 75px; height: 75px; margin-top: -40px; }
        .products-grid .p-name { font-size: 0.8rem; }
        .products-grid .p-desc { display: none; }
        .products-grid .p-price { font-size: 0.95rem; }
        .btn-cart-add { width: 30px; height: 30px; font-size: 0.75rem; }
        .main-header h1 { font-size: 1.2rem; }
        .blog-grid { grid-template-columns: 1fr; }
    }
</style>

<div class="app-container">

    <!-- ═══ SOL SIDEBAR ═══ -->
    <aside class="app-sidebar">
        <div class="user-profile-card">
            <?php if($is_logged_in): ?>
                <div class="user-avatar-circle"><?= $initials ?></div>
                <div class="welcome-text-small">Hoşgeldiniz</div>
                <h4><?= htmlspecialchars($user_name) ?></h4>
                <?php if(!empty($user_phone)): ?>
                    <span><?= htmlspecialchars($user_phone) ?></span>
                <?php endif; ?>
            <?php else: ?>
                <div class="user-avatar-circle" style="background:#e2e8f0; color:#64748b; border-color:#cbd5e1;">Mİ</div>
                <div class="welcome-text-small" style="color:#64748b;">Misafir</div>
                <h4>Giriş Yapın</h4>
            <?php endif; ?>
        </div>

        <div class="sidebar-nav">
            <a href="/" class="nav-item"><i class="fas fa-home"></i> Ana Sayfa</a>
            <button class="nav-item active" id="navCatalog" onclick="switchTab('catalog')"><i class="fas fa-th-large"></i> Katalog</button>
            <button class="nav-item" id="navBlog" onclick="switchTab('blog')"><i class="fas fa-newspaper"></i> Makaleler</button>
            <button class="nav-item d-none d-lg-flex" id="navCart" onclick="switchTab('cart')">
                <i class="fas fa-shopping-basket"></i> Sepetim
                <?php if($cart_count > 0): ?>
                <span class="badge-count" id="leftCartBadge"><?php echo $cart_count; ?></span>
                <?php endif; ?>
            </button>
            <?php if ($is_logged_in): ?>
                <button class="nav-item" id="navAccount" onclick="switchTab('account')"><i class="fas fa-user-circle"></i> Hesabım</button>
            <?php else: ?>
                <a href="https://fidebahcesi.com/login" class="nav-item"><i class="fas fa-sign-in-alt"></i> Giriş Yap / Kayıt Ol</a>
            <?php endif; ?>
        </div>

        <div class="sidebar-promo">
            <i class="fas fa-shipping-fast"></i>
            <h5>Hızlı Teslimat</h5>
            <p>Tüm Türkiye'ye güvenli kargo</p>
        </div>
    </aside>

    <!-- ═══ ORTA ANA ALAN ═══ -->
    <main class="app-main">
        
        <!-- Üst Header -->
        <div class="main-header">
            <h1>Kataloğa Hoşgeldin 🌱</h1>
            <div class="search-box">
                <i class="fas fa-search"></i>
                <input type="text" id="searchInput" placeholder="Fide, tohum, ürün ara..." autocomplete="off">
            </div>
        </div>

        <!-- 1. SEKME: KATALOG (KATEGORİLER VE ÜRÜNLER) -->
        <div id="catalogSection" class="spa-section active">
            <!-- Kategori Chip'leri (KARE IZGARA DÜZELTİLDİ) -->
            <div class="cat-grid" id="catGrid">
                <div class="cat-square active" onclick="filterCat('all', this)">
                    <i class="fas fa-border-all"></i>
                    <span>Tümü</span>
                </div>
                <?php foreach($categories as $cat):
                    $icon = !empty($cat['icon']) ? $cat['icon'] : 'fa-leaf';
                ?>
                <div class="cat-square" onclick="filterCat('<?php echo $cat['id']; ?>', this)">
                    <i class="fas <?php echo htmlspecialchars($icon); ?>"></i>
                    <span><?php echo htmlspecialchars($cat['name']); ?></span>
                </div>
                <?php endforeach; ?>
            </div>

            <!-- Toolbar -->
            <div class="prod-toolbar">
                <h2>Ürünler <span style="font-size:0.9rem; color:var(--text-muted); font-weight:700; margin-left:5px;" id="prodCount">(<?php echo count($products); ?>)</span></h2>
                <div class="toolbar-right">
                    <!-- Sonsuz kaydırma mantığı eklendi, select listesi gizli başlangıç limiti olarak çalışacak -->
                    <select class="limit-sel" id="limitSelect" onchange="changeLimit()">
                        <option value="12">12 İlk Yükleme</option>
                        <option value="24">24 İlk Yükleme</option>
                        <option value="all">Hepsini Aç</option>
                    </select>
                    <button class="view-toggle active" onclick="setViewMode('grid', this)"><i class="fas fa-th-large"></i></button>
                    <button class="view-toggle" onclick="setViewMode('list', this)"><i class="fas fa-list"></i></button>
                </div>
            </div>

            <!-- Ürünler (Görünürlük JS ile Yönetilecek) -->
            <div class="products-grid" id="productContainer">
                <?php if(empty($products)): ?>
                    <div style="grid-column: 1/-1; text-align:center; padding: 40px 20px; color:var(--text-muted);">
                        <i class="fas fa-box-open fa-3x mb-3 opacity-50"></i>
                        <h4>Henüz ürün eklenmedi.</h4>
                    </div>
                <?php else:
                    foreach($products as $p):
                        $p_img = fixAppImg($p['main_image']);
                        $p_price = ($p['discount_price'] > 0 && $p['discount_price'] < $p['price']) ? $p['discount_price'] : $p['price'];
                        $p_slug = !empty($p['slug']) ? $p['slug'] : $p['id'];
                        $cats = $p['category_id'];
                        $p_desc = !empty($p['short_description']) ? mb_substr(strip_tags($p['short_description']), 0, 50) : '';
                ?>
                <a href="/urun/<?php echo htmlspecialchars($p_slug); ?>"
                   class="p-card product-item"
                   data-cats="<?php echo htmlspecialchars($cats); ?>"
                   data-name="<?php echo mb_strtolower($p['name'], 'UTF-8'); ?>">
                    <div class="p-img-wrap">
                        <img src="<?php echo htmlspecialchars($p_img); ?>" alt="<?php echo htmlspecialchars($p['name']); ?>" loading="lazy">
                    </div>
                    <div class="p-name"><?php echo htmlspecialchars($p['name']); ?></div>
                    <div class="p-desc"><?php echo htmlspecialchars($p_desc); ?>...</div>
                    <div class="p-foot">
                        <div class="p-price">₺<?php echo number_format($p_price, 2); ?></div>
                        <button type="button" class="btn-cart-add" onclick="addToCart(event, this, <?= $p['id'] ?>, '<?= htmlspecialchars(addslashes($p['name'])) ?>', <?= $p_price ?>, '<?= $p_img ?>')">
                            <i class="fas fa-plus"></i>
                        </button>
                    </div>
                </a>
                <?php endforeach; endif; ?>
            </div>
        </div>

        <!-- 2. SEKME: MAKALELER (BLOG SPA - DÜZELTİLDİ) -->
        <div id="blogSection" class="spa-section">
            <div class="prod-toolbar mb-4">
                <h2>Uzman Makaleleri <span style="font-size:0.9rem; color:var(--text-muted); font-weight:700; margin-left:5px;">(<?php echo count($articles); ?>)</span></h2>
            </div>
            
            <?php if(empty($articles)): ?>
                <div style="text-align:center;padding:60px 0;color:var(--text-muted); background: white; border-radius: 20px; border: 1px dashed #e2e8f0;">
                    <i class="fas fa-newspaper fa-3x mb-3" style="opacity:0.3;"></i>
                    <h4 style="font-weight:700;">Henüz blog yazısı yok.</h4>
                </div>
            <?php else: ?>
                <div class="blog-grid">
                    <?php foreach($articles as $a):
                        $a_img = !empty($a['image']) ? fixAppImg($a['image']) : '';
                        $raw_desc = !empty($a['short_content']) ? $a['short_content'] : (!empty($a['short_desc']) ? $a['short_desc'] : ($a['content'] ?? ''));
                        $a_content = mb_substr(strip_tags($raw_desc), 0, 100);
                        $a_slug = !empty($a['slug']) ? $a['slug'] : $a['id'];
                        $a_date = date('d.m.Y', strtotime($a['created_at']));
                    ?>
                    <a href="/blog/<?php echo htmlspecialchars($a_slug); ?>" class="blog-card">
                        <?php if($a_img && $a_img !== '/assets/images/no-image.jpg'): ?>
                            <img class="blog-card-img" src="<?php echo htmlspecialchars($a_img); ?>" alt="<?php echo htmlspecialchars($a['title']); ?>" loading="lazy">
                        <?php else: ?>
                            <div class="blog-card-img" style="background:var(--primary-light); display:flex; align-items:center; justify-content:center;">
                                <i class="fas fa-leaf fa-2x" style="color:var(--primary);"></i>
                            </div>
                        <?php endif; ?>
                        <div class="blog-card-body">
                            <h3><?php echo htmlspecialchars($a['title']); ?></h3>
                            <p><?php echo htmlspecialchars($a_content); ?>...</p>
                            <div class="blog-card-date"><i class="fas fa-calendar-alt"></i> <?php echo $a_date; ?></div>
                        </div>
                    </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <!-- 3. SEKME: SEPET (ORTADA AÇILACAK) -->
        <div id="cartSection" class="spa-section">
            <div class="prod-toolbar mb-4">
                <h2><i class="fas fa-shopping-basket text-primary me-2"></i> Detaylı Sepetim</h2>
            </div>
            
            <div class="center-cart-wrapper">
                <?php if (empty($cart_items)): ?>
                    <div style="text-align:center;padding:50px 0;color:var(--text-muted);">
                        <i class="fas fa-shopping-basket fa-3x mb-3" style="opacity:0.3;"></i>
                        <h4 style="font-weight:700;">Sepetiniz boş</h4>
                        <p style="font-size:0.9rem;">Hemen katalogdan ürün eklemeye başlayın.</p>
                        <button onclick="switchTab('catalog')" class="btn-checkout" style="width:auto; display:inline-block; padding:12px 30px;">Kataloğa Dön</button>
                    </div>
                <?php else: ?>
                    <?php foreach($cart_items as $ci): ?>
                    <div class="center-cart-item">
                        <img src="<?php echo htmlspecialchars(fixAppImg($ci['image'])); ?>" class="center-cart-img" alt="">
                        <div class="center-cart-info">
                            <h4><?php echo htmlspecialchars($ci['name'], ENT_QUOTES); ?></h4>
                            <div class="price">₺<?php echo number_format($ci['price'], 2); ?></div>
                        </div>
                        <div class="center-cart-actions">
                            <div class="qty-controls">
                                <button onclick="updateCartQty(<?php echo $ci['id']; ?>, -1)">−</button>
                                <span><?php echo $ci['quantity']; ?></span>
                                <button onclick="updateCartQty(<?php echo $ci['id']; ?>, 1)">+</button>
                            </div>
                            <button class="remove-btn" onclick="removeFromCart(<?php echo $ci['id']; ?>)">
                                <i class="fas fa-trash-alt"></i>
                            </button>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    
                    <div style="margin-top:30px; padding-top:20px; border-top:2px solid #e2e8f0; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:20px;">
                        <div>
                            <span style="font-size:1.1rem; color:var(--text-muted); font-weight:600; display:block;">Genel Toplam</span>
                            <strong style="font-size:1.8rem; color:var(--primary); font-weight:900;">₺<?php echo number_format($cart_total, 2); ?></strong>
                        </div>
                        <a href="/cart.php" class="btn-checkout" style="width:250px; margin:0; padding:18px; font-size:1.1rem;">
                            Sepeti Onayla <i class="fas fa-check-circle ms-1"></i>
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- 4. SEKME: HESABIM (YENİ EKLENDİ) -->
        <div id="accountSection" class="spa-section">
            <div class="prod-toolbar mb-4">
                <h2><i class="fas fa-user-circle text-primary me-2"></i> Hesabım</h2>
            </div>
            
            <?php if($is_logged_in): ?>
            <div class="row g-4">
                <div class="col-md-6">
                    <div class="account-card">
                        <i class="fas fa-box-open fa-3x mb-3 text-primary"></i>
                        <h4 style="font-weight:800; color:var(--text-dark);">Siparişlerim</h4>
                        <p class="text-muted small px-2">Geçmiş siparişlerinizi, kargo durumunu ve detayları görüntüleyin.</p>
                        <a href="https://fidebahcesi.com/hesabim/siparisler" class="btn-checkout w-auto d-inline-block px-4 py-2 mt-2" style="border-radius:12px;">Siparişlere Git</a>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="account-card">
                        <i class="fas fa-user-edit fa-3x mb-3" style="color:var(--accent);"></i>
                        <h4 style="font-weight:800; color:var(--text-dark);">Hesap Ayarları</h4>
                        <p class="text-muted small px-2">Teslimat adresi, telefon ve şifre gibi bilgilerinizi güncelleyin.</p>
                        <a href="https://fidebahcesi.com/hesabim/ayarlar" class="btn-checkout w-auto d-inline-block px-4 py-2 mt-2" style="background:var(--accent); border-radius:12px;">Bilgileri Düzenle</a>
                    </div>
                </div>
                <div class="col-12">
                    <div class="d-flex justify-content-between align-items-center p-4 mt-2" style="background:white; border-radius:20px; border:1px solid #f1f5f9;">
                        <div class="d-flex align-items-center gap-3">
                            <div class="user-avatar-circle" style="width:50px; height:50px; margin:0; font-size:1.2rem; box-shadow:none;"><?= $initials ?></div>
                            <div>
                                <h5 style="margin:0; font-weight:800; color:var(--text-dark);"><?= htmlspecialchars($user_name) ?></h5>
                                <span class="text-muted small"><?= htmlspecialchars($user_phone ?: 'Kayıtlı Telefon Yok') ?></span>
                            </div>
                        </div>
                        <a href="https://fidebahcesi.com/logout" class="btn btn-sm btn-danger fw-bold rounded-pill px-4 py-2 text-white text-decoration-none shadow-sm"><i class="fas fa-sign-out-alt me-1"></i> Çıkış Yap</a>
                    </div>
                </div>
            </div>
            <?php else: ?>
            <div style="text-align:center;padding:60px 0;color:var(--text-muted); background: white; border-radius: 20px; border: 1px dashed #e2e8f0;">
                <i class="fas fa-user-lock fa-3x mb-3 opacity-50"></i>
                <h4 style="font-weight:700;">Giriş Yapmadınız</h4>
                <p style="font-size:0.9rem;">Siparişlerinizi ve hesap bilgilerinizi görmek için lütfen giriş yapın.</p>
                <a href="https://fidebahcesi.com/login" class="btn-checkout w-auto d-inline-block px-5 py-3 mt-3" style="border-radius:14px; font-size:1rem;">Giriş Yap / Kayıt Ol</a>
            </div>
            <?php endif; ?>
        </div>

    </main>

    <!-- ═══ SAĞ SIDEBAR (SEPET + PROMO YAPIŞKAN) ═══ -->
    <aside class="app-right">

        <!-- Sepet Paneli -->
        <div class="cart-panel">
            <div class="cart-panel-header">
                <h3><i class="fas fa-shopping-basket text-primary"></i> Sepetim</h3>
                <span class="cart-count-badge" id="rightCartBadge"><?php echo $cart_count; ?></span>
            </div>

            <?php if (empty($cart_items)): ?>
                <div class="cart-empty">
                    <i class="fas fa-shopping-basket"></i>
                    <p>Sepetiniz boş</p>
                </div>
            <?php else:
                foreach($cart_items as $ci): ?>
                <div class="cart-item-row">
                    <div class="cart-item-img">
                        <img src="<?php echo htmlspecialchars(fixAppImg($ci['image'])); ?>" alt="">
                    </div>
                    <div class="cart-item-info">
                        <h5><?php echo htmlspecialchars($ci['name']); ?></h5>
                        <span>₺<?php echo number_format($ci['price'], 2); ?> × <?php echo $ci['quantity']; ?></span>
                    </div>
                </div>
            <?php endforeach; ?>
                <div class="cart-summary">
                    <div class="cart-summary-row total">
                        <span>Toplam</span>
                        <strong>₺<?php echo number_format($cart_total, 2); ?></strong>
                    </div>
                    <button class="btn-checkout" onclick="switchTab('cart')">
                        Sepete Git <i class="fas fa-arrow-right ms-1"></i>
                    </button>
                </div>
            <?php endif; ?>
        </div>

        <!-- Promo (Büyük) -->
        <a href="/kampanyalar" class="promo-banner">
            <h3>%20 İndirim</h3>
            <p>Seçili aşılı fidelerde!</p>
            <img src="/assets/images/header_sebze.png" onerror="this.style.display='none'" alt="">
        </a>

        <!-- Yeni Ürünler (List Yapısı) -->
        <div class="new-products-section">
            <h3><i class="fas fa-fire"></i> Yeni Ürünler</h3>
            <?php foreach($new_products as $np):
                $np_img = fixAppImg($np['main_image']);
                $np_price = ($np['discount_price'] > 0 && $np['discount_price'] < $np['price']) ? $np['discount_price'] : $np['price'];
                $np_slug = !empty($np['slug']) ? $np['slug'] : $np['id'];
            ?>
            <a href="/urun/<?php echo htmlspecialchars($np_slug); ?>" class="new-prod-item">
                <div class="new-prod-img">
                    <img src="<?php echo htmlspecialchars($np_img); ?>" alt="<?php echo htmlspecialchars($np['name']); ?>" loading="lazy">
                </div>
                <div class="new-prod-info">
                    <h4><?php echo htmlspecialchars($np['name']); ?></h4>
                    <span>₺<?php echo number_format($np_price, 2); ?></span>
                </div>
                <span class="new-prod-badge">Yeni</span>
            </a>
            <?php endforeach; ?>
        </div>

    </aside>

</div>

<!-- ═══════════════════════════════════════ -->
<!--        MOBİL BOTTOM NAVİGASYON         -->
<!-- ═══════════════════════════════════════ -->
<nav class="mobile-bottom-nav">
    <div class="mobile-bottom-nav-inner">
        <a href="/" class="mob-nav-btn"><i class="fas fa-home"></i><span>Ana Sayfa</span></a>
        <button class="mob-nav-btn active" id="mobNavCatalog" onclick="switchTab('catalog')"><i class="fas fa-th-large"></i><span>Katalog</span></button>
        <button class="mob-nav-btn" id="mobNavBlog" onclick="switchTab('blog')"><i class="fas fa-newspaper"></i><span>Makaleler</span></button>
        <button class="mob-nav-btn" id="mobNavCart" onclick="switchTab('cart')">
            <i class="fas fa-shopping-basket"></i><span>Sepet</span>
            <?php if($cart_count > 0): ?>
            <span class="mob-badge" id="mobCartBadge"><?php echo $cart_count; ?></span>
            <?php endif; ?>
        </button>
        <?php if ($is_logged_in): ?>
            <button class="mob-nav-btn" id="mobNavAccount" onclick="switchTab('account')"><i class="fas fa-user-circle"></i><span>Hesabım</span></button>
        <?php else: ?>
            <a href="https://fidebahcesi.com/login" class="mob-nav-btn"><i class="fas fa-sign-in-alt"></i><span>Giriş</span></a>
        <?php endif; ?>
    </div>
</nav>

<!-- ═══════════════════════════════════════ -->
<!--               JAVASCRIPT                -->
<!-- ═══════════════════════════════════════ -->
<script>
    var currentView = 'grid';
    var currentCat = 'all';
    var currentSearch = '';
    
    // SONSUZ KAYDIRMA LİMİTİ
    var currentLimit = parseInt(document.getElementById('limitSelect').value) || 12;

    // ─── SPA TAB DEĞİŞTİRİCİ (Katalog <-> Blog <-> Sepet <-> Hesabım) ───
    function switchTab(tabName) {
        document.getElementById('catalogSection').classList.remove('active');
        document.getElementById('blogSection').classList.remove('active');
        document.getElementById('cartSection').classList.remove('active');
        document.getElementById('accountSection').classList.remove('active');
        
        document.getElementById(tabName + 'Section').classList.add('active');
        
        document.getElementById('navCatalog').classList.remove('active');
        document.getElementById('navBlog').classList.remove('active');
        if(document.getElementById('navCart')) document.getElementById('navCart').classList.remove('active');
        if(document.getElementById('navAccount')) document.getElementById('navAccount').classList.remove('active');
        
        if(document.getElementById('mobNavCatalog')) document.getElementById('mobNavCatalog').classList.remove('active');
        if(document.getElementById('mobNavBlog')) document.getElementById('mobNavBlog').classList.remove('active');
        if(document.getElementById('mobNavCart')) document.getElementById('mobNavCart').classList.remove('active');
        if(document.getElementById('mobNavAccount')) document.getElementById('mobNavAccount').classList.remove('active');
        
        if (tabName === 'catalog') {
            document.getElementById('navCatalog').classList.add('active');
            if(document.getElementById('mobNavCatalog')) document.getElementById('mobNavCatalog').classList.add('active');
            document.getElementById('searchInput').placeholder = "Fide, tohum, ürün ara...";
        } else if (tabName === 'blog') {
            document.getElementById('navBlog').classList.add('active');
            if(document.getElementById('mobNavBlog')) document.getElementById('mobNavBlog').classList.add('active');
            document.getElementById('searchInput').placeholder = "Makale başlıklarında ara...";
        } else if (tabName === 'cart') {
            if(document.getElementById('navCart')) document.getElementById('navCart').classList.add('active');
            if(document.getElementById('mobNavCart')) document.getElementById('mobNavCart').classList.add('active');
        } else if (tabName === 'account') {
            if(document.getElementById('navAccount')) document.getElementById('navAccount').classList.add('active');
            if(document.getElementById('mobNavAccount')) document.getElementById('mobNavAccount').classList.add('active');
        }
        
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }

    // ─── GÖRÜNÜM DEĞİŞTİR ───
    function setViewMode(mode, btn) {
        currentView = mode;
        document.querySelectorAll('.view-toggle').forEach(function(b){ b.classList.remove('active'); });
        btn.classList.add('active');
        var container = document.getElementById('productContainer');
        container.className = (mode === 'grid') ? 'products-grid' : 'products-list';
        if (mode === 'list') {
            document.querySelectorAll('.product-item').forEach(function(card) {
                if (card.querySelector('.p-info')) return;
                var imgWrap = card.querySelector('.p-img-wrap');
                var nameEl = card.querySelector('.p-name');
                var descEl = card.querySelector('.p-desc');
                var footEl = card.querySelector('.p-foot');
                var infoDiv = document.createElement('div');
                infoDiv.className = 'p-info';
                infoDiv.appendChild(nameEl.cloneNode(true));
                infoDiv.appendChild(descEl.cloneNode(true));
                var footDiv = document.createElement('div');
                footDiv.className = 'p-foot';
                footDiv.appendChild(footEl.querySelector('.p-price').cloneNode(true));
                var origBtn = footEl.querySelector('.btn-cart-add');
                var newBtn = origBtn.cloneNode(true);
                newBtn.setAttribute('onclick', origBtn.getAttribute('onclick'));
                footDiv.appendChild(newBtn);
                card.innerHTML = '';
                card.appendChild(imgWrap);
                card.appendChild(infoDiv);
                card.appendChild(footDiv);
            });
        } else {
            location.reload(); 
        }
    }

    // ─── KATEGORİ FİLTRELE ───
    function filterCat(catId, el) {
        currentCat = catId;
        document.querySelectorAll('.cat-square').forEach(function(c){ c.classList.remove('active'); });
        el.classList.add('active');
        document.getElementById('searchInput').value = '';
        currentSearch = '';
        // Kategori değişince limiti sıfırla (Sonsuz kaydırma için başa dön)
        currentLimit = parseInt(document.getElementById('limitSelect').value) || 12;
        applyFilters();
    }

    // ─── ARAMA ───
    document.getElementById('searchInput').addEventListener('input', function() {
        currentSearch = this.value.toLowerCase().trim();
        if(document.getElementById('blogSection').classList.contains('active')) {
            const blogs = document.querySelectorAll('.blog-card');
            blogs.forEach(blog => {
                const title = blog.querySelector('h3').textContent.toLowerCase();
                if(title.includes(currentSearch)) { blog.style.display = 'flex'; } 
                else { blog.style.display = 'none'; }
            });
        } else {
            applyFilters();
        }
    });

    // ─── LİMİT DEĞİŞTİR ───
    function changeLimit() {
        var val = document.getElementById('limitSelect').value;
        if(val === 'all') currentLimit = 9999;
        else currentLimit = parseInt(val);
        applyFilters();
    }

    // ─── FİLTRE + SONSUZ SAYFALAMA MOTORU ───
    function applyFilters() {
        var items = document.querySelectorAll('.product-item');
        var visibleCount = 0;
        var totalMatch = 0;
        
        items.forEach(function(item) {
            var cats = item.getAttribute('data-cats').split(',');
            var name = item.getAttribute('data-name');
            var catMatch = (currentCat === 'all') || (cats.indexOf(currentCat.toString()) !== -1);
            var searchMatch = (!currentSearch) || (name.indexOf(currentSearch) !== -1);
            
            if (catMatch && searchMatch) {
                totalMatch++;
                if (currentLimit === 9999 || visibleCount < currentLimit) {
                    item.style.display = ''; // Flex iptal edildi çünkü grid yönetiyor
                    visibleCount++;
                } else {
                    item.style.display = 'none';
                }
            } else {
                item.style.display = 'none';
            }
        });
        document.getElementById('prodCount').textContent = '(' + totalMatch + ')';
    }

    // ─── SONSUZ KAYDIRMA EKRANI İZLEME ───
    window.addEventListener('scroll', function() {
        if(document.getElementById('catalogSection').classList.contains('active')) {
            // Sayfa sonuna 300px kala tetikle
            if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 300) {
                if (currentLimit !== 9999) {
                    currentLimit += 12; // 12 ürün daha yükle
                    applyFilters();
                }
            }
        }
    });

    // ─── SEPETE EKLE ───
    function addToCart(event, btnEl, productId, productName, price, image) {
        event.preventDefault();
        event.stopPropagation();

        btnEl.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        btnEl.disabled = true;

        var formData = new FormData();
        formData.append('add_to_cart', '1');
        formData.append('product_id', productId);
        formData.append('quantity', '1');

        fetch('/cart.php', { method: 'POST', body: formData })
        .then(function(res) { return res.json(); })
        .then(function(data) {
            if (data.status === 'success' || data.success === true) {
                Swal.fire({
                    icon: 'success', title: 'Sepete Eklendi!',
                    text: productName + ' sepetinize eklendi.',
                    toast: true, position: 'top-end',
                    showConfirmButton: false, timer: 1500,
                    customClass: { popup: 'swal2-container' }
                });
                setTimeout(function() { window.location.reload(); }, 1500);
            } else {
                btnEl.innerHTML = '<i class="fas fa-plus"></i>';
                btnEl.disabled = false;
                Swal.fire({ icon: 'error', title: 'Hata', text: data.message || 'Eklenemedi.', toast: true, position: 'top-end', showConfirmButton: false, timer: 2000, customClass: { popup: 'swal2-container' } });
            }
        })
        .catch(function(err) {
            console.error(err);
            var form = document.createElement('form');
            form.method = 'POST'; form.action = '/cart.php';
            var i1 = document.createElement('input'); i1.type='hidden'; i1.name='add_to_cart'; i1.value='1';
            var i2 = document.createElement('input'); i2.type='hidden'; i2.name='product_id'; i2.value=productId;
            var i3 = document.createElement('input'); i3.type='hidden'; i3.name='quantity'; i3.value='1';
            form.appendChild(i1); form.appendChild(i2); form.appendChild(i3);
            document.body.appendChild(form); form.submit();
        });
    }

    // ─── SEPET MİKTAR GÜNCELLE ───
    function updateCartQty(productId, delta) {
        var formData = new FormData();
        formData.append('update_cart', '1');
        formData.append('product_id', productId);
        formData.append('delta', delta);
        fetch('/cart.php', { method: 'POST', body: formData })
        .then(function() { window.location.reload(); })
        .catch(function() { window.location.reload(); });
    }

    // ─── SEPETTEN SİL ───
    function removeFromCart(productId) {
        Swal.fire({
            title: 'Ürün silinsin mi?',
            text: 'Bu ürün sepetinizden kaldırılacak.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#94a3b8',
            confirmButtonText: 'Evet, Sil',
            cancelButtonText: 'Vazgeç',
            customClass: { popup: 'swal2-container' }
        }).then(function(result) {
            if (result.isConfirmed) {
                var formData = new FormData();
                formData.append('remove_from_cart', '1');
                formData.append('product_id', productId);
                fetch('/cart.php', { method: 'POST', body: formData })
                .then(function() { window.location.reload(); })
                .catch(function() { window.location.reload(); });
            }
        });
    }

    // ─── İLK YÜKLEME ───
    document.addEventListener('DOMContentLoaded', function() {
        applyFilters();
        
        // URL'de hash varsa (örn: site.com/katalog#sepet) direkt sekmeyi aç
        if(window.location.hash === '#sepet' || window.location.hash === '#cart') {
            switchTab('cart');
        } else if(window.location.hash === '#blog' || window.location.hash === '#makaleler') {
            switchTab('blog');
        } else if(window.location.hash === '#hesabim' || window.location.hash === '#account') {
            switchTab('account');
        }
    });
</script>

<?php require_once 'includes/footer.php'; ?>