<?php
/**
 * Conversions tab body.
 *
 * Rendered via kantan_render_conversions_tab(). Available vars:
 *   $days, $total_conversions, $conversion_summary, $conversions_by_source,
 *   $recent_conversions, $show_seo_upsell (bool), $upsell_full (bool)
 */
if (!defined('ABSPATH')) {
    exit;
}

// Bar colors cycled for conversion types.
$type_palette = array('bg-blue-500', 'bg-emerald-500', 'bg-amber-500', 'bg-purple-500', 'bg-pink-500', 'bg-cyan-500', 'bg-orange-500', 'bg-indigo-500');

// Traffic-source colors, consistent with the Overview tab.
$source_bar = array('organic' => 'bg-green-500', 'direct' => 'bg-blue-500', 'referral' => 'bg-purple-500', 'social' => 'bg-pink-500', 'ai' => 'bg-amber-500', 'unknown' => 'bg-gray-400');
$source_pill = array(
    'organic'  => 'bg-green-100 text-green-800',
    'direct'   => 'bg-blue-100 text-blue-800',
    'referral' => 'bg-purple-100 text-purple-800',
    'social'   => 'bg-pink-100 text-pink-800',
    'ai'       => 'bg-amber-100 text-amber-800',
    'unknown'  => 'bg-gray-100 text-gray-600',
);

// Reused linked label: "Settings › Conversion Links".
$settings_link_label = esc_html__('Settings › Conversion Links', 'kantan-analytics');
?>

<!-- ==================== CONVERSIONS TAB ==================== -->

<div class="flex justify-between items-center mb-6">
    <h1 class="text-2xl font-bold text-gray-900"><?php esc_html_e('Conversions', 'kantan-analytics'); ?></h1>
    <?php /* translators: %d: number of days in the reporting period */ ?>
    <span class="text-sm text-gray-400"><?php printf(esc_html__('Last %d days', 'kantan-analytics'), (int) $days); ?></span>
</div>

<?php if ($total_conversions <= 0): ?>

    <!-- Empty state -->
    <div class="bg-white rounded-xl shadow-md p-6 mb-8">
        <div class="text-center py-10">
            <svg class="w-12 h-12 text-gray-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
            <p class="text-gray-700 font-medium"><?php esc_html_e('No conversions recorded yet', 'kantan-analytics'); ?></p>
            <p class="text-gray-500 text-sm mt-1 max-w-md mx-auto">
                <?php esc_html_e('Define what counts as a conversion under', 'kantan-analytics'); ?>
                <a href="?page=kantan-analytics&tab=settings&days=<?php echo (int) $days; ?>" class="text-blue-600 hover:underline"><?php echo $settings_link_label; ?></a>.
                <?php esc_html_e('Phone, email, and directions clicks plus form submissions are tracked automatically.', 'kantan-analytics'); ?>
            </p>
        </div>
    </div>

