<?php
require_once __DIR__ . '/../header.php';
use Core\System\PluginManager;
use Core\System\SeoManager;
$socialStudioActive = PluginManager::isActive('SocialProductStudio');
?>

<div class="content-wrapper">
<section class="content pt-3">
<div class="container-fluid pb-5">

<!-- ��������������������������������������������������
     PAGE HEADER
�������������������������������������������������� -->
<div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
    <div>
        <h3 class="mb-1 fw-bold">
            <i class="bi bi-box-seam me-2 text-primary"></i>
            <?= __('products.all_products','All Products') ?>
        </h3>
        <p class="text-muted mb-0 small">
            <?= __('products.subtitle','Manage your products and product pages') ?>
        </p>
    </div>
    <a href="/admin/products/create" class="btn btn-primary">
        <i class="bi bi-plus-lg me-1"></i>
        <?= __('products.add_product','Add Product') ?>
    </a>
</div>

<!-- ��������������������������������������������������
     FILTERS + SEARCH
�������������������������������������������������� -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-body py-3">
        <form method="GET" action="/admin/products" class="row g-2 align-items-end">
            <div class="col-md-5">
                <div class="input-group input-group-sm">
                    <span class="input-group-text bg-white"><i class="bi bi-search text-muted"></i></span>
                    <input type="text" name="search" class="form-control border-start-0"
                           placeholder="<?= __('products.search_placeholder','Search by name...') ?>"
                           value="<?= htmlspecialchars($_GET['search'] ?? '') ?>">
                </div>
            </div>
            <div class="col-md-2">
                <select name="status" class="form-select form-select-sm">
                    <option value=""><?= __('products.all_statuses','All statuses') ?></option>
                    <option value="active"    <?= ($_GET['status']??'')==='active'    ? 'selected':'' ?>><?= __('actions.active','Active') ?></option>
                    <option value="inactive"  <?= ($_GET['status']??'')==='inactive'  ? 'selected':'' ?>><?= __('actions.inactive','Inactive') ?></option>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-sm btn-primary w-100">
                    <i class="bi bi-funnel me-1"></i><?= __('actions.filter','Filter') ?>
                </button>
            </div>
            <?php if (!empty($_GET['search']) || !empty($_GET['status'])): ?>
            <div class="col-md-1">
                <a href="/admin/products" class="btn btn-sm btn-outline-secondary w-100">
                    <i class="bi bi-x-lg"></i>
                </a>
            </div>
            <?php endif; ?>
        </form>
    </div>
</div>

<!-- ��������������������������������������������������
     TABLE
