<?php include __DIR__ . '/../layout/header.php'; ?>

<?php
$imageBase = \App\Models\Settings::get('image_base_url', $baseUrl . '/image');

function pSortUrl($field, $currentSort, $currentOrder, $search) {
    $ord = ($currentSort === $field && $currentOrder === 'asc') ? 'desc' : 'asc';
    $q   = 'sort=' . $field . '&order=' . $ord;
    if ($search !== '') $q .= '&search=' . urlencode($search);
    return '?' . $q;
}
function pSortIcon($field, $currentSort, $currentOrder) {
    if ($currentSort !== $field) return '<i class="fa fa-sort" style="opacity:.3;font-size:10px;"></i>';
    return $currentOrder === 'asc'
        ? '<i class="fa fa-sort-asc" style="color:var(--primary);font-size:11px;"></i>'
        : '<i class="fa fa-sort-desc" style="color:var(--primary);font-size:11px;"></i>';
}
$qs = '';
if ($search !== '') $qs .= '&search=' . urlencode($search);
if ($sort !== '')   $qs .= '&sort=' . $sort . '&order=' . $order;
?>

<!-- ─── Toolbar ─── -->
<div class="page-toolbar">
    <form method="GET" action="<?php echo $baseUrl; ?>/admin/products" id="product-search-form" class="search-bar" style="max-width:480px;">
        <i class="fa fa-search search-icon"></i>
        <input type="text" name="search" id="product-search-input"
               value="<?php echo htmlspecialchars($search); ?>"
               placeholder="Ürün adı, model veya marka ara..."
               autocomplete="off">
        <?php if ($search !== ''): ?>
        <a href="<?php echo $baseUrl; ?>/admin/products" class="search-clear-btn"><i class="fa fa-times"></i></a>
        <?php endif; ?>
    </form>

    <div class="header-spacer"></div>

    <a href="<?php echo $baseUrl; ?>/admin/products/create" class="admin-btn admin-btn-primary">
        <i class="fa fa-plus-circle"></i> Yeni Ürün
    </a>
</div>