<?php else: ?>

    <!-- Hero total -->
    <div class="bg-white rounded-xl shadow-md p-6 mb-8">
        <p class="text-sm font-medium text-gray-500"><?php esc_html_e('Total Conversions', 'kantan-analytics'); ?></p>
        <p class="text-4xl font-bold text-gray-900 mt-1"><?php echo number_format($total_conversions); ?></p>
        <p class="text-sm text-gray-400 mt-1"><?php
            $type_count = count($conversion_summary);
            /* translators: 1: number of conversion types (already formatted), 2: number of days */
            printf(
                esc_html(_n(
                    '%1$s conversion type in the last %2$d days',
                    '%1$s conversion types in the last %2$d days',
                    $type_count,
                    'kantan-analytics'
                )),
                number_format($type_count),
                (int) $days
            );
        ?></p>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">

        <!-- By type -->
        <div class="bg-white rounded-xl shadow-md p-6">
            <h2 class="text-2xl font-bold text-gray-900 mb-6"><?php esc_html_e('By Type', 'kantan-analytics'); ?></h2>
            <div class="space-y-4">
                <?php $ti = 0; foreach ($conversion_summary as $row):
                    $pct = $total_conversions > 0 ? round(($row->total / $total_conversions) * 100, 1) : 0;
                    $bar = $type_palette[$ti % count($type_palette)];
                ?>
                    <div>
                        <div class="flex justify-between items-center mb-1">
                            <span class="text-gray-700 font-medium"><?php echo esc_html(kantan_format_conversion_type($row->conversion_type)); ?></span>
                            <span class="text-gray-600"><?php echo number_format($row->total); ?> <span class="text-sm">(<?php echo esc_html($pct); ?>%)</span></span>
                        </div>
                        <div class="w-full bg-gray-200 rounded-full h-3">
                            <div class="<?php echo esc_attr($bar); ?> h-3 rounded-full transition-all" style="width: <?php echo esc_attr($pct); ?>%"></div>
                        </div>
                    </div>
                <?php $ti++; endforeach; ?>
            </div>
        </div>

        <!-- By source -->
        <div class="bg-white rounded-xl shadow-md p-6">
            <h2 class="text-2xl font-bold text-gray-900 mb-6"><?php esc_html_e('By Traffic Source', 'kantan-analytics'); ?></h2>
            <div class="space-y-4">
                <?php foreach ($conversions_by_source as $row):
                    $src = $row->traffic_source ?: 'unknown';
                    $pct = $total_conversions > 0 ? round(($row->total / $total_conversions) * 100, 1) : 0;
                    $bar = $source_bar[$src] ?? 'bg-gray-400';
                ?>
                    <div>
                        <div class="flex justify-between items-center mb-1">
                            <span class="text-gray-700 font-medium capitalize"><?php echo esc_html($src); ?></span>
                            <span class="text-gray-600"><?php echo number_format($row->total); ?> <span class="text-sm">(<?php echo esc_html($pct); ?>%)</span></span>
                        </div>
                        <div class="w-full bg-gray-200 rounded-full h-3">
                            <div class="<?php echo esc_attr($bar); ?> h-3 rounded-full transition-all" style="width: <?php echo esc_attr($pct); ?>%"></div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

    </div>

    <!-- Recent conversions -->
    <div class="bg-white rounded-xl shadow-md p-6 mb-8">
        <div class="flex justify-between items-center mb-6">
            <div class="flex items-center gap-2">
                <h2 class="text-2xl font-bold text-gray-900"><?php esc_html_e('Recent Conversions', 'kantan-analytics'); ?></h2>
                <?php kantan_ai_prompts('analytics-conversions'); ?>
            </div>
            <span class="text-sm text-gray-400"><?php esc_html_e('10 most recent', 'kantan-analytics'); ?></span>
        </div>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Type', 'kantan-analytics'); ?></th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Detail', 'kantan-analytics'); ?></th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Page', 'kantan-analytics'); ?></th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Source', 'kantan-analytics'); ?></th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('When', 'kantan-analytics'); ?></th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php foreach ($recent_conversions as $conv):
                        $src = $conv->traffic_source ?: 'unknown';
                        $pill = $source_pill[$src] ?? 'bg-gray-100 text-gray-600';
                        $conv_ts = strtotime($conv->converted_at);
                        /* translators: %s: human-readable time difference, e.g. "3 hours" */
                        $ago_text = sprintf(__('%s ago', 'kantan-analytics'), human_time_diff($conv_ts));
                    ?>
                        <tr class="hover:bg-gray-50 cursor-pointer kantan-conv-row"
                            title="<?php esc_attr_e('View full detail', 'kantan-analytics'); ?>"
                            data-type="<?php echo esc_attr(kantan_format_conversion_type($conv->conversion_type)); ?>"
                            data-label="<?php echo esc_attr($conv->conversion_label); ?>"
                            data-value="<?php echo esc_attr($conv->conversion_value); ?>"
                            data-page="<?php echo esc_attr($conv->page_url); ?>"
                            data-source="<?php echo esc_attr($src); ?>"
                            data-referrer="<?php echo esc_attr($conv->referrer); ?>"
                            data-when="<?php echo esc_attr(date_i18n('M j, Y · g:i a', $conv_ts)); ?>"
                            data-ago="<?php echo esc_attr($ago_text); ?>">
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="px-3 py-1 inline-flex text-xs leading-5 font-semibold rounded-full bg-emerald-100 text-emerald-800"><?php echo esc_html(kantan_format_conversion_type($conv->conversion_type)); ?></span>
                            </td>
                            <td class="px-6 py-4">
                                <div class="text-sm text-gray-700 truncate" style="max-width: 240px;"><?php echo esc_html($conv->conversion_label ?: '—'); ?></div>
                            </td>
                            <td class="px-6 py-4">
                                <div class="text-sm text-gray-500 truncate" style="max-width: 280px;"><?php echo esc_html($conv->page_url); ?></div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="px-2 py-0.5 inline-flex text-xs font-medium rounded capitalize <?php echo esc_attr($pill); ?>"><?php echo esc_html($src); ?></span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php
                                /* translators: %s: human-readable time difference, e.g. "3 hours" */
                                printf(esc_html__('%s ago', 'kantan-analytics'), human_time_diff(strtotime($conv->converted_at)));
                            ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <p class="text-xs text-gray-400 mt-4"><?php esc_html_e('Adjust what counts as a conversion under', 'kantan-analytics'); ?> <a href="?page=kantan-analytics&amp;tab=settings&amp;days=<?php echo (int) $days; ?>" class="text-blue-600 hover:underline"><?php echo $settings_link_label; ?></a>.</p>
    </div>

