<?= $this->include('partials/html') ?>

<head>
    <?php echo view("partials/title-meta", array("title" => $title)) ?>
    <?= $this->include('partials/head-css') ?>
    <link rel="stylesheet" href="/vendor/select2/select2.min.css">
    <style>
        .vs-container { background: #fff; padding: 20px; }
        .vs-title { margin: 0 0 18px; font-size: 24px; font-weight: 600; }
        .vs-topbar { display: flex; align-items: center; justify-content: flex-end; margin-bottom: 12px; }
        .vs-tutorial { border: 1px solid #dbe7ff; background: #f6f9ff; border-radius: 6px; padding: 12px 14px; margin: 0 0 14px; }
        .vs-tutorial.is-hidden { display: none; }
        .vs-tutorial-title { font-size: 14px; font-weight: 700; margin: 0 0 8px; color: #0b3d91; }
        .vs-tutorial-list { margin: 0; padding-left: 18px; }
        .vs-tutorial-list li { margin: 0 0 5px; color: #344054; }
        .vs-grid { display: grid; grid-template-columns: 2fr 1fr 1fr 1fr auto; gap: 12px; margin-bottom: 15px; align-items: start; }
        .vs-grid .select2-container { width: 100% !important; }
        .vs-search-wrap { position: relative; }
        .vs-suggestions { position: absolute; z-index: 20; left: 0; right: 0; top: 40px; border: 1px solid #ced4da; border-radius: 4px; background: #fff; max-height: 280px; overflow: auto; display: none; }
        .vs-suggestions.active { display: block; }
        .vs-suggestion-item { padding: 9px 10px; border-bottom: 1px solid #eee; cursor: pointer; line-height: 1.35; }
        .vs-suggestion-item:hover { background: #f8f9fa; }
        .vs-selected-wrap { margin: 0 0 12px; }
        .vs-selected-title { font-size: 13px; margin-bottom: 6px; color: #495057; }
        .vs-selected-products { display: flex; flex-wrap: wrap; gap: 8px; }
        .vs-selected-item { display: inline-flex; align-items: center; gap: 8px; border: 1px solid #cfe2ff; background: #eef5ff; color: #0b5ed7; border-radius: 16px; padding: 5px 10px; font-size: 12px; line-height: 1; }
        .vs-selected-remove { border: none; background: transparent; color: #0b5ed7; cursor: pointer; font-size: 15px; line-height: 1; padding: 0; }
        .vs-customers-grid { display: grid; grid-template-columns: minmax(280px, 1fr) auto auto; gap: 12px; align-items: end; margin-bottom: 10px; }
        .vs-customers-search-wrap { position: relative; }
        .vs-customers-suggestions { position: absolute; z-index: 20; left: 0; right: 0; top: 40px; border: 1px solid #ced4da; border-radius: 4px; background: #fff; max-height: 280px; overflow: auto; display: none; }
        .vs-customers-suggestions.active { display: block; }
        .vs-customer-suggestion-item { padding: 9px 10px; border-bottom: 1px solid #eee; cursor: pointer; line-height: 1.35; }
        .vs-customer-suggestion-item:hover { background: #f8f9fa; }
        .vs-table-wrap { overflow: auto; border: 1px solid #dee2e6; border-radius: 4px; }
        .vs-table-wrap .table { width: 100%; border-collapse: collapse; margin: 0; font-size: 13px; }
        .vs-table-wrap .table th, .vs-table-wrap .table td { padding: 10px; border-bottom: 1px solid #dee2e6; text-align: left; vertical-align: top; }
        .vs-table-wrap .table thead th { background: #f8f9fa; font-size: 12px; text-transform: uppercase; letter-spacing: 0.3px; }
        .vs-details-row { background: #fafcff; }
        .vs-muted { color: #6c757d; }
        .vs-loading, .vs-empty, .vs-error { padding: 16px; border-radius: 4px; margin-bottom: 10px; }
        .vs-loading { background: #f5f9ff; color: #0b5ed7; }
        .vs-empty { background: #f8f9fa; color: #6c757d; }
        .vs-error { background: #fff3f3; color: #dc3545; }
        .vs-summary { margin: 10px 0; font-size: 13px; }
        .vs-footer { margin-top: 10px; display: flex; gap: 10px; align-items: center; }
        .vs-trend-btn { display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px; border: 1px solid #ced4da; border-radius: 4px; background: #fff; color: #0b5ed7; cursor: pointer; padding: 0; }
        .vs-trend-title { font-weight: 600; margin-bottom: 10px; }
        .vs-trend-canvas-wrap { width: 100%; overflow-x: auto; }
        .vs-trend-canvas { width: 100%; min-height: 220px; height: 220px; border: 1px solid #e7edf5; border-radius: 4px; background: #fff; }
        @media (max-width: 980px) {
            .vs-grid { grid-template-columns: 1fr; }
            .vs-customers-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>

<body>
    <div class="wrapper">
        <?= $this->include('partials/menu') ?>

        <div class="page-content">
            <div class="page-container">
                <div class="row">
                    <div class="col-12">
                        <div class="page-title-box">
                            <h4 class="page-title"><?= esc($title) ?></h4>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body vs-container">

                                <div class="vs-topbar">
                                    <button type="button" id="vs-toggle-tutorial" class="btn btn-dark">Tutoriel</button>
                                </div>

                                <div id="vs-tutorial" class="vs-tutorial is-hidden">
                                    <div class="vs-tutorial-title">Comment utiliser ce module</div>
                                    <ol class="vs-tutorial-list">
                                        <li>Recherchez puis sélectionnez un ou plusieurs produits (SKU, nom ou marque).</li>
                                        <li>La période par défaut démarre au <strong>premier jour du mois en cours</strong> jusqu'à aujourd'hui.</li>
                                        <li>Cliquez sur <strong>Soumettre</strong> pour charger les statistiques.</li>
                                        <li>Sur un produit configurable, cliquez sur <strong>+</strong> pour afficher les déclinaisons enfants vendues sur la période.</li>
                                        <li>Cliquez sur <strong>Voir clients</strong> pour ouvrir la liste des clients, puis utilisez le filtre pour cibler certains clients.</li>
                                        <li>Cliquez sur l'icône <strong>Graph</strong> pour afficher la courbe d'évolution des ventes du produit.</li>
                                        <li>Utilisez <strong>Charger plus</strong> pour parcourir les pages suivantes de résultats.</li>
                                    </ol>
                                </div>

                                <div class="vs-grid">
                                    <div class="vs-search-wrap">
                                        <input type="text" id="vs-q" class="form-control" placeholder="Produit / SKU / Titre / Marque" autocomplete="off">
                                        <div id="vs-suggestions" class="vs-suggestions"></div>
                                    </div>
                                    <select id="vs-company" class="form-control select2" multiple="multiple" data-placeholder="Chargement des sociétés..."><option></option></select>
                                    <input type="date" id="vs-date-from" class="form-control" title="Date de début">
                                    <input type="date" id="vs-date-to" class="form-control" title="Date de fin">
                                    <button type="button" id="vs-search-btn" class="btn btn-primary">Soumettre</button>
                                </div>

                                <div class="vs-selected-wrap">
                                    <div class="vs-selected-title">Produits sélectionnés (<span id="vs-selected-count">0</span>)</div>
                                    <div id="vs-selected-products" class="vs-selected-products">
                                        <span class="vs-muted">Aucun produit sélectionné.</span>
                                    </div>
                                </div>

                                <div id="vs-summary" class="vs-summary vs-muted"></div>
                                <div id="vs-messages"></div>

                                <div class="vs-table-wrap">
                                    <table class="table" id="vs-main-table" data-exclusion-table="ventesstats_products">
                                        <thead>
                                            <tr>
                                                <th class="exclusion-checkbox"></th>
                                                <th>Détails</th>
                                                <th>Produit</th>
                                                <th>Marque</th>
                                                <th class="text-end">Qté vendue</th>
                                                <th class="text-end">J-30</th>
                                                <th class="text-end">Nb commandes</th>
                                                <th>Première vente</th>
                                                <th>Dernière vente</th>
                                                <th>Graph</th>
                                                <th>Clients</th>
                                            </tr>
                                        </thead>
                                        <tbody id="vs-main-body">
                                            <tr><td colspan="11" class="vs-muted">Lancez une recherche pour afficher les statistiques.</td></tr>
                                        </tbody>
                                    </table>
                                </div>

                                <div class="vs-footer">
                                    <button type="button" id="vs-load-more" class="btn btn-outline-secondary" style="display:none;">Charger plus</button>
                                    <span id="vs-page-info" class="vs-muted"></span>
                                </div>

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

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

    <?= $this->include('partials/footer-scripts') ?>
    <?= $this->include('partials/exclusion-actions') ?>
    <script src="/vendor/select2/select2.min.js"></script>

    <script>
    $(function () {
        'use strict';

        var statsUrl = '/admin/ventesstats/getStats';
        var customersUrl = '/admin/ventesstats/getCustomers';
        var suggestionsUrl = '/admin/ventesstats/searchProducts';
        var companiesUrl = '/admin/ventesstats/getCompanies';
        var childrenUrl = '/admin/ventesstats/getChildren';
        var trendUrl = '/admin/ventesstats/getTrend';

        var searchTimeout = null;
        var currentPage = 1;
        var pageSize = 50;
        var hasMorePages = false;
        var selectedProducts = {};

        function escapeHtml(text) {
            return String(text || '')
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#039;');
        }

        function formatDate(dateValue) {
            if (!dateValue) return '-';
            var date = new Date(dateValue.replace(' ', 'T'));
            if (isNaN(date.getTime())) return escapeHtml(dateValue);
            var day = String(date.getDate()).padStart(2, '0');
            var month = String(date.getMonth() + 1).padStart(2, '0');
            var year = date.getFullYear();
            var hours = String(date.getHours()).padStart(2, '0');
            var mins = String(date.getMinutes()).padStart(2, '0');
            return day + '/' + month + '/' + year + ' ' + hours + ':' + mins;
        }

        function formatQty(value) {
            var number = Number(value || 0);
            return !isFinite(number) ? '0' : String(Math.round(number));
        }

        function showMessage(type, message) {
            var className = type === 'error' ? 'vs-error' : (type === 'loading' ? 'vs-loading' : 'vs-empty');
            $('#vs-messages').html('<div class="' + className + '">' + escapeHtml(message) + '</div>');
        }

        function clearMessage() {
            $('#vs-messages').html('');
        }

        function getSelectedProductIds() {
            return Object.keys(selectedProducts).map(Number).filter(function (id) { return id > 0; });
        }

        function getSelectedCompanyValues() {
            return ($('#vs-company').val() || []).filter(function (v) { return v !== ''; });
        }

        function getCommonAjaxData() {
            return {
                product_ids: getSelectedProductIds(),
                date_from: $('#vs-date-from').val(),
                date_to: $('#vs-date-to').val(),
                company_values: getSelectedCompanyValues()
            };
        }

        function renderSelectedProducts() {
            var ids = getSelectedProductIds();
            $('#vs-selected-count').text(String(ids.length));
            var $wrap = $('#vs-selected-products');
            if (!ids.length) {
                $wrap.html('<span class="vs-muted">Aucun produit sélectionné.</span>');
                return;
            }
            var html = '';
            ids.forEach(function (id) {
                var item = selectedProducts[id];
                if (!item) return;
                var label = (item.product_sku || '') + ' - ' + (item.product_name || '');
                html += '<span class="vs-selected-item">' +
                    '<span>' + escapeHtml(label) + '</span>' +
                    '<button type="button" class="vs-selected-remove" data-product-id="' + id + '" aria-label="Retirer">&times;</button>' +
                    '</span>';
            });
            $wrap.html(html);
        }

        function addSelectedProduct(item) {
            var productId = Number(item && item.product_id ? item.product_id : 0);
            if (!productId) return;
            selectedProducts[productId] = {
                product_id: productId,
                product_sku: String(item.product_sku || ''),
                product_name: String(item.product_name || ''),
                brand: String(item.brand || '')
            };
            renderSelectedProducts();
        }

        function removeSelectedProduct(productId) {
            if (!selectedProducts[productId]) return;
            delete selectedProducts[productId];
            renderSelectedProducts();
        }

        function loadStats(reset) {
            var productIds = getSelectedProductIds();

            if (!productIds.length) {
                showMessage('error', 'Sélectionnez au moins un produit avant de soumettre.');
                if (reset) {
                    $('#vs-main-body').html('<tr><td colspan="11" class="vs-muted">Sélectionnez un ou plusieurs produits puis cliquez sur Soumettre.</td></tr>');
                    $('#vs-summary').text('0 produit chargé');
                    $('#vs-load-more').hide();
                    $('#vs-page-info').text('');
                }
                return;
            }

            if (reset) {
                currentPage = 1;
                hasMorePages = false;
                $('#vs-main-body').html('<tr><td colspan="11" class="vs-muted">Chargement...</td></tr>');
                $('#vs-load-more').hide();
                $('#vs-page-info').text('');
            }

            showMessage('loading', 'Chargement des statistiques...');

            var ajaxData = getCommonAjaxData();
            ajaxData.page = currentPage;
            ajaxData.page_size = pageSize;

            $.ajax({
                url: statsUrl,
                type: 'GET',
                dataType: 'json',
                data: ajaxData
            }).done(function (response) {
                renderStats((response && response.items) ? response.items : [], reset);
                hasMorePages = !!(response && response.has_more);
                if (hasMorePages) {
                    $('#vs-load-more').show();
                } else {
                    $('#vs-load-more').hide();
                }
                $('#vs-page-info').text('Page ' + String(currentPage));
                if (response && response.message) {
                    showMessage('empty', response.message);
                } else {
                    clearMessage();
                }
            }).fail(function () {
                showMessage('error', 'Erreur pendant le chargement des statistiques.');
            });
        }

        function renderStats(items, reset) {
            var $body = $('#vs-main-body');
            if (!items.length) {
                $('#vs-summary').text('0 produit trouvé');
                if (reset) {
                    $body.html('<tr><td colspan="11" class="vs-muted">Aucune donnée trouvée.</td></tr>');
                }
                return;
            }

            var existingRows = reset ? 0 : $body.find('tr[id^="vs-row-"]').length;
            $('#vs-summary').text((existingRows + items.length) + ' produit(s) chargé(s)');

            var html = '';
            items.forEach(function (item) {
                var productId = Number(item.product_id || 0);
                var label = escapeHtml((item.product_sku || '') + ' - ' + (item.product_name || ''));
                var isConfigurable = Number(item.is_configurable || 0) === 1;
                var isBundle = String(item.product_type || '') === 'bundle';
                var canShowDetails = isConfigurable || isBundle;
                var detailButton = canShowDetails
                    ? '<button type="button" class="btn btn-link vs-toggle-children" data-parent-product-id="' + productId + '">+</button>'
                    : '-';
                var trendButton = '<button type="button" class="vs-trend-btn vs-toggle-trend" data-product-id="' + productId + '" title="Voir la courbe des ventes" aria-label="Voir la courbe des ventes">' +
                    '<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="width:16px;height:16px;">' +
                    '<path d="M4 18H20" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>' +
                    '<path d="M6 15L10 11L13 14L18 8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>' +
                    '</svg>' +
                    '</button>';

                html += '<tr id="vs-row-' + productId + '" data-exclusion-id="' + productId + '" data-exclusion-label="' + escapeHtml((item.product_sku || '') + ' - ' + (item.product_name || '')) + '">' +
                    '<td class="exclusion-checkbox"><input type="checkbox" class="exclusion-item form-check-input" value="' + productId + '" data-label="' + escapeHtml((item.product_sku || '') + ' - ' + (item.product_name || '')) + '"></td>' +
                    '<td>' + detailButton + '</td>' +
                    '<td>' + label + '</td>' +
                    '<td>' + escapeHtml(item.brand || '-') + '</td>' +
                    '<td class="text-end">' + formatQty(item.total_qty) + '</td>' +
                    '<td class="text-end">' + formatQty(item.j30_qty) + '</td>' +
                    '<td class="text-end">' + escapeHtml(item.orders_count || '0') + '</td>' +
                    '<td>' + formatDate(item.first_sale_at) + '</td>' +
                    '<td>' + formatDate(item.last_sale_at) + '</td>' +
                    '<td>' + trendButton + '</td>' +
                    '<td><button type="button" class="btn btn-link vs-toggle-customers" data-product-id="' + productId + '">Voir clients</button></td>' +
                    '</tr>';
            });

            if (reset) {
                $body.html(html);
            } else {
                $body.append(html);
            }
        }

        function loadCustomers(productId, $button) {
            var detailRowId = 'vs-detail-row-' + productId;
            $('#' + detailRowId).remove();

            var loadingHtml = '<tr id="' + detailRowId + '" class="vs-details-row"><td colspan="11">Chargement des clients...</td></tr>';
            $('#vs-row-' + productId).after(loadingHtml);

            var ajaxData = getCommonAjaxData();
            ajaxData.product_id = productId;

            $.ajax({
                url: customersUrl,
                type: 'GET',
                dataType: 'json',
                data: ajaxData
            }).done(function (response) {
                var items = (response && response.items) ? response.items : [];
                var html = '';
                var filterInputId = 'vs-customers-filter-input-' + productId;
                var suggestionsId = 'vs-customers-suggestions-' + productId;
                var selectedId = 'vs-customers-selected-' + productId;

                function buildCustomerKey(customer) {
                    var customerId = Number(customer && customer.customer_id ? customer.customer_id : 0);
                    var customerEmail = String(customer && customer.customer_email ? customer.customer_email : '').toLowerCase();
                    if (customerId > 0) return 'id:' + String(customerId);
                    return 'email:' + customerEmail;
                }

                if (!items.length) {
                    html = '<div class="vs-muted">Aucun client trouvé pour ce produit.</div>';
                } else {
                    var filterHtml = '<div class="vs-customers-filter-wrap">' +
                        '<div class="vs-customers-grid">' +
                        '<div class="vs-customers-search-wrap">' +
                        '<label for="' + filterInputId + '" class="vs-muted" style="display:block;margin-bottom:4px;">Filtrer clients</label>' +
                        '<input type="text" id="' + filterInputId + '" class="form-control vs-customers-q" placeholder="Nom / email client" autocomplete="off">' +
                        '<div id="' + suggestionsId + '" class="vs-customers-suggestions"></div>' +
                        '</div>' +
                        '<button type="button" class="btn btn-primary vs-apply-customers-filter" data-target-row-id="' + detailRowId + '">Soumettre</button>' +
                        '<button type="button" class="btn btn-outline-secondary vs-reset-customers-filter" data-target-row-id="' + detailRowId + '">Réinitialiser</button>' +
                        '</div>' +
                        '<div class="vs-selected-wrap">' +
                        '<div class="vs-selected-title">Clients sélectionnés (<span class="vs-customers-selected-count">0</span>)</div>' +
                        '<div id="' + selectedId + '" class="vs-selected-products">' +
                        '<span class="vs-muted">Aucun client sélectionné.</span>' +
                        '</div>' +
                        '</div>' +
                        '</div>';

                    html = '<table class="table">' +
                        '<thead><tr>' +
                        '<th>Client</th><th>Email</th><th>Société</th>' +
                        '<th class="text-end">Nb commandes</th><th class="text-end">Qté totale</th><th class="text-end">J-30</th>' +
                        '<th>1ère commande (produit)</th><th>Dernière commande (produit)</th>' +
                        '</tr></thead><tbody>';

                    items.forEach(function (customer) {
                        var customerKey = buildCustomerKey(customer);
                        html += '<tr class="vs-customer-row" data-customer-key="' + escapeHtml(customerKey) + '">' +
                            '<td>' + escapeHtml(customer.customer_name || '-') + '</td>' +
                            '<td>' + escapeHtml(customer.customer_email || '-') + '</td>' +
                            '<td>' + escapeHtml(customer.customer_company || '-') + '</td>' +
                            '<td class="text-end">' + escapeHtml(customer.orders_count || '0') + '</td>' +
                            '<td class="text-end">' + formatQty(customer.total_qty) + '</td>' +
                            '<td class="text-end">' + formatQty(customer.j30_qty) + '</td>' +
                            '<td>' + formatDate(customer.first_order_at) + '</td>' +
                            '<td>' + formatDate(customer.last_order_at) + '</td>' +
                            '</tr>';
                    });

                    html += '</tbody></table>';
                    html = filterHtml + html;
                }

                $('#' + detailRowId).html('<td colspan="11">' + html + '</td>');

                if (items.length) {
                    var customersByKey = {};
                    items.forEach(function (customer) {
                        var key = buildCustomerKey(customer);
                        customersByKey[key] = {
                            key: key,
                            name: String(customer.customer_name || '-'),
                            email: String(customer.customer_email || '-'),
                            label: String(customer.customer_name || '-') + ' | ' + String(customer.customer_email || '-')
                        };
                    });
                    $('#' + detailRowId).find('.vs-customers-filter-wrap')
                        .data('customersByKey', customersByKey)
                        .data('selectedCustomers', {});
                }

                $button.text('Masquer clients').attr('data-open', '1');
            }).fail(function () {
                $('#' + detailRowId).html('<td colspan="11"><div class="vs-error">Erreur pendant le chargement des clients.</div></td>');
            });
        }

        function closeCustomers(productId, $button) {
            $('#vs-detail-row-' + productId).remove();
            $button.text('Voir clients').attr('data-open', '0');
        }

        function renderSelectedCustomers($filterWrap) {
            var selectedCustomers = $filterWrap.data('selectedCustomers') || {};
            var keys = Object.keys(selectedCustomers);
            var html = '';
            keys.forEach(function (key) {
                var customer = selectedCustomers[key];
                html += '<span class="vs-selected-item">' +
                    '<span>' + escapeHtml(customer.label) + '</span>' +
                    '<button type="button" class="vs-customer-selected-remove" data-customer-key="' + escapeHtml(key) + '" aria-label="Retirer">&times;</button>' +
                    '</span>';
            });
            $filterWrap.find('.vs-customers-selected-count').text(String(keys.length));
            $filterWrap.find('.vs-selected-products').html(html || '<span class="vs-muted">Aucun client sélectionné.</span>');
        }

        function loadChildren(parentProductId, $button) {
            var detailRowId = 'vs-children-row-' + parentProductId;
            $('#' + detailRowId).remove();

            var loadingHtml = '<tr id="' + detailRowId + '" class="vs-details-row"><td colspan="11">Chargement des déclinaisons enfants...</td></tr>';
            $('#vs-row-' + parentProductId).after(loadingHtml);

            var ajaxData = getCommonAjaxData();
            ajaxData.parent_product_id = parentProductId;

            $.ajax({
                url: childrenUrl,
                type: 'GET',
                dataType: 'json',
                data: ajaxData
            }).done(function (response) {
                var items = (response && response.items) ? response.items : [];
                var html = '';
                if (!items.length) {
                    html = '<div class="vs-muted">Aucune vente enfant trouvée pour ce configurable sur cette période.</div>';
                } else {
                    html = '<table class="table">' +
                        '<thead><tr>' +
                        '<th>Child SKU</th><th>Produit enfant</th><th>Marque</th>' +
                        '<th class="text-end">Qté vendue</th><th class="text-end">Nb commandes</th>' +
                        '<th>Première vente</th><th>Dernière vente</th>' +
                        '</tr></thead><tbody>';

                    items.forEach(function (child) {
                        html += '<tr>' +
                            '<td>' + escapeHtml(child.product_sku || '-') + '</td>' +
                            '<td>' + escapeHtml(child.product_name || '-') + '</td>' +
                            '<td>' + escapeHtml(child.brand || '-') + '</td>' +
                            '<td class="text-end">' + formatQty(child.total_qty) + '</td>' +
                            '<td class="text-end">' + escapeHtml(child.orders_count || '0') + '</td>' +
                            '<td>' + formatDate(child.first_sale_at) + '</td>' +
                            '<td>' + formatDate(child.last_sale_at) + '</td>' +
                            '</tr>';
                    });

                    html += '</tbody></table>';
                }

                $('#' + detailRowId).html('<td colspan="11">' + html + '</td>');
                $button.text('-').attr('data-open', '1');
            }).fail(function () {
                $('#' + detailRowId).html('<td colspan="11"><div class="vs-error">Erreur pendant le chargement des enfants.</div></td>');
            });
        }

        function closeChildren(parentProductId, $button) {
            $('#vs-children-row-' + parentProductId).remove();
            $button.text('+').attr('data-open', '0');
        }

        function drawTrend(canvasId, items, granularity) {
            var canvas = document.getElementById(canvasId);
            if (!canvas) return;
            var ctx = canvas.getContext('2d');
            var cssWidth = canvas.clientWidth || 700;
            var cssHeight = canvas.clientHeight || 220;
            canvas.width = cssWidth;
            canvas.height = cssHeight;
            ctx.clearRect(0, 0, cssWidth, cssHeight);

            if (!items.length) {
                ctx.fillStyle = '#6c757d';
                ctx.font = '13px Arial';
                ctx.fillText('Aucune vente dans cette periode', 16, 24);
                return;
            }

            var padding = { top: 16, right: 16, bottom: 42, left: 44 };
            var plotWidth = cssWidth - padding.left - padding.right;
            var plotHeight = cssHeight - padding.top - padding.bottom;
            var values = items.map(function (point) { return Number(point.total_qty || 0); });
            var maxValue = Math.max.apply(null, values.concat([1]));
            var minValue = 0;
            var xStep = items.length > 1 ? (plotWidth / (items.length - 1)) : 0;

            ctx.strokeStyle = '#d9e3f2'; ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.moveTo(padding.left, padding.top);
            ctx.lineTo(padding.left, padding.top + plotHeight);
            ctx.lineTo(padding.left + plotWidth, padding.top + plotHeight);
            ctx.stroke();

            ctx.strokeStyle = '#0b5ed7'; ctx.lineWidth = 2;
            ctx.beginPath();
            items.forEach(function (point, index) {
                var x = padding.left + (index * xStep);
                var value = Number(point.total_qty || 0);
                var y = padding.top + plotHeight - ((value - minValue) / (maxValue - minValue)) * plotHeight;
                if (index === 0) ctx.moveTo(x, y);
                else ctx.lineTo(x, y);
            });
            ctx.stroke();

            ctx.fillStyle = '#0b5ed7';
            items.forEach(function (point, index) {
                var x = padding.left + (index * xStep);
                var value = Number(point.total_qty || 0);
                var y = padding.top + plotHeight - ((value - minValue) / (maxValue - minValue)) * plotHeight;
                ctx.beginPath();
                ctx.arc(x, y, 2.5, 0, Math.PI * 2);
                ctx.fill();
            });

            ctx.fillStyle = '#6c757d'; ctx.font = '11px Arial';
            ctx.fillText('0', 12, padding.top + plotHeight + 4);
            ctx.fillText(String(Math.round(maxValue)), 6, padding.top + 10);

            var labelCount = Math.min(items.length, 6);
            for (var i = 0; i < labelCount; i++) {
                var idx = labelCount === 1 ? 0 : Math.round((i * (items.length - 1)) / (labelCount - 1));
                var xLabel = padding.left + (idx * xStep);
                var raw = String(items[idx].bucket || '');
                var label = granularity === 'month' ? raw : raw.slice(5);
                ctx.fillText(label, xLabel - 14, padding.top + plotHeight + 20);
            }
        }

        function loadTrend(productId, $button) {
            var detailRowId = 'vs-trend-row-' + productId;
            var canvasId = 'vs-trend-canvas-' + productId;
            $('#' + detailRowId).remove();

            var loadingHtml = '<tr id="' + detailRowId + '" class="vs-details-row"><td colspan="11">Chargement de la courbe...</td></tr>';
            $('#vs-row-' + productId).after(loadingHtml);

            var ajaxData = getCommonAjaxData();
            ajaxData.product_id = productId;

            $.ajax({
                url: trendUrl,
                type: 'GET',
                dataType: 'json',
                data: ajaxData
            }).done(function (response) {
                var items = (response && response.items) ? response.items : [];
                var granularity = (response && response.granularity) ? response.granularity : 'day';
                var modeLabel = granularity === 'month' ? 'par mois' : 'par jour';
                var html = '<div class="vs-trend-title">Courbe des ventes ' + modeLabel + '</div>' +
                    '<div class="vs-trend-canvas-wrap"><canvas id="' + canvasId + '" class="vs-trend-canvas"></canvas></div>';
                $('#' + detailRowId).html('<td colspan="11">' + html + '</td>');
                drawTrend(canvasId, items, granularity);
                $button.attr('data-open', '1');
            }).fail(function () {
                $('#' + detailRowId).html('<td colspan="11"><div class="vs-error">Erreur pendant le chargement de la courbe.</div></td>');
            });
        }

        function closeTrend(productId, $button) {
            $('#vs-trend-row-' + productId).remove();
            $button.attr('data-open', '0');
        }

        function renderSuggestions(items) {
            var $box = $('#vs-suggestions');
            if (!items.length) {
                $box.removeClass('active').html('');
                return;
            }
            var html = '';
            items.forEach(function (item) {
                var productId = Number(item.product_id || 0);
                if (!productId || selectedProducts[productId]) return;
                html += '<div class="vs-suggestion-item" data-product-id="' + productId +
                    '" data-product-sku="' + escapeHtml(item.product_sku || '') +
                    '" data-product-name="' + escapeHtml(item.product_name || '') +
                    '" data-product-brand="' + escapeHtml(item.brand || '') +
                    '">' +
                    '<strong>' + escapeHtml(item.product_sku || '') + '</strong> - ' +
                    escapeHtml(item.product_name || '') +
                    (item.brand ? ' <span class="vs-muted">(' + escapeHtml(item.brand) + ')</span>' : '') +
                    '</div>';
            });
            if (!html) {
                $box.removeClass('active').html('');
                return;
            }
            $box.html(html).addClass('active');
        }

        function searchSuggestions(query) {
            $.ajax({
                url: suggestionsUrl,
                type: 'GET',
                dataType: 'json',
                data: { q: query }
            }).done(function (response) {
                renderSuggestions((response && response.items) ? response.items : []);
            }).fail(function () {
                $('#vs-suggestions').removeClass('active').html('');
            });
        }

        function updateTutorialToggleLabel() {
            var isHidden = $('#vs-tutorial').hasClass('is-hidden');
            $('#vs-toggle-tutorial').text(isHidden ? 'Tutoriel' : 'Fermer tutoriel');
        }

        $('#vs-search-btn').on('click', function () { loadStats(true); });

        $('#vs-load-more').on('click', function () {
            if (!hasMorePages) return;
            currentPage += 1;
            loadStats(false);
        });

        $('#vs-q').on('input', function () {
            var query = $(this).val().trim();
            clearTimeout(searchTimeout);
            if (query.length < 2) {
                $('#vs-suggestions').removeClass('active').html('');
                return;
            }
            searchTimeout = setTimeout(function () { searchSuggestions(query); }, 250);
        });

        $(document).on('click', '.vs-suggestion-item', function (e) {
            e.preventDefault(); e.stopPropagation();
            var $item = $(this);
            addSelectedProduct({
                product_id: Number($item.data('product-id')),
                product_sku: String($item.data('product-sku') || ''),
                product_name: String($item.data('product-name') || ''),
                brand: String($item.data('product-brand') || '')
            });
            $item.remove();
            if (!$('#vs-suggestions').find('.vs-suggestion-item').length) {
                $('#vs-suggestions').removeClass('active').html('');
            }
        });

        $(document).on('click', '.vs-selected-remove', function () {
            var productId = Number($(this).data('product-id'));
            if (!productId) return;
            removeSelectedProduct(productId);
        });

        $(document).on('click', function (e) {
            if (!$(e.target).closest('.vs-search-wrap').length) {
                $('#vs-suggestions').removeClass('active').html('');
            }
            if (!$(e.target).closest('.vs-customers-search-wrap').length) {
                $('.vs-customers-filter-wrap .vs-customers-suggestions').removeClass('active').html('');
            }
        });

        $(document).on('click', '.vs-toggle-customers', function () {
            var $button = $(this);
            var productId = Number($button.data('product-id'));
            var open = String($button.attr('data-open') || '0') === '1';
            if (!productId) return;
            if (open) { closeCustomers(productId, $button); return; }
            loadCustomers(productId, $button);
        });

        $(document).on('click', '.vs-apply-customers-filter', function () {
            var $button = $(this);
            var targetRowId = String($button.data('target-row-id') || '');
            var $wrap = $('#' + targetRowId);
            var $filterWrap = $wrap.find('.vs-customers-filter-wrap');
            if (!targetRowId || !$filterWrap.length) return;

            var $rows = $wrap.find('tr.vs-customer-row');
            var selectedCustomers = $filterWrap.data('selectedCustomers') || {};
            var selectedKeys = Object.keys(selectedCustomers);
            $wrap.find('.vs-customers-no-match').remove();

            if (!selectedKeys.length) {
                $rows.show();
                return;
            }

            var selectedMap = {};
            selectedKeys.forEach(function (key) { selectedMap[String(key)] = true; });

            var visibleCount = 0;
            $rows.each(function () {
                var $row = $(this);
                var rowKey = String($row.data('customer-key') || '');
                var shouldShow = !!selectedMap[rowKey];
                $row.toggle(shouldShow);
                if (shouldShow) visibleCount += 1;
            });

            if (!visibleCount) {
                $wrap.find('table').after('<div class="vs-customers-no-match vs-muted" style="margin-top:8px;">Aucun client correspondant à la sélection.</div>');
            }
        });

        $(document).on('click', '.vs-reset-customers-filter', function () {
            var $button = $(this);
            var targetRowId = String($button.data('target-row-id') || '');
            var $wrap = $('#' + targetRowId);
            var $filterWrap = $wrap.find('.vs-customers-filter-wrap');
            if (!targetRowId || !$filterWrap.length) return;
            $filterWrap.data('selectedCustomers', {});
            $filterWrap.find('.vs-customers-q').val('');
            $filterWrap.find('.vs-customers-suggestions').removeClass('active').html('');
            renderSelectedCustomers($filterWrap);
            $wrap.find('.vs-customers-no-match').remove();
            $wrap.find('tr.vs-customer-row').show();
        });

        $(document).on('input', '.vs-customers-q', function () {
            var $input = $(this);
            var query = $input.val().trim().toLowerCase();
            var $filterWrap = $input.closest('.vs-customers-filter-wrap');
            var customersByKey = $filterWrap.data('customersByKey') || {};
            var selectedCustomers = $filterWrap.data('selectedCustomers') || {};
            var $suggestions = $filterWrap.find('.vs-customers-suggestions');
            var html = '';

            if (query.length < 2) {
                $suggestions.removeClass('active').html('');
                return;
            }

            Object.keys(customersByKey).forEach(function (key) {
                if (selectedCustomers[key]) return;
                var customer = customersByKey[key];
                var haystack = (customer.name + ' ' + customer.email).toLowerCase();
                if (haystack.indexOf(query) === -1) return;
                html += '<div class="vs-customer-suggestion-item" data-customer-key="' + escapeHtml(customer.key) + '">' +
                    '<strong>' + escapeHtml(customer.name) + '</strong> - ' + escapeHtml(customer.email) +
                    '</div>';
            });

            if (!html) {
                $suggestions.removeClass('active').html('');
                return;
            }
            $suggestions.html(html).addClass('active');
        });

        $(document).on('click', '.vs-customer-suggestion-item', function (e) {
            e.preventDefault(); e.stopPropagation();
            var $item = $(this);
            var customerKey = String($item.data('customer-key') || '');
            var $filterWrap = $item.closest('.vs-customers-filter-wrap');
            var customersByKey = $filterWrap.data('customersByKey') || {};
            var selectedCustomers = $filterWrap.data('selectedCustomers') || {};
            if (!customerKey || !customersByKey[customerKey]) return;
            selectedCustomers[customerKey] = customersByKey[customerKey];
            $filterWrap.data('selectedCustomers', selectedCustomers);
            renderSelectedCustomers($filterWrap);
            $filterWrap.find('.vs-customers-q').trigger('input');
        });

        $(document).on('click', '.vs-customer-selected-remove', function () {
            var $button = $(this);
            var customerKey = String($button.data('customer-key') || '');
            var $filterWrap = $button.closest('.vs-customers-filter-wrap');
            var selectedCustomers = $filterWrap.data('selectedCustomers') || {};
            if (!customerKey || !selectedCustomers[customerKey]) return;
            delete selectedCustomers[customerKey];
            $filterWrap.data('selectedCustomers', selectedCustomers);
            renderSelectedCustomers($filterWrap);
            $filterWrap.find('.vs-customers-q').trigger('input');
        });

        $(document).on('click', '.vs-toggle-children', function () {
            var $button = $(this);
            var parentProductId = Number($button.data('parent-product-id'));
            var open = String($button.attr('data-open') || '0') === '1';
            if (!parentProductId) return;
            if (open) { closeChildren(parentProductId, $button); return; }
            loadChildren(parentProductId, $button);
        });

        $(document).on('click', '.vs-toggle-trend', function () {
            var $button = $(this);
            var productId = Number($button.data('product-id'));
            var open = String($button.attr('data-open') || '0') === '1';
            if (!productId) return;
            if (open) { closeTrend(productId, $button); return; }
            loadTrend(productId, $button);
        });

        $('#vs-toggle-tutorial').on('click', function () {
            $('#vs-tutorial').toggleClass('is-hidden');
            updateTutorialToggleLabel();
        });

        (function presetDefaultPeriod() {
            var now = new Date();
            var firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
            function toInputDate(date) {
                var year = date.getFullYear();
                var month = String(date.getMonth() + 1).padStart(2, '0');
                var day = String(date.getDate()).padStart(2, '0');
                return year + '-' + month + '-' + day;
            }
            if (!$('#vs-date-from').val()) $('#vs-date-from').val(toInputDate(firstDayOfMonth));
            if (!$('#vs-date-to').val()) $('#vs-date-to').val(toInputDate(now));
        })();

        (function initSelect2() {
            $.ajax({
                url: companiesUrl,
                type: 'GET',
                dataType: 'json'
            }).done(function (response) {
                var companies = (response && response.items) ? response.items : [];
                var options = '<option></option>' + companies.map(function (company) {
                    return '<option value="' + escapeHtml(company) + '">' + escapeHtml(company) + '</option>';
                }).join('');
                $('#vs-company').html(options).select2({
                    placeholder: 'Société (toutes)',
                    allowClear: true
                });
            }).fail(function () {
                $('#vs-company').select2({
                    placeholder: 'Société (toutes)',
                    allowClear: true
                });
            });
        })();

        renderSelectedProducts();
        updateTutorialToggleLabel();
    });
    </script>
</body>

</html>