<!-- ─── Main Card ─── -->
<div class="admin-card" style="padding:0;overflow:hidden;">

    <?php if (!empty($products)): ?>

    <!-- Bulk Bar -->
    <div class="bulk-bar" id="bulkBar" style="margin:16px 16px 0;border-radius:var(--r-md);">
        <div style="font-size:13.5px;font-weight:700;color:var(--text-1);">
            <span id="selectedCount">0</span> ürün seçildi
        </div>
        <div style="display:flex;gap:8px;flex-wrap:wrap;">
            <button class="admin-btn admin-btn-sm admin-btn-success" onclick="performBulkAction('status_active')">
                <i class="fa fa-check"></i> Aktif Yap
            </button>
            <button class="admin-btn admin-btn-sm" onclick="performBulkAction('status_inactive')">
                <i class="fa fa-times"></i> Pasif Yap
            </button>
            <button class="admin-btn admin-btn-sm admin-btn-danger" onclick="performBulkAction('delete')">
                <i class="fa fa-trash"></i> Sil
            </button>
        </div>
    </div>

    <!-- DESKTOP TABLE -->
    <div class="admin-table-wrap desktop-only" style="border:none;border-radius:0;">
        <table class="admin-table products-table">
            <thead>
                <tr>
                    <th style="width:36px;"><input type="checkbox" id="selectAllProducts" style="cursor:pointer;accent-color:var(--primary);"></th>
                    <th style="width:48px;">Görsel</th>
                    <th><a href="<?php echo pSortUrl('name', $sort, $order, $search); ?>" style="color:inherit;text-decoration:none;display:inline-flex;align-items:center;gap:5px;">Ürün Adı <?php echo pSortIcon('name', $sort, $order); ?></a></th>
                    <th style="width:90px;"><a href="<?php echo pSortUrl('brand_slug', $sort, $order, $search); ?>" style="color:inherit;text-decoration:none;display:inline-flex;align-items:center;gap:5px;">Marka <?php echo pSortIcon('brand_slug', $sort, $order); ?></a></th>
                    <th><a href="<?php echo pSortUrl('model', $sort, $order, $search); ?>" style="color:inherit;text-decoration:none;display:inline-flex;align-items:center;gap:5px;">Model <?php echo pSortIcon('model', $sort, $order); ?></a></th>
                    <th><a href="<?php echo pSortUrl('price', $sort, $order, $search); ?>" style="color:inherit;text-decoration:none;display:inline-flex;align-items:center;gap:5px;">Fiyat <?php echo pSortIcon('price', $sort, $order); ?></a></th>
                    <th><a href="<?php echo pSortUrl('stock', $sort, $order, $search); ?>" style="color:inherit;text-decoration:none;display:inline-flex;align-items:center;gap:5px;">Stok <?php echo pSortIcon('stock', $sort, $order); ?></a></th>
                    <th><a href="<?php echo pSortUrl('status', $sort, $order, $search); ?>" style="color:inherit;text-decoration:none;display:inline-flex;align-items:center;gap:5px;">Durum <?php echo pSortIcon('status', $sort, $order); ?></a></th>
                    <th style="width:44px;text-align:center;"><a href="<?php echo pSortUrl('featured', $sort, $order, $search); ?>" style="color:inherit;text-decoration:none;display:inline-flex;align-items:center;gap:3px;"><i class="fa fa-star"></i><?php echo pSortIcon('featured', $sort, $order); ?></a></th>
                    <th style="text-align:right;width:90px;">İşlemler</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($products as $prod): ?>
                <?php
                    $imgs    = $prod->getImages();
                    $mainImg = !empty($imgs) ? $baseUrl . $imgs[0] : '';
                    $brandSlug = $prod->brand_slug ?? '';
                    $brandName = '';
                    foreach ($brands as $b) {
                        if ($b['slug'] === $brandSlug) { $brandName = $b['name']; break; }
                    }
                ?>
                <tr>
                    <td style="text-align:center;"><input type="checkbox" class="product-checkbox" value="<?php echo $prod->id; ?>" style="cursor:pointer;accent-color:var(--primary);"></td>
                    <td>
                        <div style="width:44px;height:44px;background:var(--surface-2);border-radius:8px;overflow:hidden;display:flex;align-items:center;justify-content:center;border:1px solid var(--border);padding:2px;">
                            <?php if ($mainImg): ?>
                            <img src="<?php echo htmlspecialchars($mainImg); ?>" alt="" style="max-width:100%;max-height:100%;object-fit:contain;" loading="lazy">
                            <?php else: ?>
                            <i class="fa fa-image" style="color:var(--text-3);font-size:18px;"></i>
                            <?php endif; ?>
                        </div>
                    </td>
                    <td class="editable-field" data-id="<?php echo $prod->id; ?>" data-field="name" data-value="<?php echo htmlspecialchars($prod->name); ?>" title="Çift tıklayarak düzenleyin" style="font-weight:600;color:var(--text-1);cursor:pointer;">
                        <div class="editable-cell">
                            <span><?php echo htmlspecialchars($prod->name); ?></span>
                            <i class="fa fa-pencil"></i>
                        </div>
                    </td>
                    <td style="font-size:12px;color:var(--text-3);"><?php echo htmlspecialchars($brandName ?: '—'); ?></td>
                    <td class="editable-field" data-id="<?php echo $prod->id; ?>" data-field="model" data-value="<?php echo htmlspecialchars($prod->model); ?>" title="Çift tıklayarak düzenleyin" style="cursor:pointer;">
                        <div class="editable-cell">
                            <code style="background:var(--surface-2);color:var(--text-2);padding:3px 8px;border-radius:5px;font-size:11.5px;border:1px solid var(--border);"><?php echo htmlspecialchars($prod->model ?: '—'); ?></code>
                            <i class="fa fa-pencil"></i>
                        </div>
                    </td>
                    <td class="editable-field" data-id="<?php echo $prod->id; ?>" data-field="price" data-value="<?php echo htmlspecialchars($prod->price); ?>" title="Çift tıklayarak düzenleyin" style="font-weight:700;color:var(--primary);cursor:pointer;">
                        <div class="editable-cell">
                            <span><?php echo $prod->getOriginalPriceFormatted(); ?></span>
                            <i class="fa fa-pencil"></i>
                        </div>
                    </td>
                    <td class="editable-field" data-id="<?php echo $prod->id; ?>" data-field="stock" data-value="<?php echo htmlspecialchars($prod->stock); ?>" title="Çift tıklayarak düzenleyin" style="font-weight:600;cursor:pointer;">
                        <div class="editable-cell">
                            <span><?php echo $prod->stock; ?></span>
                            <i class="fa fa-pencil"></i>
                        </div>
                    </td>
                    <td>
                        <?php if ($prod->status == 1): ?>
                        <span class="status-badge badge-success">Aktif</span>
                        <?php else: ?>
                        <span class="status-badge badge-muted">Pasif</span>
                        <?php endif; ?>
                    </td>
                    <td style="text-align:center;">
                        <button class="star-toggle featured-toggle <?php echo ($prod->featured ?? 0) ? 'active' : ''; ?>"
                                data-id="<?php echo $prod->id; ?>"
                                data-featured="<?php echo (int)($prod->featured ?? 0); ?>"
                                title="Öne çıkar">
                            <i class="fa <?php echo ($prod->featured ?? 0) ? 'fa-star' : 'fa-star-o'; ?>"></i>
                        </button>
                    </td>
                    <td style="text-align:right;">
                        <div style="display:flex;gap:4px;justify-content:flex-end;">
                            <a href="<?php echo $baseUrl; ?>/admin/products/edit/<?php echo $prod->id; ?>" class="admin-action-btn edit" title="Düzenle">
                                <i class="fa fa-pencil"></i>
                            </a>
                            <button onclick="confirmDelete('<?php echo $baseUrl; ?>/admin/products/delete/<?php echo $prod->id; ?>')" class="admin-action-btn delete" title="Sil">
                                <i class="fa fa-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- MOBILE CARDS -->
    <div class="mobile-only" style="padding:12px;">
        <?php foreach ($products as $prod): ?>
        <?php
            $imgs    = $prod->getImages();
            $mainImg = !empty($imgs) ? $baseUrl . $imgs[0] : '';
            $brandSlug = $prod->brand_slug ?? '';
            $brandName = '';
            foreach ($brands as $b) {
                if ($b['slug'] === $brandSlug) { $brandName = $b['name']; break; }
            }
        ?>
        <div class="m-card">
            <div class="m-card-header">
                <div class="m-card-title-wrap">
                    <?php if ($mainImg): ?>
                    <img src="<?php echo htmlspecialchars($mainImg); ?>" class="m-card-img" alt="" loading="lazy">
                    <?php else: ?>
                    <div class="m-card-icon"><i class="fa fa-print"></i></div>
                    <?php endif; ?>
                    <div style="overflow:hidden;">
                        <h3 class="m-card-title"><?php echo htmlspecialchars($prod->name); ?></h3>
                        <p class="m-card-subtitle"><?php echo htmlspecialchars($brandName ?: ''); ?><?php if ($prod->model): ?> · <?php echo htmlspecialchars($prod->model); ?><?php endif; ?></p>
                    </div>
                </div>
                <div class="m-card-value" style="color:var(--primary);"><?php echo $prod->getOriginalPriceFormatted(); ?></div>
            </div>
            <div class="m-card-footer">
                <div class="m-card-badges">
                    <?php if ($prod->status == 1): ?>
                    <span class="m-badge m-badge-success">Aktif</span>
                    <?php else: ?>
                    <span class="m-badge m-badge-dark">Pasif</span>
                    <?php endif; ?>
                    <span class="m-badge m-badge-dark"><i class="fa fa-cubes"></i> <?php echo $prod->stock; ?> Stok</span>
                    <?php if ($prod->featured ?? 0): ?>
                    <span class="m-badge m-badge-warning"><i class="fa fa-star"></i> Öne Çıkan</span>
                    <?php endif; ?>
                </div>
                <div class="m-card-actions">
                    <a href="<?php echo $baseUrl; ?>/admin/products/edit/<?php echo $prod->id; ?>" class="m-action-btn edit"><i class="fa fa-pencil"></i></a>
                    <button onclick="confirmDelete('<?php echo $baseUrl; ?>/admin/products/delete/<?php echo $prod->id; ?>')" class="m-action-btn delete"><i class="fa fa-trash"></i></button>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Pagination -->
    <?php if (isset($totalPages) && $totalPages > 1): ?>
    <div class="pagination">
        <?php if ($currentPage > 1): ?>
        <a href="?page=<?php echo $currentPage - 1; ?><?php echo $qs; ?>"><i class="fa fa-chevron-left"></i></a>
        <?php endif; ?>
        <?php
        $start = max(1, $currentPage - 2);
        $end   = min($totalPages, $currentPage + 2);
        if ($start > 1) echo '<a href="?page=1'.$qs.'">1</a>';
        if ($start > 2) echo '<span style="background:none;border:none;color:var(--text-3);">…</span>';
        for ($i = $start; $i <= $end; $i++) {
            if ($i == $currentPage)
                echo '<span>' . $i . '</span>';
            else
                echo '<a href="?page='.$i.$qs.'">'.$i.'</a>';
        }
        if ($end < $totalPages - 1) echo '<span style="background:none;border:none;color:var(--text-3);">…</span>';
        if ($end < $totalPages) echo '<a href="?page='.$totalPages.$qs.'">'.$totalPages.'</a>';
        ?>
        <?php if ($currentPage < $totalPages): ?>
        <a href="?page=<?php echo $currentPage + 1; ?><?php echo $qs; ?>"><i class="fa fa-chevron-right"></i></a>
        <?php endif; ?>
    </div>
    <div style="text-align:center;padding-bottom:16px;font-size:12px;color:var(--text-3);">
        Toplam <strong><?php echo $totalProducts; ?></strong> ürün
        (Sayfa <?php echo $currentPage; ?>/<?php echo $totalPages; ?>)
    </div>
    <?php endif; ?>

    <?php else: ?>
    <div style="text-align:center;padding:64px 20px;color:var(--text-3);">
        <i class="fa fa-print" style="font-size:56px;opacity:0.15;display:block;margin-bottom:18px;"></i>
        <p style="font-size:15px;">Henüz hiç ürün eklenmemiş.</p>
        <a href="<?php echo $baseUrl; ?>/admin/products/create" class="admin-btn admin-btn-primary" style="margin-top:16px;">
            <i class="fa fa-plus-circle"></i> İlk Ürünü Ekle
        </a>
    </div>
    <?php endif; ?>