<?php endif; ?>

<?php if ($show_seo_upsell): ?>
    <?php if ($upsell_full): ?>

        <!-- SEO upsell — full (directly-distributed build) -->
        <div class="rounded-xl border border-blue-200 bg-gradient-to-br from-blue-50 to-indigo-50 p-6">
            <div class="flex flex-col lg:flex-row lg:items-center gap-6">
                <div class="flex-1">
                    <span class="inline-block text-xs font-semibold uppercase tracking-wider text-blue-700 bg-blue-100 rounded px-2 py-0.5 mb-3">Kantan SEO</span>
                    <h2 class="text-xl font-bold text-gray-900"><?php esc_html_e('See the revenue behind these conversions', 'kantan-analytics'); ?></h2>
                    <p class="text-gray-600 text-sm mt-2 max-w-xl"><?php
                        echo wp_kses_post(__('Kantan Analytics tells you <em>how many</em> conversions you got. Kantan SEO tells you <em>what they\'re worth</em> and <em>what drove them</em>.', 'kantan-analytics'));
                    ?></p>
                    <ul class="mt-4 space-y-2 text-sm text-gray-700">
                        <li class="flex items-start gap-2"><svg class="w-5 h-5 text-blue-600 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg><?php echo wp_kses_post(__('Assign a <strong>dollar value</strong> to every conversion type', 'kantan-analytics')); ?></li>
                        <li class="flex items-start gap-2"><svg class="w-5 h-5 text-blue-600 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg><?php echo wp_kses_post(__('Attribute conversions to <strong>organic keywords and landing pages</strong>', 'kantan-analytics')); ?></li>
                        <li class="flex items-start gap-2"><svg class="w-5 h-5 text-blue-600 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg><?php echo wp_kses_post(__('Track conversion <strong>value against your rankings</strong> over time', 'kantan-analytics')); ?></li>
                        <li class="flex items-start gap-2"><svg class="w-5 h-5 text-blue-600 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg><?php echo wp_kses_post(__('Browse your <strong>full conversion history</strong> — not just the 10 most recent', 'kantan-analytics')); ?></li>
                    </ul>
                </div>
                <div class="lg:w-64 flex-shrink-0">
                    <!-- locked preview -->
                    <div class="bg-white rounded-lg border border-gray-200 p-4 mb-4">
                        <p class="text-xs text-gray-400 mb-2"><?php esc_html_e('Conversion value (with SEO)', 'kantan-analytics'); ?></p>
                        <div class="flex items-center justify-between text-sm py-1">
                            <span class="text-gray-500"><?php esc_html_e('Phone', 'kantan-analytics'); ?></span>
                            <span class="font-mono text-gray-300 blur-[2px] select-none">$1,2••</span>
                        </div>
                        <div class="flex items-center justify-between text-sm py-1">
                            <span class="text-gray-500"><?php esc_html_e('Form', 'kantan-analytics'); ?></span>
                            <span class="font-mono text-gray-300 blur-[2px] select-none">$8••</span>
                        </div>
                    </div>
                    <a href="<?php echo esc_url('https://trykantan.com/seo/'); ?>" target="_blank" rel="noopener" class="block w-full text-center px-4 py-2.5 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition text-sm"><?php esc_html_e('Upgrade to Kantan SEO', 'kantan-analytics'); ?></a>
                </div>
            </div>
        </div>

    <?php else: ?>

        <!-- SEO upsell — restrained (wp.org build) -->
        <div class="rounded-xl border border-gray-200 bg-gray-50 p-6">
            <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                    <h2 class="text-base font-semibold text-gray-900"><?php esc_html_e('See the revenue behind your conversions', 'kantan-analytics'); ?></h2>
                    <p class="text-gray-600 text-sm mt-1 max-w-2xl"><?php esc_html_e('Kantan SEO assigns a dollar value to every conversion, shows your full conversion history (Analytics lists the 10 most recent here), and reveals which organic keywords and landing pages drove them.', 'kantan-analytics'); ?></p>
                </div>
                <a href="<?php echo esc_url('https://trykantan.com/seo/'); ?>" target="_blank" rel="noopener" class="flex-shrink-0 text-sm font-medium text-blue-600 hover:text-blue-700 hover:underline whitespace-nowrap"><?php esc_html_e('Learn more about Kantan SEO →', 'kantan-analytics'); ?></a>
            </div>
        </div>

    <?php endif; ?>
