<?php
/**
 * Admin Analytics Template
 *
 * Tab-based admin analytics with filters, KPI cards, status breakdown,
 * charts (bookings/revenue), category doughnut, and top products table.
 *
 * @package WahraRentalsBookings
 */

defined('ABSPATH') || exit;

$currency_symbol = html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8');

// Get vendors who have bookings (for dropdown filter)
$db = WAHRB_Database::instance();
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom table, simple distinct query
$vendors_with_bookings = $wpdb->get_results("SELECT DISTINCT b.vendor_id, u.display_name FROM {$db->table('bookings')} b LEFT JOIN {$wpdb->users} u ON b.vendor_id = u.ID WHERE b.deleted_at IS NULL ORDER BY u.display_name ASC", ARRAY_A) ?: [];
?>

<div class="wrap wahrb-aa">
    <h1><?php esc_html_e('Wahra Bookings Statistics', 'wahra-rentals-bookings'); ?></h1>

    <!-- ─── Filters bar ─── -->
    <div class="wahrb-aa-filters">
        <div class="wahrb-aa-filter-group">
            <label for="wahrb-aa-period"><?php esc_html_e('Period', 'wahra-rentals-bookings'); ?></label>
            <select id="wahrb-aa-period">
                <option value="week"><?php esc_html_e('Last week', 'wahra-rentals-bookings'); ?></option>
                <option value="month" selected><?php esc_html_e('Last month', 'wahra-rentals-bookings'); ?></option>
                <option value="quarter"><?php esc_html_e('Last 3 months', 'wahra-rentals-bookings'); ?></option>
                <option value="year"><?php esc_html_e('Last year', 'wahra-rentals-bookings'); ?></option>
            </select>
        </div>
        <?php if (count($vendors_with_bookings) > 1) : ?>
        <div class="wahrb-aa-filter-group">
            <label for="wahrb-aa-vendor"><?php esc_html_e('Vendor', 'wahra-rentals-bookings'); ?></label>
            <select id="wahrb-aa-vendor">
                <option value=""><?php esc_html_e('All vendors', 'wahra-rentals-bookings'); ?></option>
                <?php foreach ($vendors_with_bookings as $v) : ?>
                <option value="<?php echo esc_attr($v['vendor_id']); ?>">
                    <?php echo esc_html($v['display_name'] ?: __('Vendor', 'wahra-rentals-bookings') . ' #' . $v['vendor_id']); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php endif; ?>
    </div>

    <!-- ─── Loading ─── -->
    <div id="wahrb-aa-loading" class="wahrb-aa-loading">
        <span class="spinner is-active" style="float:none;"></span>
        <?php esc_html_e('Loading statistics...', 'wahra-rentals-bookings'); ?>
    </div>

    <!-- ─── Main content (hidden until loaded) ─── -->
    <div id="wahrb-aa-content" style="display:none;">

        <!-- KPI Cards (always visible above tabs) -->
        <div class="wahrb-aa-kpis">
            <div class="wahrb-aa-kpi wahrb-aa-kpi--bookings">
                <div class="wahrb-aa-kpi-icon">&#128203;</div>
                <div class="wahrb-aa-kpi-body">
                    <span class="wahrb-aa-kpi-label"><?php esc_html_e('Total Bookings', 'wahra-rentals-bookings'); ?></span>
                    <span class="wahrb-aa-kpi-value" id="wa-total">0</span>
                </div>
            </div>
            <div class="wahrb-aa-kpi wahrb-aa-kpi--revenue">
                <div class="wahrb-aa-kpi-icon">&#128176;</div>
                <div class="wahrb-aa-kpi-body">
                    <span class="wahrb-aa-kpi-label"><?php esc_html_e('Revenue', 'wahra-rentals-bookings'); ?></span>
                    <span class="wahrb-aa-kpi-value" id="wa-revenue">0</span>
                </div>
            </div>
            <div class="wahrb-aa-kpi wahrb-aa-kpi--rate">
                <div class="wahrb-aa-kpi-icon">&#128200;</div>
                <div class="wahrb-aa-kpi-body">
                    <span class="wahrb-aa-kpi-label"><?php esc_html_e('Conversion Rate', 'wahra-rentals-bookings'); ?></span>
                    <span class="wahrb-aa-kpi-value" id="wa-rate">0%</span>
                </div>
            </div>
            <div class="wahrb-aa-kpi wahrb-aa-kpi--vendors">
                <div class="wahrb-aa-kpi-icon">&#128101;</div>
                <div class="wahrb-aa-kpi-body">
                    <span class="wahrb-aa-kpi-label"><?php esc_html_e('Active Vendors', 'wahra-rentals-bookings'); ?></span>
                    <span class="wahrb-aa-kpi-value" id="wa-vendors">0</span>
                </div>
            </div>
        </div>

        <!-- Activity badges -->
        <div class="wahrb-aa-activity">
            <span class="wahrb-aa-badge wahrb-aa-badge--upcoming">
                &#128197; <?php esc_html_e('Upcoming', 'wahra-rentals-bookings'); ?>: <strong id="wa-upcoming">0</strong>
            </span>
            <span class="wahrb-aa-badge wahrb-aa-badge--checkin">
                &#9989; <?php esc_html_e('Today check-ins', 'wahra-rentals-bookings'); ?>: <strong id="wa-checkins">0</strong>
            </span>
            <span class="wahrb-aa-badge wahrb-aa-badge--checkout">
                &#128682; <?php esc_html_e('Today check-outs', 'wahra-rentals-bookings'); ?>: <strong id="wa-checkouts">0</strong>
            </span>
        </div>

        <!-- ─── Tab navigation ─── -->
        <div class="wahrb-aa-tabs">
            <button class="wahrb-aa-tab wahrb-aa-tab--active" data-tab="overview">
                <?php esc_html_e('Overview', 'wahra-rentals-bookings'); ?>
            </button>
            <button class="wahrb-aa-tab" data-tab="charts">
                <?php esc_html_e('Charts', 'wahra-rentals-bookings'); ?>
            </button>
            <button class="wahrb-aa-tab" data-tab="breakdown">
                <?php esc_html_e('Products & Categories', 'wahra-rentals-bookings'); ?>
            </button>
        </div>

        <!-- ═══ Tab 1: Overview ═══ -->
        <div class="wahrb-aa-panel wahrb-aa-panel--active" id="wahrb-panel-overview">

            <!-- Status breakdown -->
            <div class="wahrb-aa-section">
                <h3><?php esc_html_e('Status Breakdown', 'wahra-rentals-bookings'); ?></h3>
                <div id="wa-status-breakdown" class="wahrb-aa-status-grid"></div>
            </div>

            <!-- Status doughnut chart -->
            <div class="wahrb-aa-section">
                <h3><?php esc_html_e('Status Distribution', 'wahra-rentals-bookings'); ?></h3>
                <div class="wahrb-aa-chart-wrap wahrb-aa-chart-wrap--small"><canvas id="wa-status-chart"></canvas></div>
            </div>
        </div>

        <!-- ═══ Tab 2: Charts ═══ -->
        <div class="wahrb-aa-panel" id="wahrb-panel-charts">
            <div class="wahrb-aa-charts-row">
                <div class="wahrb-aa-chart-card">
                    <h3><?php esc_html_e('Bookings per month', 'wahra-rentals-bookings'); ?></h3>
                    <div class="wahrb-aa-chart-wrap"><canvas id="wa-bookings-chart"></canvas></div>
                </div>
                <div class="wahrb-aa-chart-card">
                    <h3><?php esc_html_e('Revenue per month', 'wahra-rentals-bookings'); ?></h3>
                    <div class="wahrb-aa-chart-wrap"><canvas id="wa-revenue-chart"></canvas></div>
                </div>
            </div>
        </div>

        <!-- ═══ Tab 3: Products & Categories ═══ -->
        <div class="wahrb-aa-panel" id="wahrb-panel-breakdown">
            <div class="wahrb-aa-breakdown-grid">
                <!-- Category breakdown -->
                <div class="wahrb-aa-section">
                    <h3><?php esc_html_e('Breakdown by Category', 'wahra-rentals-bookings'); ?></h3>
                    <div class="wahrb-aa-chart-wrap wahrb-aa-chart-wrap--small"><canvas id="wa-category-chart"></canvas></div>
                    <div id="wa-category-table" class="wahrb-aa-cat-table"></div>
                </div>
                <!-- Top products -->
                <div class="wahrb-aa-section">
                    <h3><?php esc_html_e('Top Products', 'wahra-rentals-bookings'); ?></h3>
                    <table class="wp-list-table widefat fixed striped">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th><?php esc_html_e('Product', 'wahra-rentals-bookings'); ?></th>
                                <th><?php esc_html_e('Bookings', 'wahra-rentals-bookings'); ?></th>
                                <th><?php esc_html_e('Revenue', 'wahra-rentals-bookings'); ?></th>
                            </tr>
                        </thead>
                        <tbody id="wa-top-products">
                            <tr><td colspan="4"><?php esc_html_e('No data available', 'wahra-rentals-bookings'); ?></td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    </div><!-- /#wahrb-aa-content -->