�������������������������������������������������� -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
        <h6 class="mb-0 fw-semibold">
            <i class="bi bi-list-ul me-2 text-muted"></i>
            <?= __('products.list_title','Products List') ?>
        </h6>
        <span class="badge bg-secondary rounded-pill"><?= count($products) ?> <?= __('products.count_label','Products') ?></span>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th class="ps-3" style="width:64px"><?= __('products.table.image','Image') ?></th>
                        <th><?= __('products.table.name','Product Name') ?></th>
                        <th><?= __('products.table.price','Price') ?></th>
                        <th><?= __('products.table.status','Status') ?></th>
                        <th class="text-end pe-3"><?= __('products.table.actions','Actions') ?></th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($products)): ?>
                    <tr>
                        <td colspan="5">
                            <div class="text-center py-5">
                                <i class="bi bi-box-seam display-5 text-muted mb-3 d-block opacity-50"></i>
                                <h5 class="mb-1 fw-semibold"><?= __('products.empty_title','No products yet') ?></h5>
                                <p class="text-muted small mb-3"><?= __('products.empty_text','Start by adding your first product.') ?></p>
                                <a href="/admin/products/create" class="btn btn-primary btn-sm">
                                    <i class="bi bi-plus-lg me-1"></i><?= __('products.add_product','Add Product') ?>
                                </a>
                            </div>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($products as $product): ?>
                    <tr class="product-row" style="cursor:pointer" data-edit-url="/admin/products/edit/<?= (int)$product['id'] ?>">
                        <!-- Image -->
                        <td class="ps-3">
                            <?php if (!empty($product['featured_image'])): ?>
                                <img src="<?= htmlspecialchars($product['featured_image']) ?>"
                                     class="rounded-2" style="width:48px;height:48px;object-fit:cover;">
                            <?php else: ?>
                                <div class="bg-light rounded-2 d-flex align-items-center justify-content-center"
                                     style="width:48px;height:48px;">
                                    <i class="bi bi-image text-muted"></i>
                                </div>
                            <?php endif; ?>
                        </td>

                        <!-- Name -->
                        <td>
                            <div class="fw-semibold"><?= htmlspecialchars($product['title']) ?></div>
                            <?php if (!empty($product['sku'])): ?>
                                <div class="text-muted smaller">SKU: <?= htmlspecialchars($product['sku']) ?></div>
                            <?php endif; ?>
                            <?php if (!empty($product['is_featured'])): ?>
                                <span class="badge bg-warning-subtle text-warning border border-warning-subtle small">
                                    <i class="bi bi-star-fill me-1"></i><?= __('products.featured','Featured') ?>
                                </span>
                            <?php endif; ?>
                        </td>

                        <!-- Price -->
                        <td>
                            <span class="fw-semibold"><?= number_format((float)$product['price']) ?></span>
                            <small class="text-muted ms-1"><?= __('finance.currency','DZD') ?></small>
                            <?php if (!empty($product['sale_price']) && $product['sale_price'] < $product['price']): ?>
                                <div class="text-danger smaller">
                                    <i class="bi bi-tag-fill me-1"></i><?= number_format((float)$product['sale_price']) ?>
                                </div>
                            <?php endif; ?>
                        </td>

                        <!-- Status -->
                        <td>
                            <?php if ($product['status'] === 'active'): ?>
                                <span class="badge bg-success-subtle text-success border border-success-subtle">
                                    <i class="bi bi-check-circle me-1"></i><?= __('actions.active','Active') ?>
                                </span>
                            <?php else: ?>
                                <span class="badge bg-secondary-subtle text-secondary border border-secondary-subtle">
                                    <i class="bi bi-pause-circle me-1"></i><?= __('actions.inactive','Inactive') ?>
                                </span>
                            <?php endif; ?>
                        </td>

                        <!-- Actions -->
                        <td class="text-end pe-3">
                            <div class="d-flex gap-1 justify-content-end">
                                <?php if ($socialStudioActive): ?>
                                <a href="/admin/social-studio/<?= (int)$product['id'] ?>"
                                   class="btn btn-sm btn-outline-success"
                                   title="<?= __('social_studio.open','Open Social Studio') ?>">
                                    <i class="bi bi-megaphone"></i>
                                </a>
                                <?php endif; ?>

                                <?php $publicUrl = SeoManager::absoluteUrl('/product/' . rawurlencode($product['slug'] ?? (string)(int)$product['id'])); ?>
                                <button type="button"
                                        class="btn btn-sm btn-outline-secondary js-share-product"
                                        data-title="<?= htmlspecialchars($product['title'], ENT_QUOTES) ?>"
                                        data-share-url="<?= htmlspecialchars($publicUrl, ENT_QUOTES) ?>"
                                        data-image="<?= htmlspecialchars($product['og_image'] ?? ($product['featured_image'] ?? ''), ENT_QUOTES) ?>"
                                        title="<?= __('actions.share','Share') ?>">
                                    <i class="bi bi-share"></i>
                                </button>

                                <a href="/admin/products/edit/<?= (int)$product['id'] ?>"
                                   class="btn btn-sm btn-outline-primary"
                                   title="<?= __('actions.edit','Edit') ?>">
                                    <i class="bi bi-pencil"></i>
                                </a>

                                <form method="post" action="/admin/products/delete/<?= (int)$product['id'] ?>" class="d-inline" onsubmit="return confirm('<?= __('actions.confirm_delete','Are you sure?') ?>')">
                                    <?= \Core\System\Csrf::field() ?>
                                    <button type="submit" class="btn btn-sm btn-outline-danger" title="<?= __('actions.delete','Delete') ?>">
                                        <i class="bi bi-trash3"></i>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

</div>
</section>
</div>