<?php endif; ?>

<!-- Conversion detail modal -->
<div id="kantan-conv-modal" class="fixed inset-0 z-[99999] hidden flex items-center justify-center p-4" style="margin:0!important;">
    <div class="absolute inset-0 bg-black/50" id="kantan-conv-modal-backdrop"></div>
    <div class="relative bg-white rounded-2xl shadow-2xl w-full max-w-2xl p-6 max-h-[90vh] overflow-y-auto">
        <div class="flex items-center justify-between mb-5">
            <h3 class="text-lg font-bold text-gray-900"><?php esc_html_e('Conversion detail', 'kantan-analytics'); ?></h3>
            <button type="button" id="kantan-conv-modal-close" class="text-gray-400 hover:text-gray-600 p-1" aria-label="<?php esc_attr_e('Close', 'kantan-analytics'); ?>">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
            </button>
        </div>
        <dl class="space-y-3 text-sm">
            <div class="flex justify-between gap-4">
                <dt class="text-gray-500 flex-shrink-0"><?php esc_html_e('Type', 'kantan-analytics'); ?></dt>
                <dd class="text-gray-900 font-medium text-right" id="kantan-conv-type"></dd>
            </div>
            <div class="flex justify-between gap-4">
                <dt class="text-gray-500 flex-shrink-0"><?php esc_html_e('When', 'kantan-analytics'); ?></dt>
                <dd class="text-gray-900 text-right" id="kantan-conv-when"></dd>
            </div>
            <div class="flex justify-between gap-4">
                <dt class="text-gray-500 flex-shrink-0"><?php esc_html_e('Traffic source', 'kantan-analytics'); ?></dt>
                <dd class="text-gray-900 text-right capitalize" id="kantan-conv-source"></dd>
            </div>
            <div class="pt-3 border-t border-gray-100">
                <dt class="text-gray-500 mb-1"><?php esc_html_e('Detail', 'kantan-analytics'); ?></dt>
                <dd class="text-gray-900 break-words" id="kantan-conv-label"></dd>
            </div>
            <div id="kantan-conv-value-row">
                <dt class="text-gray-500 mb-1"><?php esc_html_e('Value', 'kantan-analytics'); ?></dt>
                <dd class="text-gray-900 break-all" id="kantan-conv-value"></dd>
            </div>
            <div>
                <dt class="text-gray-500 mb-1"><?php esc_html_e('Page', 'kantan-analytics'); ?></dt>
                <dd class="break-all"><a id="kantan-conv-page" target="_blank" rel="noopener" class="text-blue-600 hover:underline"></a></dd>
            </div>
            <div id="kantan-conv-referrer-row">
                <dt class="text-gray-500 mb-1"><?php esc_html_e('Referrer', 'kantan-analytics'); ?></dt>
                <dd class="break-all"><a id="kantan-conv-referrer" target="_blank" rel="noopener" class="text-blue-600 hover:underline"></a></dd>
            </div>
        </dl>
    </div>
