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

<head>
    <?php echo view("partials/title-meta", array("title" => $title)) ?>
    <?= $this->include('partials/head-css') ?>
</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 row-cols-xxl-3 row-cols-md-3 row-cols-1 g-3">
                    <div class="col">
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <p class="text-muted mb-1">Produits offerts distincts</p>
                                        <h3 class="fw-semibold mb-0"><?= number_format($summary['nb_produits'] ?? 0, 0, ',', ' ') ?></h3>
                                    </div>
                                    <div class="avatar-sm bg-primary rounded d-flex align-items-center justify-content-center">
                                        <i class="ti ti-gift text-white fs-20"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col">
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <p class="text-muted mb-1">Commandes concernées</p>
                                        <h3 class="fw-semibold mb-0"><?= number_format($summary['nb_commandes'] ?? 0, 0, ',', ' ') ?></h3>
                                    </div>
                                    <div class="avatar-sm bg-success rounded d-flex align-items-center justify-content-center">
                                        <i class="ti ti-shopping-cart text-white fs-20"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col">
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <p class="text-muted mb-1">Quantité totale offerte</p>
                                        <h3 class="fw-semibold mb-0"><?= number_format($summary['total_qty'] ?? 0, 0, ',', ' ') ?></h3>
                                    </div>
                                    <div class="avatar-sm bg-info rounded d-flex align-items-center justify-content-center">
                                        <i class="ti ti-packages text-white fs-20"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row mt-4">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex flex-wrap justify-content-between align-items-center mb-3 gap-2">
                                    <div>
                                        <h4 class="header-title mb-1">Produits cadeaux offerts dans les règles panier</h4>
                                        <p class="text-muted mb-0 small">
                                            Données issues de <code>lca_promo_limiter_usage</code>. Les quantités des SKU enfants d'un configurable sont regroupées sur la ligne du produit parent.
                                        </p>
                                    </div>
                                    <form method="get" class="d-flex gap-2">
                                        <input type="date" name="date_debut" value="<?= esc($dateDebut) ?>" class="form-control">
                                        <input type="date" name="date_fin" value="<?= esc($dateFin) ?>" class="form-control">
                                        <button type="submit" class="btn btn-primary">Filtrer</button>
                                    </form>
                                </div>

                                <div class="table-responsive">
                                    <table id="table-promos-produits" class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Produit</th>
                                                <th>SKU</th>
                                                <th>Marque</th>
                                                <th>Règles panier</th>
                                                <th>Statut</th>
                                                <th class="text-end">Commandes</th>
                                                <th class="text-end">Qté totale</th>
                                                <th>1ère utilisation</th>
                                                <th>Dernière utilisation</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if (empty($produits)): ?>
                                                <tr>
                                                    <td colspan="11" class="text-center">Aucun produit cadeau trouvé sur cette période.</td>
                                                </tr>
                                            <?php else: ?>
                                                <?php foreach ($produits as $produit): ?>
                                                    <tr>
                                                        <td><?= esc($produit['entity_id']) ?></td>
                                                        <td><?= esc($produit['product_name']) ?></td>
                                                        <td><code><?= esc($produit['sku']) ?></code></td>
                                                        <td><?= esc($produit['brand']) ?></td>
                                                        <td>
                                                            <?php if (!empty($produit['rules'])): ?>
                                                                <?php foreach ($produit['rules'] as $rule): ?>
                                                                    <div class="mb-1">
                                                                        <span class="badge bg-secondary"><?= (int) $rule['rule_id'] ?></span>
                                                                        <?= esc($rule['name']) ?>
                                                                        <?php if (!empty($rule['from_date']) || !empty($rule['to_date'])): ?>
                                                                            <br>
                                                                            <small class="text-muted">
                                                                                <?= !empty($rule['from_date']) ? esc(date('d/m/Y', strtotime($rule['from_date']))) : '...' ?>
                                                                                →
                                                                                <?php if (!empty($rule['to_date'])): ?>
                                                                                    <?= esc(date('d/m/Y', strtotime($rule['to_date']))) ?>
                                                                                <?php else: ?>
                                                                                    <span class="text-danger">sans date de fin</span>
                                                                                <?php endif; ?>
                                                                            </small>
                                                                        <?php endif; ?>
                                                                    </div>
                                                                <?php endforeach; ?>
                                                            <?php else: ?>
                                                                -
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <?php if (!empty($produit['rules'])): ?>
                                                                <?php foreach ($produit['rules'] as $rule): ?>
                                                                    <div class="mb-1">
                                                                        <?php if ($rule['status'] === 'Actif'): ?>
                                                                            <span class="badge bg-success">Actif</span>
                                                                        <?php elseif ($rule['status'] === 'Inactif'): ?>
                                                                            <span class="badge bg-danger">Inactif</span>
                                                                        <?php else: ?>
                                                                            <span class="badge bg-secondary"><?= esc($rule['status']) ?></span>
                                                                        <?php endif; ?>
                                                                    </div>
                                                                <?php endforeach; ?>
                                                            <?php else: ?>
                                                                -
                                                            <?php endif; ?>
                                                        </td>
                                                        <td class="text-end" data-order="<?= (int) ($produit['orders_count'] ?? 0) ?>"><?= number_format((int) ($produit['orders_count'] ?? 0), 0, ',', ' ') ?></td>
                                                        <td class="text-end" data-order="<?= (float) ($produit['total_qty'] ?? 0) ?>"><?= number_format((float) ($produit['total_qty'] ?? 0), 0, ',', ' ') ?></td>
                                                        <td><?= !empty($produit['first_used_at']) ? esc(date('d/m/Y H:i', strtotime($produit['first_used_at']))) : '-' ?></td>
                                                        <td><?= !empty($produit['last_used_at']) ? esc(date('d/m/Y H:i', strtotime($produit['last_used_at']))) : '-' ?></td>
                                                        <td class="text-nowrap">
                                                            <button type="button" class="btn btn-sm btn-info btn-clients me-1"
                                                                    data-product-id="<?= (int) $produit['entity_id'] ?>"
                                                                    data-product-name="<?= esc($produit['product_name'], 'attr') ?>"
                                                                    data-product-sku="<?= esc($produit['sku'], 'attr') ?>">
                                                                <i class="ti ti-users"></i> Clients
                                                            </button>
                                                            <a href="https://magento.lcanetwork.com/admin/catalog/product/edit/id/<?= (int) $produit['entity_id'] ?>/" target="_blank" class="btn btn-sm btn-light" title="Ouvrir dans Magento">
                                                                <i class="ti ti-external-link"></i>
                                                            </a>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row mt-4">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="header-title mb-1">Règles panier sans produit cadeau</h4>
                                <p class="text-muted mb-3 small">
                                    Règles qui n'ont aucun produit offert dans <code>lca_promo_limiter_usage</code> sur la période sélectionnée.
                                </p>

                                <div class="table-responsive">
                                    <table id="table-unused-rules" class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>ID règle</th>
                                                <th>Nom</th>
                                                <th>Statut</th>
                                                <th>Date début</th>
                                                <th>Date fin</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if (empty($unusedRules)): ?>
                                                <tr>
                                                    <td colspan="5" class="text-center">Aucune règle sans produit cadeau trouvée.</td>
                                                </tr>
                                            <?php else: ?>
                                                <?php foreach ($unusedRules as $rule): ?>
                                                    <tr>
                                                        <td><?= (int) $rule['rule_id'] ?></td>
                                                        <td><?= esc($rule['name']) ?></td>
                                                        <td>
                                                            <?php if ($rule['status'] === 'Actif'): ?>
                                                                <span class="badge bg-success">Actif</span>
                                                            <?php else: ?>
                                                                <span class="badge bg-danger">Inactif</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td><?= !empty($rule['from_date']) ? esc(date('d/m/Y', strtotime($rule['from_date']))) : '-' ?></td>
                                                        <td>
                                                            <?php if (!empty($rule['to_date'])): ?>
                                                                <?= esc(date('d/m/Y', strtotime($rule['to_date']))) ?>
                                                            <?php else: ?>
                                                                <span class="text-danger">sans date de fin</span>
                                                            <?php endif; ?>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

    </div>

    <?= $this->include('partials/footer-scripts') ?>
    <?= $this->include('partials/datatables') ?>

    <style>
        #table-promos-produits tbody td.details-control {
            cursor: pointer;
        }
        .promo-clients-detail {
            padding: 1rem;
            background-color: var(--ct-light, #f8f9fa);
            border-top: 1px solid var(--ct-border-color, #dee2e6);
        }
    </style>

    <script>
        $(document).ready(function() {
            const mainTable = initDataTable('#table-promos-produits', {
                order: [[7, 'desc']],
                pageLength: 25
            });

            initDataTable('#table-unused-rules', {
                order: [[0, 'desc']],
                pageLength: 25
            });

            const dateDebut = <?= json_encode($dateDebut) ?>;
            const dateFin   = <?= json_encode($dateFin) ?>;

            function formatDate(dt) {
                if (!dt) return '-';
                const d = new Date(dt);
                if (isNaN(d.getTime())) return dt;
                return ('0' + d.getDate()).slice(-2) + '/' + ('0' + (d.getMonth() + 1)).slice(-2) + '/' + d.getFullYear() + ' ' + ('0' + d.getHours()).slice(-2) + ':' + ('0' + d.getMinutes()).slice(-2);
            }

            function escapeHtml(text) {
                return $('<div>').text(text ?? '').html();
            }

            function formatClientsDetail(clients, productName) {
                if (clients.length === 0) {
                    return '<div class="promo-clients-detail text-muted">Aucun client trouvé pour <strong>' + escapeHtml(productName) + '</strong>.</div>';
                }

                let html = '<div class="promo-clients-detail">';
                html += '<h6 class="mb-3">Clients ayant reçu : <strong>' + escapeHtml(productName) + '</strong></h6>';
                html += '<div class="table-responsive">';
                html += '<table class="table table-sm table-striped table-bordered mb-0">';
                html += '<thead><tr><th>ID client</th><th>Email</th><th>Nom</th><th class="text-end">Commandes</th><th class="text-end">Qté totale</th><th>1ère utilisation</th><th>Dernière utilisation</th></tr></thead>';
                html += '<tbody>';

                for (const client of clients) {
                    html += '<tr>' +
                        '<td>' + (client.customer_id || '-') + '</td>' +
                        '<td>' + escapeHtml(client.customer_email) + '</td>' +
                        '<td>' + escapeHtml(client.customer_name) + '</td>' +
                        '<td class="text-end">' + new Intl.NumberFormat('fr-FR').format(client.nb_commandes || 0) + '</td>' +
                        '<td class="text-end">' + new Intl.NumberFormat('fr-FR').format(client.total_qty || 0) + '</td>' +
                        '<td>' + formatDate(client.first_used_at) + '</td>' +
                        '<td>' + formatDate(client.last_used_at) + '</td>' +
                    '</tr>';
                }

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

            $('#table-promos-produits').on('click', '.btn-clients', function() {
                const tr = $(this).closest('tr');
                const row = mainTable.row(tr);
                const productId   = $(this).data('product-id');
                const productName = $(this).data('product-name');
                const btn         = $(this);

                if (row.child.isShown()) {
                    row.child.hide();
                    btn.html('<i class="ti ti-users"></i> Clients').removeClass('btn-warning').addClass('btn-info');
                    return;
                }

                // Fermer les autres lignes ouvertes
                mainTable.rows().every(function() {
                    if (this.child.isShown()) {
                        this.child.hide();
                        $(this.node()).find('.btn-clients')
                            .html('<i class="ti ti-users"></i> Clients')
                            .removeClass('btn-warning')
                            .addClass('btn-info');
                    }
                });

                row.child('<div class="promo-clients-detail text-center">Chargement…</div>').show();
                btn.prop('disabled', true);

                $.getJSON('/admin/promos-produits/clients/' + productId, {
                    date_debut: dateDebut,
                    date_fin: dateFin
                }).done(function(response) {
                    row.child(formatClientsDetail(response.clients || [], productName)).show();
                    btn.html('<i class="ti ti-chevron-up"></i> Fermer').removeClass('btn-info').addClass('btn-warning');
                }).fail(function(xhr) {
                    let message = 'Erreur lors du chargement des clients.';
                    try {
                        const json = JSON.parse(xhr.responseText);
                        if (json.error) message = json.error;
                    } catch (e) {}
                    row.child('<div class="promo-clients-detail text-danger">' + escapeHtml(message) + '</div>').show();
                    btn.removeClass('btn-info').addClass('btn-warning').html('<i class="ti ti-chevron-up"></i> Fermer');
                }).always(function() {
                    btn.prop('disabled', false);
                });
            });
        });
    </script>
</body>

</html>