<div class="modal fade" id="shareModal" tabindex="-1" aria-hidden="true" aria-labelledby="shareModalTitle">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content share-modal-shell border-0 shadow-lg overflow-hidden">
            <div class="share-modal-hero p-4 pb-3">
                <div class="d-flex align-items-start justify-content-between gap-3">
                    <div>
                        <div class="text-uppercase small fw-semibold opacity-75 mb-2"><?= __('actions.share','Share') ?></div>
                        <h5 class="modal-title fw-bold mb-1" id="shareModalTitle"><?= __('products.share_product','Share product') ?></h5>
                        <p class="mb-0 small opacity-75"><?= __('products.share_modal_subtitle', 'Use the product link below for Facebook, WhatsApp and the rest of your channels.') ?></p>
                    </div>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
            </div>

            <div class="modal-body p-4">
                <div class="share-product-panel rounded-4 p-3 mb-4">
                    <div class="d-flex flex-column flex-md-row gap-3 align-items-md-center">
                        <div class="share-product-thumb rounded-4 overflow-hidden bg-white border flex-shrink-0 d-flex align-items-center justify-content-center">
                            <img id="shareProductImage" src="" alt="" class="w-100 h-100 object-fit-cover d-none">
                            <i id="shareProductPlaceholder" class="bi bi-image text-muted fs-2"></i>
                        </div>
                        <div class="flex-grow-1 min-w-0">
                            <div class="d-flex flex-wrap gap-2 mb-2">
                                <span class="badge rounded-pill text-bg-light border"><?= __('products.share_ready_badge', 'Ready to share') ?></span>
                                <span class="badge rounded-pill text-bg-light border"><i class="bi bi-link-45deg me-1"></i><?= __('products.product_link','Product Link') ?></span>
                            </div>
                            <div id="shareProductTitle" class="share-product-title fw-bold mb-2"></div>
                            <div class="text-muted small mb-3" id="shareProductHint"><?= __('products.share_preview_hint', 'Social platforms will read this exact product page link.') ?></div>
                            <div class="d-flex flex-wrap gap-2">
                                <a id="shareOpenLink" href="#" target="_blank" rel="noopener" class="btn btn-outline-primary btn-sm">
                                    <i class="bi bi-box-arrow-up-right me-1"></i><?= __('products.open_product_page','Open product page') ?>
                                </a>
                                <button type="button" class="btn btn-primary btn-sm" id="shareCopyBtn">
                                    <i class="bi bi-clipboard me-1"></i><?= __('actions.copy','Copy') ?>
                                </button>
                                <button type="button" class="btn btn-outline-dark btn-sm d-none" id="shareNativeBtn">
                                    <i class="bi bi-send me-1"></i><?= __('products.native_share','Share now') ?>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label small text-muted mb-2"><?= __('products.product_link','Product Link') ?></label>
                    <div class="share-link-box rounded-4 px-3 py-2 d-flex align-items-center gap-2">
                        <i class="bi bi-link-45deg text-primary"></i>
                        <input type="text" class="form-control border-0 bg-transparent px-0" id="shareProductUrl" readonly>
                    </div>
                </div>

                <div class="share-network-grid row g-3" id="shareButtons"></div>
            </div>
        </div>
    </div>
