<?php
/**
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Smile ElasticSuite to newer
 * versions in the future.
 *
 * @category  Smile
 * @package   Smile\ElasticsuiteAnalytics
 * @author    Richard Bayet <richard.bayet@smile.fr>
 * @copyright 2020 Smile
 * @license   Open Software License ("OSL") v. 3.0
 */
?>

<?php
/**
 * @var Smile\ElasticsuiteAnalytics\Block\Adminhtml\Search\Usage\SearchTerms $block
 * @var \Magento\Framework\Escaper $escaper
 */
$maxVisibleTerms    = $block->getMaxVisibleTerms();
$termsData          = $block->getTermsData();
$visibleTermsData   = array_slice($termsData, 0, $maxVisibleTerms);
$hiddenTermsData    = array_slice($termsData, $maxVisibleTerms);
?>
<div class="dashboard-item" id="<?= $block->getJsId() ?>">
    <div class="dashboard-item-title">
        <span><?= $block->getTitle() ;?></span>
        <?php if (!empty($termsData)) : ?>
            <span id="<?= $block->getJsId() ?>_copy" class="admin__field-action-export" title="<?= $block->escapeHtml(__('Copy table data to clipboard')) ?>">
                <span class="copy-feedback-text"><?= __('Copied to clipboard !') ?></span>
            </span>
        <?php endif; ?>
        <?php if ($block->hasHelp()) :?>
            <div class="admin__field-tooltip tooltip">
                <a href="#<?= $block->getJsId() ?>_help"
                   title="<?= $block->escapeHtml(__('What is this ?')) ?>" class="admin__field-tooltip-action action-help">
                    <span style="display: inline-block"><?= __('What is this ?') ?></span>
                </a>
            </div>
        <?php endif; ?>
    </div>
    <?php if ($block->hasHelp()) :?>
        <div class="dashboard-item-help dashboard-data" id="<?= $block->getJsId() ?>_help">
            <p><?= $block->getHelp() ?></p>
        </div>
    <?php endif; ?>
    <div class="dashboard-item-content">
        <table class="admin__table-primary dashboard-data terms-report">
            <thead>
                <tr>
                    <th class="data-grid-th no-link col-search-query"><span><?= __('Term');?></span></th>
                    <th class="data-grid-th no-link"><span><?= __('Sessions');?></span></th>
                    <th class="data-grid-th no-link"><span><?= __('Visitors');?></span></th>
                    <th class="data-grid-th no-link <?php if (!$block->getShowConversionRate()) : ?>col-total<?php endif; ?>"><span><?= __('# Results (avg.)');?></span></th>
                    <?php if ($block->getShowConversionRate()) : ?>
                        <th class="data-grid-th no-link col-total">
                            <span title="<?= $block->escapeHtml(__('Conversion rate for the term(s)')) ?>">
                                <?= __('Conv. rate');?>
                            </span>
                        </th>
                    <?php endif; ?>
            </thead>
            <?php if (empty($termsData)) : ?>
                <tbody>
                    <tr>
                        <td colspan="<?= ($block->getShowConversionRate() ? 5 : 4) ?>" style="text-align:center; padding: 20px;">
                            <em><?= __('No data over the selected period.'); ?></em>
                        </td>
                    </tr>
                </tbody>
            <?php else : ?>
                <tbody>
                    <?php foreach ($visibleTermsData as $termData) : ?>
                    <tr>
                        <td class="col-search-query"><?php if ($termData['url']) : ?>
                                <a href=<?= $termData['url']; ?> target="_blank">
                                    <span title="<?= $escaper->escapeHtmlAttr($termData['term']); ?>"><?= $escaper->escapeHtml($termData['term']); ?></span>
                                </a>
                            <?php else : ?>
                                <span title="<?= $escaper->escapeHtmlAttr($termData['term']); ?>"><?= $escaper->escapeHtml($termData['term']); ?></span>
                            <?php endif; ?>
                        </td>
                        <td class="col-number"><?= $termData['sessions']; ?></td>
                        <td class="col-number"><?= $termData['visitors']; ?></td>
                        <td class="col-number"><?= $termData['result_count']; ?></td>
                        <?php if ($block->getShowConversionRate()) : ?>
                            <td class="col-number"><?= number_format($termData['conversion_rate'] * 100, 2); ?> %</td>
                        <?php endif; ?>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tbody class="extra" id="<?php echo $block->getJsId() ?>_extra">
                    <?php foreach ($hiddenTermsData as $termData) : ?>
                        <tr>
                            <td class="col-search-query"><?php if ($termData['url']) : ?>
                                    <a href=<?= $termData['url']; ?> target="_blank">
                                        <span title="<?= $escaper->escapeHtmlAttr($termData['term']); ?>"><?= $escaper->escapeHtml($termData['term']); ?></span>
                                    </a>
                                <?php else : ?>
                                    <span title="<?= $escaper->escapeHtmlAttr($termData['term']); ?>"><?= $escaper->escapeHtml($termData['term']); ?></span>
                                <?php endif; ?>
                            </td>
                            <td class="col-number"><?= $termData['sessions']; ?></td>
                            <td class="col-number"><?= $termData['visitors']; ?></td>
                            <td class="col-number"><?= $termData['result_count']; ?></td>
                            <?php if ($block->getShowConversionRate()) : ?>
                                <td class="col-number"><?= number_format($termData['conversion_rate'] * 100, 2); ?> %</td>
                            <?php endif; ?>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            <?php endif; ?>
            <?php if (!empty($hiddenTermsData)) : ?>
                <tfoot>
                    <tr>
                        <td colspan="<?= ($block->getShowConversionRate() ? 5 : 4) ?>" style="text-align:right; padding: 20px;">
                            <a href="javascript:void(0)" id="<?= $block->getJsId() ?>_toggle"><?= __('Show more...'); ?></a>
                        </td>
                    </tr>
                </tfoot>
            <?php endif; ?>
        </table>
    </div>