</div><!-- /.admin-card -->

<script>
/* ── Auto search ── */
initAutoSearch('product-search-input', 'product-search-form', 400);

/* ── Select all checkbox ── */
var selectAllCb = document.getElementById('selectAllProducts');
var productCbs  = document.querySelectorAll('.product-checkbox');
var bulkBar     = document.getElementById('bulkBar');
var countSpan   = document.getElementById('selectedCount');

function syncBulk() {
    var checked = document.querySelectorAll('.product-checkbox:checked').length;
    if (countSpan) countSpan.textContent = checked;
    if (bulkBar) bulkBar.classList.toggle('visible', checked > 0);
    if (selectAllCb) {
        selectAllCb.checked       = (checked === productCbs.length && productCbs.length > 0);
        selectAllCb.indeterminate = (checked > 0 && checked < productCbs.length);
    }
}

if (selectAllCb) {
    selectAllCb.addEventListener('change', function() {
        productCbs.forEach(function(cb) { cb.checked = selectAllCb.checked; });
        syncBulk();
    });
}
productCbs.forEach(function(cb) { cb.addEventListener('change', syncBulk); });

/* ── Delete confirm ── */
function confirmDelete(url) {
    adminConfirm('Bu ürünü kalıcı olarak silmek istiyor musunuz?', function() {
        window.location.href = url;
    });
}