</div>

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

    var apiUrl = <?php echo wp_json_encode(untrailingslashit(rest_url('wahrb/v1'))); ?>;
    var nonce  = <?php echo wp_json_encode(wp_create_nonce('wp_rest')); ?>;
    var currencySymbol = <?php echo wp_json_encode($currency_symbol); ?>;
    var bChart = null, rChart = null, catChart = null, statusChart = null;

    var statusLabels = {
        'pending':     <?php echo wp_json_encode(__('Pending', 'wahra-rentals-bookings')); ?>,
        'confirmed':   <?php echo wp_json_encode(__('Confirmed', 'wahra-rentals-bookings')); ?>,
        'checked_in':  <?php echo wp_json_encode(__('Checked In', 'wahra-rentals-bookings')); ?>,
        'checked_out': <?php echo wp_json_encode(__('Checked Out', 'wahra-rentals-bookings')); ?>,
        'completed':   <?php echo wp_json_encode(__('Completed', 'wahra-rentals-bookings')); ?>,
        'cancelled':   <?php echo wp_json_encode(__('Cancelled', 'wahra-rentals-bookings')); ?>,
        'failed':      <?php echo wp_json_encode(__('Failed', 'wahra-rentals-bookings')); ?>
    };
    var statusColors = {
        'pending':'#f59e0b','confirmed':'#10b981','checked_in':'#3b82f6',
        'checked_out':'#8b5cf6','completed':'#059669','cancelled':'#ef4444','failed':'#6b7280'
    };

    function fmt(a) { return parseFloat(a||0).toFixed(2) + ' ' + currencySymbol; }
    function esc(s) { var d = document.createElement('div'); d.textContent = String(s); return d.innerHTML; }

    /* ── Tab switching ── */
    $('.wahrb-aa-tab').on('click', function() {
        var tab = $(this).data('tab');
        $('.wahrb-aa-tab').removeClass('wahrb-aa-tab--active');
        $(this).addClass('wahrb-aa-tab--active');
        $('.wahrb-aa-panel').removeClass('wahrb-aa-panel--active');
        $('#wahrb-panel-' + tab).addClass('wahrb-aa-panel--active');
        /* Resize charts when switching to Charts or Breakdown tab */
        if (tab === 'charts') {
            if (bChart) bChart.resize();
            if (rChart) rChart.resize();
        }
        if (tab === 'breakdown' && catChart) catChart.resize();
        if (tab === 'overview' && statusChart) statusChart.resize();
    });

    /* ── Load stats from API ── */
    function load() {
        var params = { period: $('#wahrb-aa-period').val() };
        var vendorSel = $('#wahrb-aa-vendor');
        if (vendorSel.length && vendorSel.val()) {
            params.vendor_id = vendorSel.val();
        }
        $('#wahrb-aa-loading').show();
        $('#wahrb-aa-content').hide();

        $.ajax({
            url: apiUrl + '/admin/bookings/stats',
            method: 'GET',
            dataType: 'json',
            data: params,
            beforeSend: function(x) { x.setRequestHeader('X-WP-Nonce', nonce); },
            success: function(res) {
                var d = res.data || res;

                /* KPI cards */
                $('#wa-total').text(d.total_bookings || 0);
                $('#wa-revenue').text(fmt(d.total_revenue));
                $('#wa-rate').text((d.conversion_rate || 0) + '%');
                $('#wa-vendors').text(d.active_vendors || 0);

                /* Activity badges */
                $('#wa-upcoming').text(d.upcoming || d.upcoming_bookings || 0);
                $('#wa-checkins').text(d.today_checkins || 0);
                $('#wa-checkouts').text(d.today_checkouts || 0);

                /* Status breakdown cards */
                var sb = d.status_breakdown || {}, html = '';
                for (var s in statusLabels) {
                    var count = sb[s] || 0;
                    html += '<div class="wahrb-aa-status-card" style="border-left:4px solid ' + statusColors[s] + '">';
                    html += '<div class="wahrb-aa-status-count" style="color:' + statusColors[s] + '">' + count + '</div>';
                    html += '<div class="wahrb-aa-status-label">' + esc(statusLabels[s]) + '</div>';
                    html += '</div>';
                }
                $('#wa-status-breakdown').html(html);

                /* Render all chart sections */
                renderStatusChart(sb);
                renderMonthlyCharts(d.monthly_data || []);
                renderProducts(d.top_products || []);
                renderCategories(d.category_breakdown || []);

                $('#wahrb-aa-loading').hide();
                $('#wahrb-aa-content').show();
            },
            error: function(xhr, textStatus) {
                console.error('WAHRB Admin Analytics error:', textStatus, xhr.status, xhr.statusText);
                if (xhr.responseText) { console.error('Response (500):', xhr.responseText.substring(0, 500)); }
                var msg = <?php echo wp_json_encode(__('Error loading statistics.', 'wahra-rentals-bookings')); ?>;
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    msg += ' ' + xhr.responseJSON.message;
                } else if (textStatus === 'parsererror') {
                    msg += ' ' + <?php echo wp_json_encode(__('(Invalid server response)', 'wahra-rentals-bookings')); ?>;
                } else if (xhr.status) {
                    msg += ' (HTTP ' + xhr.status + ')';
                }
                $('#wahrb-aa-loading').html('<span style="color:#ef4444;font-weight:500;">' + esc(msg) + '</span>');
            }
        });
    }

    /* ── Status doughnut chart ── */
    function renderStatusChart(sb) {
        var labels = [], data = [], colors = [];
        for (var s in statusLabels) {
            var c = sb[s] || 0;
            if (c > 0) {
                labels.push(statusLabels[s]);
                data.push(c);
                colors.push(statusColors[s]);
            }
        }
        var el = document.getElementById('wa-status-chart');
        if (statusChart) statusChart.destroy();
        if (!el || !data.length) return;
        statusChart = new Chart(el, {
            type: 'doughnut',
            data: { labels: labels, datasets: [{ data: data, backgroundColor: colors, borderWidth: 2, borderColor: '#fff' }] },
            options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'right', labels: { padding: 12, font: { size: 13 }, usePointStyle: true, pointStyle: 'circle' } } }, cutout: '60%' }
        });
    }

    /* ── Monthly bar charts ── */
    function renderMonthlyCharts(m) {
        var labels = m.map(function(d) { return d.month; });
        var bk = m.map(function(d) { return d.bookings; });
        var rv = m.map(function(d) { return d.revenue; });
        var c1 = document.getElementById('wa-bookings-chart');
        var c2 = document.getElementById('wa-revenue-chart');
        if (bChart) bChart.destroy();
        if (rChart) rChart.destroy();
        if (c1) bChart = new Chart(c1, { type: 'bar', data: { labels: labels, datasets: [{ label: <?php echo wp_json_encode(__('Bookings', 'wahra-rentals-bookings')); ?>, data: bk, backgroundColor: 'rgba(37,99,235,0.75)', borderRadius: 4, borderSkipped: false }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, ticks: { stepSize: 1 }, grid: { color: '#f1f5f9' } }, x: { grid: { display: false } } } } });
        if (c2) rChart = new Chart(c2, { type: 'bar', data: { labels: labels, datasets: [{ label: <?php echo wp_json_encode(__('Revenue', 'wahra-rentals-bookings')); ?>, data: rv, backgroundColor: 'rgba(16,185,129,0.75)', borderRadius: 4, borderSkipped: false }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, grid: { color: '#f1f5f9' } }, x: { grid: { display: false } } } } });
    }

    /* ── Top products table ── */
    function renderProducts(products) {
        var $t = $('#wa-top-products');
        if (!products.length) {
            $t.html('<tr><td colspan="4">' + esc(<?php echo wp_json_encode(__('No data available', 'wahra-rentals-bookings')); ?>) + '</td></tr>');
            return;
        }
        var h = '';
        for (var i = 0; i < products.length; i++) {
            var p = products[i];
            h += '<tr><td>' + (i + 1) + '</td><td>' + esc(p.name) + '</td><td>' + parseInt(p.bookings) + '</td><td>' + fmt(p.revenue) + '</td></tr>';
        }
        $t.html(h);
    }

    /* ── Category doughnut + table ── */
    function renderCategories(cats) {
        var $tbl = $('#wa-category-table');
        var catColors = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899'];
        if (!cats.length) {
            if (catChart) { catChart.destroy(); catChart = null; }
            $tbl.html('<p style="color:#94a3b8;padding:12px 0;">' + esc(<?php echo wp_json_encode(__('No category data', 'wahra-rentals-bookings')); ?>) + '</p>');
            return;
        }
        var labels = [], data = [], colors = [];
        var h = '<table class="wp-list-table widefat fixed striped"><thead><tr>';
        h += '<th>' + esc(<?php echo wp_json_encode(__('Category', 'wahra-rentals-bookings')); ?>) + '</th>';
        h += '<th>' + esc(<?php echo wp_json_encode(__('Bookings', 'wahra-rentals-bookings')); ?>) + '</th>';
        h += '<th>' + esc(<?php echo wp_json_encode(__('Revenue', 'wahra-rentals-bookings')); ?>) + '</th>';
        h += '</tr></thead><tbody>';
        for (var i = 0; i < cats.length; i++) {
            var c = cats[i], clr = catColors[i % catColors.length];
            labels.push((c.emoji || '') + ' ' + c.label);
            data.push(c.bookings);
            colors.push(clr);
            h += '<tr><td><span style="display:inline-block;width:12px;height:12px;border-radius:3px;background:' + clr + ';margin-right:8px;vertical-align:middle;"></span>' + esc((c.emoji || '') + ' ' + c.label) + '</td>';
            h += '<td>' + parseInt(c.bookings) + '</td><td>' + fmt(c.revenue) + '</td></tr>';
        }
        h += '</tbody></table>';
        $tbl.html(h);

        var cc = document.getElementById('wa-category-chart');
        if (catChart) catChart.destroy();
        if (cc) catChart = new Chart(cc, {
            type: 'doughnut',
            data: { labels: labels, datasets: [{ data: data, backgroundColor: colors, borderWidth: 2, borderColor: '#fff' }] },
            options: { responsive: true, maintainAspectRatio: false, cutout: '55%', plugins: { legend: { position: 'bottom', labels: { padding: 10, font: { size: 12 }, usePointStyle: true, pointStyle: 'circle' } } } }
        });
    }

    /* ── Bind filter changes ── */
    $('#wahrb-aa-period, #wahrb-aa-vendor').on('change', load);
    $(document).ready(load);

})(jQuery);
</script>