</div>
<style>
    #shareModal .modal-content { border-radius: 1.5rem; }
    .share-modal-shell { background: #fff; }
    .share-modal-hero { background: linear-gradient(135deg, #111827 0%, #1f2937 100%); color: #fff; }
    .share-product-panel { background: linear-gradient(180deg, rgba(37,99,235,.06), rgba(15,23,42,.03)); border: 1px solid rgba(15,23,42,.08); }
    .share-product-thumb { width: 104px; height: 104px; box-shadow: 0 .75rem 1.5rem rgba(15,23,42,.08); }
    .share-product-title { font-size: 1.05rem; line-height: 1.45; color: #111827; }
    .share-link-box { background: #f8fafc; border: 1px solid rgba(15,23,42,.08); }
    .share-link-box input { box-shadow: none !important; }
    #shareButtons .share-network { display:flex; align-items:center; justify-content:space-between; gap:1rem; padding:1rem 1.1rem; border:1px solid rgba(15,23,42,.08); border-radius:1rem; text-decoration:none; color:inherit; background:#fff; transition:all .18s ease; height:100%; }
    #shareButtons .share-network:hover { transform:translateY(-1px); box-shadow:0 .9rem 1.7rem rgba(15,23,42,.08); border-color:rgba(37,99,235,.18); }
    #shareButtons .share-network-main { display:flex; align-items:center; gap:.85rem; min-width:0; }
    #shareButtons .share-network i { font-size:1.25rem; }
    #shareButtons .share-label { display:flex; flex-direction:column; line-height:1.15; min-width:0; }
    #shareButtons .share-label span { font-weight: 600; color: #111827; }
    #shareButtons .share-label small { color:#6b7280; }
    #shareButtons .share-arrow { color:#9ca3af; }
</style>

<script>
(function () {

    /* ── double-click → edit ──────────────────────────────────────────── */
    document.querySelectorAll('.product-row').forEach(function (tr) {
        tr.addEventListener('dblclick', function (e) {
            if (e.target.closest('a, button, form')) return; // لا تتعارض مع الأزرار
            window.location.href = tr.dataset.editUrl;
        });
    });

    /* ── share button ─────────────────────────────────────────────────── */
    var shareModal = document.getElementById('shareModal');
    var shareButtons = document.getElementById('shareButtons');
    var shareProductUrl = document.getElementById('shareProductUrl');
    var shareProductTitle = document.getElementById('shareProductTitle');
    var shareProductImage = document.getElementById('shareProductImage');
    var shareProductPlaceholder = document.getElementById('shareProductPlaceholder');
    var shareOpenLink = document.getElementById('shareOpenLink');
    var shareCopyBtn = document.getElementById('shareCopyBtn');
    var shareNativeBtn = document.getElementById('shareNativeBtn');
    var shareModalInstance = null;
    if (shareModal && window.bootstrap && typeof window.bootstrap.Modal === 'function') {
        shareModalInstance = window.bootstrap.Modal.getOrCreateInstance(shareModal);
    }
    var copiedLabel = <?= json_encode(__('actions.copied','Copied!')) ?>;
    var copyLabel = <?= json_encode(__('actions.copy','Copy')) ?>;

    function absoluteUrl(path) {
        if (!path) return '';
        if (/^https?:\/\//i.test(path)) return path;
        return window.location.origin + '/' + String(path).replace(/^\/+/, '');
    }

    function copyShareUrl(url) {
        if (!url) return;
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(url).then(function () {
                shareCopyBtn.innerHTML = '<i class=\"bi bi-check2-circle me-1\"></i>' + copiedLabel;
                setTimeout(function () {
                    shareCopyBtn.innerHTML = '<i class=\"bi bi-clipboard me-1\"></i>' + copyLabel;
                }, 1800);
            });
            return;
        }
        window.prompt('<?= __('products.product_link','Product Link') ?>', url);
    }

    var networks = [
        { name: 'WhatsApp', icon: 'bi-whatsapp', color: '#25D366', note: <?= json_encode(__('products.share_channel_whatsapp', 'Chats & status')) ?>, build: function(t,u){ return 'https://wa.me/?text=' + encodeURIComponent(t + '\n' + u); } },
        { name: 'Facebook', icon: 'bi-facebook', color: '#1877F2', note: <?= json_encode(__('products.share_channel_facebook', 'Feed & story')) ?>, build: function(t,u){ return 'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(u); } },
        { name: 'X', icon: 'bi-twitter-x', color: '#111827', note: <?= json_encode(__('products.share_channel_x', 'Post with link')) ?>, build: function(t,u){ return 'https://twitter.com/intent/tweet?text=' + encodeURIComponent(t) + '&url=' + encodeURIComponent(u); } },
        { name: 'Telegram', icon: 'bi-telegram', color: '#229ED9', note: <?= json_encode(__('products.share_channel_telegram', 'Channels & chats')) ?>, build: function(t,u){ return 'https://t.me/share/url?url=' + encodeURIComponent(u) + '&text=' + encodeURIComponent(t); } },
    ];

    document.querySelectorAll('.js-share-product').forEach(function (btn) {
        btn.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            var title = btn.dataset.title || '';
            var url = btn.dataset.shareUrl || '';
            var image = absoluteUrl(btn.dataset.image || '');

            shareProductTitle.textContent = title;
            shareProductUrl.value = url;
            shareOpenLink.href = url;
            shareOpenLink.title = url;

            if (image) {
                shareProductImage.src = image;
                shareProductImage.alt = title;
                shareProductImage.classList.remove('d-none');
                shareProductPlaceholder.classList.add('d-none');
            } else {
                shareProductImage.src = '';
                shareProductImage.alt = '';
                shareProductImage.classList.add('d-none');
                shareProductPlaceholder.classList.remove('d-none');
            }

            shareButtons.innerHTML = '';
            networks.forEach(function (net) {
                var href = net.build(title, url);
                var col = document.createElement('div');
                col.className = 'col-md-6';

                var el = document.createElement('a');
                el.href = href;
                el.target = '_blank';
                el.rel = 'noopener';
                el.className = 'share-network';
                el.innerHTML = '<span class="share-network-main">' +
                    '<i class="bi ' + net.icon + '" style="color:' + net.color + '"></i>' +
                    '<span class="share-label"><span>' + net.name + '</span><small>' + net.note + '</small></span>' +
                    '</span>' +
                    '<i class="bi bi-arrow-up-right-circle share-arrow"></i>';
                col.appendChild(el);
                shareButtons.appendChild(col);
            });

            shareCopyBtn.onclick = function () { copyShareUrl(url); };
            if (shareNativeBtn) {
                if (navigator.share) {
                    shareNativeBtn.classList.remove('d-none');
                    shareNativeBtn.onclick = function () { navigator.share({ title: title, text: title, url: url }); };
                } else {
                    shareNativeBtn.classList.add('d-none');
                    shareNativeBtn.onclick = null;
                }
            }
            if (shareModalInstance) {
                shareModalInstance.show();
            } else if (shareModal) {
                shareModal.classList.add('show');
                shareModal.style.display = 'block';
                shareModal.removeAttribute('aria-hidden');
                document.body.classList.add('modal-open');
            } else {
                window.prompt('<?= __('products.product_link','Product Link') ?>', url);
            }
        });
    });

    if (shareModal) {
        shareModal.addEventListener('click', function (e) {
            if (e.target.matches('[data-bs-dismiss="modal"]') || e.target === shareModal) {
                if (shareModalInstance) {
                    shareModalInstance.hide();
                } else {
                    shareModal.classList.remove('show');
                    shareModal.style.display = 'none';
                    shareModal.setAttribute('aria-hidden', 'true');
                    document.body.classList.remove('modal-open');
                }
            }
        });
    }

})();
</script>

<?php if (($totalPages ?? 1) > 1): ?>
<div class="d-flex justify-content-center align-items-center gap-2 py-3 px-4">
    <?php
    $baseUrl = '/admin/products';
    $qs = $_GET;
    ?>
    <?php if (($currentPage ?? 1) > 1): ?>
        <?php $qs['page'] = ($currentPage ?? 1) - 1; ?>
        <a href="<?= $baseUrl . '?' . http_build_query($qs) ?>" class="btn btn-sm btn-outline-secondary">
            &laquo; <?= __('pagination.prev', 'Previous') ?>
        </a>
    <?php endif; ?>

    <span class="text-muted small">
        <?= __('pagination.page_of', 'Page') ?> <?= ($currentPage ?? 1) ?> / <?= ($totalPages ?? 1) ?>
        &nbsp;(<?= number_format($totalProducts ?? 0) ?> <?= __('products.total_count', 'products') ?>)
    </span>

    <?php if (($currentPage ?? 1) < ($totalPages ?? 1)): ?>
        <?php $qs['page'] = ($currentPage ?? 1) + 1; ?>
        <a href="<?= $baseUrl . '?' . http_build_query($qs) ?>" class="btn btn-sm btn-outline-secondary">
            <?= __('pagination.next', 'Next') ?> &raquo;
        </a>
    <?php endif; ?>
</div>
<?php endif; ?>

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