</div>

<script>
    require([
        'jquery'
    ], function($){
        $(function() {

            $("#<?= $block->getJsId() ?> .action-help").on('click', function(event) {
                event.preventDefault();
                $("#<?= $block->getJsId() ?> .dashboard-item-help").slideToggle();
            });

            $("#<?= $block->getJsId() ?>_toggle").on('click', function() {
                if ($("#<?= $block->getJsId() ?>_extra").is(":hidden")) {
                    $(this).text('<?= $block->escapeJs(__('Show less...')) ?>');
                } else {
                    $(this).text('<?= $block->escapeJs(__('Show more...')) ?>');
                }
                $("#<?= $block->getJsId() ?>_extra").slideToggle();
                return false;
            });

            // Copy table to clipboard using Clipboard API.
            $("#<?= $block->getJsId() ?>_copy").on("click", function () {
                const $table = $("#<?= $block->getJsId() ?> table.terms-report");
                let output = "";

                // Header row.
                const headers = [];
                $table.find("thead th").each(function () {
                    headers.push($(this).text().trim());
                });
                output += headers.join("\t") + "\n";

                // All rows (visible + hidden).
                $table.find("tbody tr").each(function () {
                    const row = [];
                    $(this).find("td").each(function () {
                        row.push($(this).text().trim());
                    });
                    output += row.join("\t") + "\n";
                });

                // Copy to clipboard.
                const $copyFeedback = $("#<?= $block->getJsId() ?>_copy");
                const blob = new Blob([output], { type: "text/plain" });
                const item = new ClipboardItem({ "text/plain": Promise.resolve(blob) });
                navigator.clipboard.write([item])
                    .then(() => {
                        console.log("✅ Copied to clipboard");

                        // Show feedback copy text.
                        $copyFeedback.addClass("show");

                        // Hide after 3 seconds.
                        setTimeout(() => {
                            $copyFeedback.removeClass("show");
                        }, 3000);
                    })
                    .catch(err => {
                        console.error("❌ Failed to copy: ", err);
                    });
            });
        });
    });
</script>