</div>

<?php ob_start(); ?>
(function() {
    'use strict';
    var modal = document.getElementById('kantan-conv-modal');
    if (!modal) return;
    var backdrop = document.getElementById('kantan-conv-modal-backdrop');
    var closeBtn = document.getElementById('kantan-conv-modal-close');

    function safeUrl(u) { return /^https?:\/\//i.test(u || '') ? u : ''; }
    function setText(id, val) { var el = document.getElementById(id); if (el) el.textContent = (val && val.length) ? val : '—'; }

    // Show a link if the value is a real http(s) URL, otherwise plain text; hide its row when empty.
    function setLink(linkId, rowId, val) {
        var el = document.getElementById(linkId);
        var row = rowId ? document.getElementById(rowId) : null;
        if (!el) return;
        var url = safeUrl(val);
        if (val && val.length) {
            el.textContent = val;
            if (url) { el.href = url; } else { el.removeAttribute('href'); }
            if (row) row.classList.remove('hidden');
        } else {
            el.textContent = '—';
            el.removeAttribute('href');
            if (row) row.classList.add('hidden');
        }
    }

    function openModal(d) {
        setText('kantan-conv-type', d.type);
        setText('kantan-conv-when', (d.when || '') + (d.ago ? ' · ' + d.ago : ''));
        setText('kantan-conv-source', d.source);
        setText('kantan-conv-label', d.label);

        var valRow = document.getElementById('kantan-conv-value-row');
        if (d.value && d.value.length) { setText('kantan-conv-value', d.value); if (valRow) valRow.classList.remove('hidden'); }
        else if (valRow) { valRow.classList.add('hidden'); }

        setLink('kantan-conv-page', null, d.page);
        setLink('kantan-conv-referrer', 'kantan-conv-referrer-row', d.referrer);

        modal.classList.remove('hidden');
    }
    function closeModal() { modal.classList.add('hidden'); }

    var rows = document.querySelectorAll('.kantan-conv-row');
    for (var i = 0; i < rows.length; i++) {
        rows[i].addEventListener('click', function() { openModal(this.dataset); });
    }
    if (closeBtn) closeBtn.addEventListener('click', closeModal);
    if (backdrop) backdrop.addEventListener('click', closeModal);
    document.addEventListener('keydown', function(e) { if (e.key === 'Escape') closeModal(); });
})();
<?php kantan_admin_inline_js( ob_get_clean() ); ?>
