{{ header }}

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

<div id="content" class="app-wrapper">

    <style>
        :root {
            --app-bg: #f4f5f9;
            --card-bg: #ffffff;
            --primary: #f27a1a; /* Trendyol Turuncusu */
            --primary-dark: #d66209;
            --text-main: #333333;
            --text-sub: #888888;
            --border: #e6e6e6;
            --success: #27ae60;
            --danger: #c0392b;
            --radius: 12px;
        }

        /* Sayfa Genel Ayarları */
        body { background-color: var(--app-bg); -webkit-font-smoothing: antialiased; }
        .page-header, .breadcrumb { display: none !important; } /* Başlıkları gizle */

        .app-wrapper {
            padding-bottom: 90px; /* Alt bar için boşluk */
            max-width: 100%;
            overflow-x: hidden;
        }

        /* MOBİLDE SOL MENÜYÜ GİZLE, MASAÜSTÜNDE GÖSTER */
        @media (max-width: 767px) {
            #column-left { display: none !important; }
        }

        /* ====================
           1. ÜST ARAMA BAR (APP HEADER)
           ==================== */
        .app-header {
            background: #fff;
            padding: 15px;
            position: sticky;
            top: 0;
            z-index: 800; /* Opencart menüsü altında kalsın diye biraz düşük */
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            border-bottom: 1px solid var(--border);
            border-radius: 0 0 12px 12px;
            margin-bottom: 15px;
        }

        .search-container {
            display: flex;
            gap: 10px;
        }

        .search-input-group {
            flex: 1;
            position: relative;
        }

        .search-input-group i {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #999;
        }

        .app-search-input {
            width: 100%;
            padding: 12px 10px 12px 35px;
            border: 1px solid #ddd;
            border-radius: 8px;
            background: #f9f9f9;
            font-size: 14px;
            outline: none;
            transition: all 0.2s;
        }
        .app-search-input:focus { background: #fff; border-color: var(--primary); }

        .btn-filter-toggle {
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 8px;
            width: 44px;
            color: #555;
            display: flex; align-items: center; justify-content: center;
            cursor: pointer;
        }

        .filter-drawer {
            display: none;
            padding-top: 15px;
            border-top: 1px solid #eee;
            margin-top: 15px;
        }
        .filter-drawer.open { display: block; }

        .filter-chip-group { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; }
        .filter-chip-label {
            background: #f0f0f0; padding: 6px 12px; border-radius: 20px;
            font-size: 12px; color: #555; display: flex; align-items: center; gap: 6px;
            cursor: pointer; border: 1px solid transparent; user-select: none;
        }
        .filter-chip-input:checked + .filter-chip-label {
            background: #fff4e6; color: var(--primary); border-color: var(--primary); font-weight: 600;
        }

        /* ====================
           2. ÜRÜN KARTLARI (RESPONSIVE GRID)
           ==================== */
        .product-grid {
            padding: 0 15px 15px 15px;
            display: grid;
            /* Mobilde 2'li, Tablette 3-4'lü, PC'de 5-6'lı otomatik sıralanır */
            grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
            gap: 15px;
        }

        /* Çok küçük ekranlar için tek sütun */
        @media (max-width: 380px) {
            .product-grid { grid-template-columns: 1fr; }
        }

        .app-card {
            background: var(--card-bg);
            border-radius: var(--radius);
            box-shadow: 0 2px 8px rgba(0,0,0,0.04);
            overflow: hidden;
            position: relative;
            transition: all 0.2s;
            border: 2px solid transparent; /* Seçim çerçevesi için yer */
        }

        .app-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        /* SEÇİLMİŞ KART STİLİ */
        .app-card.selected {
            border-color: var(--primary);
            background-color: #fffbf5;
        }

        .card-top {
            position: relative;
            height: 200px; /* Resim yüksekliği */
            background: #fff;
            cursor: pointer;
            border-bottom: 1px solid #f5f5f5;
        }

        .card-img {
            width: 100%;
            height: 100%;
            object-fit: contain;
            padding: 10px;
        }

        /* Seçim Tik İşareti */
        .card-select-overlay {
            position: absolute;
            top: 10px; left: 10px;
            width: 28px; height: 28px;
            border-radius: 50%;
            background: rgba(255,255,255,0.9);
            border: 2px solid #ddd;
            display: flex; align-items: center; justify-content: center;
            transition: all 0.2s;
            z-index: 10;
        }

        .app-card.selected .card-select-overlay {
            background: var(--primary);
            border-color: var(--primary);
            color: #fff;
        }
        .card-select-overlay i { display: none; font-size: 14px; }
        .app-card.selected .card-select-overlay i { display: block; }

        .card-body { padding: 12px; cursor: pointer; }

        .card-brand {
            font-size: 11px; font-weight: 700; color: #999; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 2px;
        }
        .card-title {
            font-size: 14px; color: var(--text-main); font-weight: 500;
            margin-bottom: 8px; line-height: 1.3;
            display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; height: 36px;
        }

        .card-price-row { display: flex; align-items: flex-end; gap: 8px; margin-bottom: 10px; }
        .price-current { font-size: 18px; font-weight: 700; color: var(--text-main); }
        .price-old { font-size: 12px; text-decoration: line-through; color: #ccc; padding-bottom: 2px; }
        .price-discount { color: var(--danger); font-size: 18px; font-weight: 700; }

        .card-status-row {
            display: flex; gap: 4px; flex-wrap: wrap; margin-top: 8px; border-top: 1px solid #f5f5f5; padding-top: 8px;
        }

        .status-badge {
            font-size: 10px; padding: 2px 6px; border-radius: 4px; font-weight: 600;
            background: #eee; color: #777;
        }
        .status-badge.active { background: #e8f5e9; color: var(--success); }
        .status-badge.error { background: #ffebee; color: var(--danger); }

        .card-link-btn {
            position: absolute; top: 10px; right: 10px;
            width: 32px; height: 32px; border-radius: 50%;
            background: #fff; box-shadow: 0 2px 5px rgba(0,0,0,0.15);
            display: flex; align-items: center; justify-content: center;
            color: #555; z-index: 20; transition: color 0.2s;
        }
        .card-link-btn:hover { color: var(--primary); }

        /* ====================
           3. STICKY BOTTOM BAR
           ==================== */
        .app-bottom-bar {
            position: fixed;
            bottom: 0; left: 0; right: 0;
            background: #fff;
            padding: 10px 20px;
            box-shadow: 0 -5px 20px rgba(0,0,0,0.05);
            display: flex;
            align-items: center;
            justify-content: space-between;
            z-index: 9999; /* En üstte */
            gap: 15px;
            border-top: 1px solid #eee;
        }

        /* Eğer masaüstünde sol menü açıksa, barın altında kalmaması için soldan pay verilebilir
           Ancak Opencart temalarında #content dinamik olduğu için %100 width en garantisidir. */

        .select-all-container {
            display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 13px; color: #555;
        }

        .switch { position: relative; display: inline-block; width: 44px; height: 26px; }
        .switch input { opacity: 0; width: 0; height: 0; }
        .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .3s; border-radius: 26px; }
        .slider:before { position: absolute; content: ""; height: 20px; width: 20px; left: 3px; bottom: 3px; background-color: white; transition: .3s; border-radius: 50%; }
        input:checked + .slider { background-color: var(--primary); }
        input:checked + .slider:before { transform: translateX(18px); }

        .btn-app-sell {
            min-width: 180px;
            background: var(--primary);
            color: #fff;
            border: none;
            padding: 12px 20px;
            border-radius: 8px;
            font-weight: 700;
            font-size: 15px;
            box-shadow: 0 4px 15px rgba(242, 122, 26, 0.3);
            display: flex; align-items: center; justify-content: center; gap: 10px;
            transition: transform 0.1s;
        }
        .btn-app-sell:active { transform: scale(0.98); }
        .btn-app-sell:hover { background: var(--primary-dark); color: #fff; }
        .btn-app-sell:disabled { background: #e0e0e0; color:#999; box-shadow: none; cursor: not-allowed; }

        .app-pagination { padding: 0 15px 20px; text-align: center; }
        .app-pagination .pagination { display: inline-flex; margin: 0; }
        .app-pagination .pagination > li > a, .app-pagination .pagination > li > span {
            border: none; background: transparent; color: #777; font-weight: 600; font-size: 16px; padding: 6px 12px;
        }
        .app-pagination .pagination > .active > span { color: var(--primary); background: transparent; font-size: 18px; }
    </style>

    <form action="{{ delete }}" method="post" enctype="multipart/form-data" id="form-product">

        <div class="app-header">
            <div class="search-container">
                <div class="search-input-group">
                    <i class="fa fa-search"></i>
                    <input type="text" name="filter_name" value="{{ filter_name }}" class="app-search-input" placeholder="Ürün Ara (İsim, Model, Barkod)...">
                </div>
                <button type="button" class="btn-filter-toggle" onclick="$('.filter-drawer').slideToggle(200);">
                    <i class="fa fa-sliders"></i>
                </button>
            </div>
            <button type="button" id="button-filter-app" class="btn btn-primary btn-block btn-sm" style="margin-top:15px; border-radius:6px;">ARAMA YAP</button>

            <div class="filter-drawer">
                <div style="font-size:11px; font-weight:700; color:#999; margin-bottom:5px; text-transform:uppercase;">Hızlı Filtreler</div>
                <div class="filter-chip-group">
                    <label>
                        <input type="checkbox"  name="filter_category" class="filter-chip-input hidden" {% if filter_category %} checked {% endif %}>
                        <span class="filter-chip-label">Kategori</span>
                    </label>
                    <label>
                        <input type="checkbox" name="filter_manufacturer" class="filter-chip-input hidden" {% if filter_manufacturer %} checked {% endif %}>
                        <span class="filter-chip-label">Marka</span>
                    </label>
                    <label>
                        <input type="checkbox" name="filter_seller" class="filter-chip-input hidden" {% if filter_seller %} checked {% endif %}>
                        <span class="filter-chip-label">Satıcı</span>
                    </label>
                    <label>
                        <input type="checkbox" checked  name="filter_special" class="filter-chip-input hidden" {% if filter_special %} checked {% endif %}>
                        <span class="filter-chip-label">Özel Sorgu</span>
                    </label>
                </div>
            </div>
        </div>

        <div class="product-grid">
            {% if products %}
                {% for key, product in products %}
                    {% set ui = product.url_info ? product.url_info : {} %}

                    <div class="app-card product-card-js {% if product.url in selected %}selected{% endif %}"
                         data-url="{{ product.url }}"
                         id="card-{{ key }}">

                        <input type="checkbox" class="hidden-checkbox" name="selected[]" value="{{ product.url }}"
                               style="display:none;"
                                {% if product.url in selected %} checked="checked" {% endif %} />

                        <div class="card-top" onclick="toggleCardSelection('{{ key }}')">
                            <div class="card-select-overlay">
                                <i class="fa fa-check"></i>
                            </div>
                            {% if product.images[0] %}
                                <img src="https://cdn.dsmcdn.com/{{ product.images[0] }}" class="card-img" loading="lazy">
                            {% else %}
                                <div style="display:flex; align-items:center; justify-content:center; height:100%; color:#ccc;"><i class="fa fa-camera fa-2x"></i></div>
                            {% endif %}
                        </div>

                        <a href="http://www.trendyol.com/{{ product.url }}" target="_blank" class="card-link-btn" title="Trendyol'da Git">
                            <i class="fa fa-external-link"></i>
                        </a>

                        <div class="card-body" onclick="toggleCardSelection('{{ key }}')">
                            <div class="card-brand">{{ product.brand.name }}</div>
                            <div class="card-title">{{ product.name }}</div>

                            <div class="card-price-row">
                                {% if product.variants[0].price.discountedPrice != product.variants[0].price.sellingPrice %}
                                    <span class="price-discount">{{ product.variants[0].price.discountedPrice }} <small>TL</small></span>
                                    <span class="price-old">{{ product.variants[0].price.sellingPrice }}</span>
                                {% else %}
                                    <span class="price-current">{{ product.variants[0].price.sellingPrice }} <small>TL</small></span>
                                {% endif %}
                            </div>

                            <div style="display:flex; justify-content:space-between; align-items:center;">
                                <span class="label label-default" style="font-size:10px; opacity:0.7;">{{ product.categoryName }}</span>
                                <div style="font-size:10px; color:#999;">
                                    <i class="fa fa-star text-warning"></i> {{ product.ratingScore.averageRating|number_format(1) }}
                                </div>
                            </div>

                            <div class="card-status-row sell-status" data-url="{{ product.url }}">
                                {% if ui.ty %}<span class="status-badge active" data-market="ty">TY</span>{% endif %}
                                {% if ui.hb %}<span class="status-badge active" data-market="hb">HB</span>{% endif %}
                                {% if ui.cs %}<span class="status-badge active" data-market="cs">CS</span>{% endif %}
                                {% if ui.pz %}<span class="status-badge active" data-market="pz">PZ</span>{% endif %}
                                {% if ui.n11 %}<span class="status-badge active" data-market="n11">N11</span>{% endif %}
                            </div>
                        </div>
                    </div>
                {% endfor %}
            {% else %}
                <div style="grid-column: 1/-1; text-align:center; padding:80px 20px; color:#999;">
                    <i class="fa fa-search fa-4x" style="color:#eee;"></i><br><br>
                    <h4 style="color:#777;">Ürün bulunamadı</h4>
                    <p>Arama kriterlerinizi değiştirip tekrar deneyin.</p>
                </div>
            {% endif %}
        </div>

        <div class="app-pagination">
            {{ pagination }}
        </div>

        <div class="app-bottom-bar">
            <div class="select-all-container">
                <label class="switch">
                    <input type="checkbox" id="app-select-all">
                    <span class="slider"></span>
                </label>
                <span id="selected-text" class="hidden-xs">Tümünü Seç</span>
            </div>

            <button type="button" class="btn-app-sell btnSell" disabled>
                <i class="fa fa-bolt"></i> <span class="hidden-xs">SEÇİLİLERİ</span> SATIŞA AÇ
                <span class="badge" id="sell-count-badge" style="background:rgba(255,255,255,0.3); margin-left:5px; display:none;">0</span>
            </button>
        </div>

    </form>

    <div class="row">
        <div class="col-sm-6 text-center">
            <a class="btn" href="{{ previous_page }}"> &lt; Önceki Sayfa </a>
            <label class="label label-success">{{ current_page }}</label>
            <a class="btn" href="{{ next_page }}">Sonraki Sayfa &gt;</a>
        </div>
        <div class="col-sm-6 text-center">{{ results }}</div>
    </div>

</div>

<script>
    // 1. KART SEÇİM
    function toggleCardSelection(key) {
        var card = $('#card-' + key);
        var checkbox = card.find('.hidden-checkbox');

        var isSelected = !card.hasClass('selected');

        if (isSelected) {
            card.addClass('selected');
            checkbox.prop('checked', true);
            card.css('transform', 'scale(0.97)'); // Tıklama efekti
            setTimeout(()=> card.css('transform', 'scale(1)'), 150);
        } else {
            card.removeClass('selected');
            checkbox.prop('checked', false);
        }
        updateSelectionUI();
    }

    // 2. HEPSİNİ SEÇ / KALDIR
    $('#app-select-all').on('change', function() {
        var checked = $(this).is(':checked');
        if(checked) {
            $('.product-card-js').addClass('selected');
            $('.hidden-checkbox').prop('checked', true);
            $('#selected-text').text('Hepsini Kaldır');
        } else {
            $('.product-card-js').removeClass('selected');
            $('.hidden-checkbox').prop('checked', false);
            $('#selected-text').text('Tümünü Seç');
        }
        updateSelectionUI();
    });

    // 3. UI GÜNCELLEME
    function updateSelectionUI() {
        var count = $('.hidden-checkbox:checked').length;
        if(count > 0) {
            $('#sell-count-badge').text(count).show();
            $('.btn-app-sell').prop('disabled', false);
            $('#selected-text').text(count + ' Seçili');
        } else {
            $('#sell-count-badge').hide();
            $('.btn-app-sell').prop('disabled', true);
            $('#selected-text').text('Tümünü Seç');
        }
    }

    // 4. FİLTRELEME
    $('#button-filter-app').on('click', function() {
        var url = 'index.php?route=catalog/product_finder&user_token={{ user_token }}';
        var filter_name = $('input[name=\'filter_name\']').val();
        if (filter_name) url += '&filter_name=' + encodeURIComponent(filter_name);

        if ($('input[name=\'filter_category\']').is(':checked')) url += '&filter_category=1';
        if ($('input[name=\'filter_manufacturer\']').is(':checked')) url += '&filter_manufacturer=1';
        if ($('input[name=\'filter_special\']').is(':checked')) url += '&filter_special=1';
        if ($('input[name=\'filter_seller\']').is(':checked')) url += '&filter_seller=1';

        location = url;
    });

    $('.app-search-input').on('keydown', function(e) {
        if (e.keyCode == 13) $('#button-filter-app').trigger('click');
    });

    $(document).ready(function(){ updateSelectionUI(); });

    // ==============================================
    // SATIŞ İŞLEMLERİ (API)
    // ==============================================
    function applyMarketResult(results, marketKey) {
        if (!results) return;
        var label = marketKey.toUpperCase();
        Object.keys(results).forEach(function(url) {
            var item = results[url] || {};
            var $cardStatusRow = $('.sell-status[data-url="' + url + '"]');
            if ($cardStatusRow.length) {
                $cardStatusRow.find('[data-market="' + marketKey + '"]').remove();
                var cls = item.status ? 'active' : 'error';
                $cardStatusRow.append('<span class="status-badge '+cls+'" data-market="'+marketKey+'">'+label+'</span>');
            }
        });
    }

    function renderBulkResults(json) {
        applyMarketResult(json.hb_result, 'hb');
        applyMarketResult(json.ty_result, 'ty');
        applyMarketResult(json.cs_result, 'cs');
        applyMarketResult(json.pz_result, 'pz');
        applyMarketResult(json.n11_result, 'n11');
    }

    $('.btnSell').on('click', function (e) {
        e.preventDefault();
        var thisbtn = $(this);
        var originalContent = thisbtn.html();

        var url_list = [];
        $(".hidden-checkbox:checked").each(function () {
            url_list.push($(this).val());
        });

        if (url_list.length === 0) return;

        thisbtn.prop('disabled', true).html('<i class="fa fa-circle-o-notch fa-spin"></i> İşleniyor...');

        // Full Screen Loading
        var progressHTML = `
            <div id="app-process-overlay" style="position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(255,255,255,0.95); z-index:10000; display:flex; flex-direction:column; align-items:center; justify-content:center; padding:20px;">
                <div style="width:60px; height:60px; border:5px solid #f3f3f3; border-top-color:var(--primary); border-radius:50%; animation:spin 1s linear infinite;"></div>
                <h3 style="margin-top:20px; font-weight:700; color:#333;">Ürünler Satışa Açılıyor</h3>
                <p id="proc-status" style="color:#777; font-size:16px;">Başlıyor...</p>
                <div style="width:300px; max-width:100%; height:8px; background:#eee; border-radius:4px; margin-top:20px; overflow:hidden;">
                    <div id="proc-bar" style="width:0%; height:100%; background:var(--primary); transition:width 0.3s;"></div>
                </div>
                <button id="proc-cancel" class="btn btn-default" style="margin-top:30px; border-radius:20px; padding:8px 25px;">İptal Et</button>
            </div>
            <style>@keyframes spin { 100% { transform: rotate(360deg); } }</style>
        `;
        $('body').append(progressHTML);

        var total = url_list.length;
        var processed = 0;
        var isCancelled = false;

        $('#proc-cancel').click(function(){ isCancelled = true; $('#app-process-overlay').remove(); thisbtn.prop('disabled',false).html(originalContent); });

        var idx = 0;
        function processNext() {
            if(isCancelled) return;
            if(idx >= total) {
                $('#proc-status').html('<b style="color:green">İşlem Tamamlandı!</b>');
                $('#proc-bar').css('width', '100%');
                setTimeout(function(){
                    $('#app-process-overlay').fadeOut(function(){ $(this).remove(); });
                    thisbtn.prop('disabled',false).html(originalContent);
                }, 1200);
                return;
            }

            var url = url_list[idx];
            $('#proc-status').text( (idx+1) + " / " + total + " işleniyor...");
            var pct = ((idx+1) / total) * 100;
            $('#proc-bar').css('width', pct + '%');

            $.post('index.php?route=catalog/product_finder/sell_product&hediye={{ hediye }}&user_token={{ user_token }}',
                { url_list: [url] },
                function(json) {
                    if(isCancelled) return;
                    renderBulkResults(json);
                    idx++;
                    processNext();
                }, 'JSON'
            ).fail(function(){
                if(isCancelled) return;
                idx++;
                processNext();
            });
        }
        processNext();
    });
</script>
</div>
{{ footer }}