/* ── Bulk actions ── */
async function performBulkAction(action) {
    var ids = Array.from(document.querySelectorAll('.product-checkbox:checked')).map(function(cb) { return cb.value; });
    if (!ids.length) return;

    var msg = action === 'delete'
        ? 'Seçilen ürünleri silmek istediğinize emin misiniz?'
        : (action === 'status_active' ? 'Seçilenleri aktif yapmak ister misiniz?' : 'Seçilenleri pasif yapmak ister misiniz?');

    adminConfirm(msg, async function() {
        try {
            var r = await fetch('<?php echo $baseUrl; ?>/admin/products/bulk-action', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: action, ids: ids })
            });
            var d = await r.json();
            if (d.success) {
                showToast(d.updatedCount + ' ürün güncellendi.', 'success');
                setTimeout(function() { window.location.reload(); }, 800);
            } else {
                showToast('Hata: ' + d.message, 'error');
            }
        } catch(e) {
            showToast('Bağlantı hatası!', 'error');
        }
    });
}

/* ── Inline edit (double-click) ── */
document.querySelectorAll('.editable-field').forEach(function(cell) {
    cell.addEventListener('dblclick', function() {
        if (this.querySelector('input')) return;
        var val   = this.getAttribute('data-value');
        var field = this.getAttribute('data-field');
        var id    = this.getAttribute('data-id');
        var span  = this.querySelector('span') || this.querySelector('code');
        var oldHtml = span ? span.outerHTML : this.innerHTML;

        var input = document.createElement('input');
        input.type  = (field === 'price' || field === 'stock') ? 'number' : 'text';
        if (field === 'price') input.step = '0.01';
        input.value = val;
        input.style.cssText = 'width:100%;max-width:200px;padding:4px 8px;border:1.5px solid var(--primary);border-radius:6px;background:var(--surface);color:var(--text-1);font-family:inherit;font-size:13px;outline:none;';

        var container = this.querySelector('.editable-cell') || this;
        container.innerHTML = '';
        container.appendChild(input);
        input.focus(); input.select();

        var cellRef = this;
        var save = async function() {
            var newVal = input.value.trim();
            if (newVal === val) { container.innerHTML = oldHtml; return; }
            container.innerHTML = '<i class="fa fa-spinner fa-spin" style="color:var(--text-3);"></i>';
            try {
                var r = await fetch('<?php echo $baseUrl; ?>/admin/products/update-field/' + id, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ field: field, value: newVal })
                });
                var d = await r.json();
                if (d.success) {
                    cellRef.setAttribute('data-value', d.newValue);
                    container.innerHTML = '<span>' + d.newFormatted + '</span><i class="fa fa-pencil"></i>';
                    showToast('Güncellendi.', 'success');
                } else {
                    showToast('Hata: ' + d.message, 'error');
                    container.innerHTML = oldHtml;
                }
            } catch(e) {
                showToast('Bağlantı hatası!', 'error');
                container.innerHTML = oldHtml;
            }
        };

        input.addEventListener('blur', save);
        input.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') input.blur();
            if (e.key === 'Escape') { container.innerHTML = oldHtml; }
        });
    });
});

/* ── Featured toggle ── */
document.querySelectorAll('.featured-toggle').forEach(function(btn) {
    btn.addEventListener('click', async function() {
        var id   = this.dataset.id;
        var icon = this.querySelector('i');
        try {
            var r = await fetch('<?php echo $baseUrl; ?>/admin/products/toggle-featured/' + id, { method: 'POST' });
            var d = await r.json();
            if (d.success) {
                var starred = !!d.featured;
                icon.className = 'fa ' + (starred ? 'fa-star' : 'fa-star-o');
                this.classList.toggle('active', starred);
                this.dataset.featured = starred ? '1' : '0';
            }
        } catch(e) { /* silent */ }
    });
});

/* ── Sticky thead ── */
(function() {
    var hdr = document.querySelector('.admin-header');
    var ths = document.querySelectorAll('.products-table thead th');
    if (!hdr || !ths.length) return;
    function setTop() { var t = hdr.offsetHeight; ths.forEach(function(th) { th.style.top = t + 'px'; }); }
    setTop();
    window.addEventListener('resize', setTop);
})();
</script>

<?php include __DIR__ . '/../layout/footer.php'; ?>
