<?php
/**
 * Dokan Vendor Analytics Template
 *
 * Fetches real booking stats from the REST API and renders
 * interactive charts, stat cards, status breakdown, and top products.
 *
 * @package WahraRentalsBookings
 */

defined('ABSPATH') || exit;

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

// Get vendor's products (including trashed) for the filter dropdown
$vendor_products = get_posts([
    'post_type'   => 'product',
    'post_status' => ['publish', 'draft', 'trash', 'pending'],
    'author'      => $vendor_id,
    'numberposts' => -1,
    'fields'      => 'ids',
]);
?>

<div class="dokan-dashboard-wrap">
    <?php do_action('dokan_dashboard_content_before'); ?>

    <div class="dokan-dashboard-content">
        <article class="dokan-product-listing-area wahrb-analytics-page">

            <!-- Page Header with Filters -->
            <header class="wahrb-page-header">
                <div class="wahrb-page-header-content">
                    <h1 class="wahrb-page-title">
                        <span class="wahrb-page-icon">&#x1F4CA;</span>
                        <?php esc_html_e('Rental Statistics', 'wahra-rentals-bookings'); ?>
                    </h1>
                    <p class="wahrb-page-description">
                        <?php esc_html_e('Track your rental performance and revenue.', 'wahra-rentals-bookings'); ?>
                    </p>
                </div>
                <div class="wahrb-filters">
                    <select class="wahrb-select" id="wahrb-period-filter">
                        <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>
                    <select class="wahrb-select" id="wahrb-product-filter">
                        <option value="0"><?php esc_html_e('All products', 'wahra-rentals-bookings'); ?></option>
                        <?php
                        foreach ($vendor_products as $pid) {
                            $p = wc_get_product($pid);
                            if ($p) {
                                printf(
                                    '<option value="%d">%s</option>',
                                    esc_attr($pid),
                                    esc_html($p->get_name())
                                );
                            }
                        }
                        ?>
                    </select>
                </div>
            </header>

            <!-- Loading indicator -->
            <div id="wahrb-loading" class="wahrb-loading">
                <span class="wahrb-spinner"></span>
                <?php esc_html_e('Loading statistics...', 'wahra-rentals-bookings'); ?>
            </div>

            <!-- Stats container (hidden until data loads) -->
            <div id="wahrb-stats-container" style="display:none;">

                <!-- Summary Stats Cards (always visible above tabs) -->
                <div class="wahrb-stats-grid">
                    <div class="wahrb-stat-card">
                        <div class="wahrb-stat-icon wahrb-stat-icon-primary"><span>&#x1F4C5;</span></div>
                        <div class="wahrb-stat-content">
                            <span class="wahrb-stat-value" id="wahrb-total-bookings">0</span>
                            <span class="wahrb-stat-label"><?php esc_html_e('Total Bookings', 'wahra-rentals-bookings'); ?></span>
                        </div>
                    </div>
                    <div class="wahrb-stat-card">
                        <div class="wahrb-stat-icon wahrb-stat-icon-success"><span>&#x1F4B0;</span></div>
                        <div class="wahrb-stat-content">
                            <span class="wahrb-stat-value" id="wahrb-total-revenue">0</span>
                            <span class="wahrb-stat-label"><?php esc_html_e('Revenue', 'wahra-rentals-bookings'); ?></span>
                        </div>
                    </div>
                    <div class="wahrb-stat-card">
                        <div class="wahrb-stat-icon wahrb-stat-icon-info"><span>&#x1F4C8;</span></div>
                        <div class="wahrb-stat-content">
                            <span class="wahrb-stat-value" id="wahrb-conversion-rate">0%</span>
                            <span class="wahrb-stat-label"><?php esc_html_e('Conversion Rate', 'wahra-rentals-bookings'); ?></span>
                        </div>
                    </div>
                    <div class="wahrb-stat-card">
                        <div class="wahrb-stat-icon wahrb-stat-icon-warning"><span>&#x23F3;</span></div>
                        <div class="wahrb-stat-content">
                            <span class="wahrb-stat-value" id="wahrb-upcoming">0</span>
                            <span class="wahrb-stat-label"><?php esc_html_e('Upcoming', 'wahra-rentals-bookings'); ?></span>
                        </div>
                    </div>
                </div>

                <!-- Tab Navigation -->
                <div class="wahrb-analytics-tabs">
                    <button type="button" class="wahrb-atab-btn active" data-atab="overview">
                        <span class="wahrb-atab-icon">&#x1F4CB;</span>
                        <span><?php esc_html_e('Overview', 'wahra-rentals-bookings'); ?></span>
                    </button>
                    <button type="button" class="wahrb-atab-btn" data-atab="charts">
                        <span class="wahrb-atab-icon">&#x1F4CA;</span>
                        <span><?php esc_html_e('Charts', 'wahra-rentals-bookings'); ?></span>
                    </button>
                    <button type="button" class="wahrb-atab-btn" data-atab="products">
                        <span class="wahrb-atab-icon">&#x1F4E6;</span>
                        <span><?php esc_html_e('Products & Categories', 'wahra-rentals-bookings'); ?></span>
                    </button>
                </div>

                <!-- Tab: Overview -->
                <div class="wahrb-atab-panel active" data-apanel="overview">

                    <!-- Today's Activity -->
                    <div class="wahrb-stats-grid wahrb-stats-grid-2" style="margin-bottom:1.5rem;">
                        <div class="wahrb-stat-card wahrb-stat-card-small">
                            <div class="wahrb-stat-icon wahrb-stat-icon-success"><span>&#x1F511;</span></div>
                            <div class="wahrb-stat-content">
                                <span class="wahrb-stat-value" id="wahrb-today-checkins">0</span>
                                <span class="wahrb-stat-label"><?php esc_html_e("Today's Check-ins", 'wahra-rentals-bookings'); ?></span>
                            </div>
                        </div>
                        <div class="wahrb-stat-card wahrb-stat-card-small">
                            <div class="wahrb-stat-icon wahrb-stat-icon-info"><span>&#x1F6AA;</span></div>
                            <div class="wahrb-stat-content">
                                <span class="wahrb-stat-value" id="wahrb-today-checkouts">0</span>
                                <span class="wahrb-stat-label"><?php esc_html_e("Today's Check-outs", 'wahra-rentals-bookings'); ?></span>
                            </div>
                        </div>
                    </div>

                    <!-- Status Breakdown -->
                    <div class="wahrb-card wahrb-status-breakdown">
                        <div class="wahrb-card-header">
                            <h3><?php esc_html_e('Booking Status Breakdown', 'wahra-rentals-bookings'); ?></h3>
                        </div>
                        <div class="wahrb-card-body">
                            <div class="wahrb-status-pills" id="wahrb-status-pills"></div>
                        </div>
                    </div>

                </div><!-- End Tab: Overview -->

                <!-- Tab: Charts -->
                <div class="wahrb-atab-panel" data-apanel="charts">
                    <div class="wahrb-charts-grid">
                        <div class="wahrb-chart-card">
                            <div class="wahrb-chart-header">
                                <h3><?php esc_html_e('Bookings per month', 'wahra-rentals-bookings'); ?></h3>
                            </div>
                            <div class="wahrb-chart-body">
                                <canvas id="wahrb-bookings-chart"></canvas>
                            </div>
                        </div>
                        <div class="wahrb-chart-card">
                            <div class="wahrb-chart-header">
                                <h3><?php esc_html_e('Revenue per month', 'wahra-rentals-bookings'); ?></h3>
                            </div>
                            <div class="wahrb-chart-body">
                                <canvas id="wahrb-revenue-chart"></canvas>
                            </div>
                        </div>
                    </div>
                </div><!-- End Tab: Charts -->

                <!-- Tab: Products & Categories -->
                <div class="wahrb-atab-panel" data-apanel="products">

                    <!-- Top Products Table -->
                    <div class="wahrb-card">
                        <div class="wahrb-card-header">
                            <h3><?php esc_html_e('Most rented products', 'wahra-rentals-bookings'); ?></h3>
                        </div>
                        <div class="wahrb-card-body wahrb-card-body-flush">
                            <table class="wahrb-table">
                                <thead>
                                    <tr>
                                        <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="wahrb-top-products">
                                    <tr>
                                        <td colspan="3" class="wahrb-table-empty">
                                            <?php esc_html_e('No data available', 'wahra-rentals-bookings'); ?>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Category Breakdown -->
                    <div class="wahrb-card">
                        <div class="wahrb-card-header">
                            <h3><?php esc_html_e('Breakdown by Category', 'wahra-rentals-bookings'); ?></h3>
                        </div>
                        <div class="wahrb-card-body">
                            <div class="wahrb-charts-grid" style="margin:0;">
                                <div style="position:relative;height:250px;"><canvas id="wahrb-category-chart"></canvas></div>
                                <div id="wahrb-category-table"></div>
                            </div>
                        </div>
                    </div>

                </div><!-- End Tab: Products & Categories -->

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

    <?php do_action('dokan_dashboard_content_after'); ?>
</div>

<script>
if (typeof wahrbVendorConfig === 'undefined') {
    var wahrbVendorConfig = <?php echo wp_json_encode([
        'apiUrl' => rest_url('wahrb/v1'),
        'nonce'  => wp_create_nonce('wp_rest'),
        'vendorId' => get_current_user_id(),
        'currency' => get_woocommerce_currency(),
        'currencySymbol' => html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8'),
    ]); ?>;
}
</script>
<script>
(function($) {
    'use strict';

    var config = typeof wahrbVendorConfig !== 'undefined' ? wahrbVendorConfig : {};
    var apiUrl = config.apiUrl || '';
    var nonce = config.nonce || '';
    var currencySymbol = <?php echo wp_json_encode($currency_symbol); ?>;
    var bookingsChart = null;
    var revenueChart = null;
    var categoryChart = 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 formatCurrency(amount) {
        return parseFloat(amount || 0).toFixed(2) + ' ' + currencySymbol;
    }

    function esc(str) {
        var d = document.createElement('div');
        d.textContent = String(str);
        return d.innerHTML;
    }

    function fetchStats() {
        var period = $('#wahrb-period-filter').val();
        var productId = $('#wahrb-product-filter').val();

        $('#wahrb-loading').show();
        $('#wahrb-stats-container').hide();

        $.ajax({
            url: apiUrl + '/vendor/bookings/stats',
            method: 'GET',
            dataType: 'json',
            data: { period: period, product_id: productId },
            beforeSend: function(xhr) {
                xhr.setRequestHeader('X-WP-Nonce', nonce);
            },
            success: function(response) {
                var data = response.data || response;
                renderStats(data);
                $('#wahrb-loading').hide();
                $('#wahrb-stats-container').show();
            },
            error: function(xhr) {
                console.error('WAHRB Analytics: Failed to load stats', xhr.responseText);
                var msg = <?php echo wp_json_encode(__('Error loading statistics. Please refresh.', 'wahra-rentals-bookings')); ?>;
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    msg += ' ' + xhr.responseJSON.message;
                } else if (xhr.status) {
                    msg += ' (HTTP ' + xhr.status + ')';
                }
                $('#wahrb-loading').html('<span style="color:#ef4444;">&#9888; ' + esc(msg) + '</span>');
            }
        });
    }

    function renderStats(data) {
        $('#wahrb-total-bookings').text(data.total_bookings || 0);
        $('#wahrb-total-revenue').text(formatCurrency(data.total_revenue));
        $('#wahrb-conversion-rate').text((data.conversion_rate || 0) + '%');
        $('#wahrb-upcoming').text(data.upcoming || 0);
        $('#wahrb-today-checkins').text(data.today_checkins || 0);
        $('#wahrb-today-checkouts').text(data.today_checkouts || 0);

        var pillsHtml = '';
        var breakdown = data.status_breakdown || {};
        for (var status in statusLabels) {
            var count = breakdown[status] || 0;
            var color = statusColors[status] || '#6b7280';
            pillsHtml += '<div class="wahrb-status-pill" style="border-left:4px solid ' + color + ';">';
            pillsHtml += '<span class="wahrb-pill-count" style="color:' + color + ';">' + count + '</span>';
            pillsHtml += '<span class="wahrb-pill-label">' + esc(statusLabels[status]) + '</span>';
            pillsHtml += '</div>';
        }
        $('#wahrb-status-pills').html(pillsHtml);

        renderBookingsChart(data.monthly_data || []);
        renderRevenueChart(data.monthly_data || []);
        renderTopProducts(data.top_products || []);
        renderCategories(data.category_breakdown || []);
    }

    function renderBookingsChart(monthlyData) {
        var labels = monthlyData.map(function(d) { return d.month; });
        var values = monthlyData.map(function(d) { return d.bookings; });
        var ctx = document.getElementById('wahrb-bookings-chart');
        if (!ctx) return;
        if (bookingsChart) bookingsChart.destroy();
        bookingsChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: <?php echo wp_json_encode(__('Bookings', 'wahra-rentals-bookings')); ?>,
                    data: values,
                    backgroundColor: 'rgba(37, 99, 235, 0.7)',
                    borderColor: '#2563eb',
                    borderWidth: 1,
                    borderRadius: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    y: { beginAtZero: true, ticks: { stepSize: 1 } },
                    x: { grid: { display: false } }
                }
            }
        });
    }

    function renderRevenueChart(monthlyData) {
        var labels = monthlyData.map(function(d) { return d.month; });
        var values = monthlyData.map(function(d) { return d.revenue; });
        var ctx = document.getElementById('wahrb-revenue-chart');
        if (!ctx) return;
        if (revenueChart) revenueChart.destroy();
        revenueChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: <?php echo wp_json_encode(__('Revenue', 'wahra-rentals-bookings')); ?>,
                    data: values,
                    backgroundColor: 'rgba(16, 185, 129, 0.7)',
                    borderColor: '#10b981',
                    borderWidth: 1,
                    borderRadius: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    y: { beginAtZero: true },
                    x: { grid: { display: false } }
                }
            }
        });
    }

    function renderTopProducts(products) {
        var $tbody = $('#wahrb-top-products');
        if (!products.length) {
            $tbody.html('<tr><td colspan="3" class="wahrb-table-empty">' +
                esc(<?php echo wp_json_encode(__('No data available', 'wahra-rentals-bookings')); ?>) +
                '</td></tr>');
            return;
        }
        var html = '';
        for (var i = 0; i < products.length; i++) {
            var p = products[i];
            html += '<tr>';
            html += '<td>' + esc(p.name) + '</td>';
            html += '<td>' + parseInt(p.bookings) + '</td>';
            html += '<td>' + formatCurrency(p.revenue) + '</td>';
            html += '</tr>';
        }
        $tbody.html(html);
    }

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

        var cc = document.getElementById('wahrb-category-chart');
        if (categoryChart) categoryChart.destroy();
        if (cc) {
            categoryChart = new Chart(cc, {
                type: 'doughnut',
                data: { labels: labels, datasets: [{ data: data, backgroundColor: colors }] },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: { legend: { position: 'bottom', labels: { padding: 10, font: { size: 12 } } } }
                }
            });
        }
    }

    // Tab navigation
    $(document).on('click', '.wahrb-atab-btn', function() {
        var tabId = $(this).data('atab');
        $('.wahrb-atab-btn').removeClass('active');
        $(this).addClass('active');
        $('.wahrb-atab-panel').removeClass('active');
        $('.wahrb-atab-panel[data-apanel="' + tabId + '"]').addClass('active');
        // Trigger chart resize when Charts tab is shown
        if (tabId === 'charts') {
            if (bookingsChart) bookingsChart.resize();
            if (revenueChart) revenueChart.resize();
        }
        if (tabId === 'products') {
            if (categoryChart) categoryChart.resize();
        }
    });

    $('#wahrb-period-filter, #wahrb-product-filter').on('change', fetchStats);

    $(document).ready(function() {
        if (apiUrl && nonce) {
            fetchStats();
        } else {
            $('#wahrb-loading').html('<span style="color:#ef4444;">&#9888; ' +
                esc(<?php echo wp_json_encode(__('Configuration error. Please reload.', 'wahra-rentals-bookings')); ?>) +
                '</span>');
        }
    });

})(jQuery);
</script>

<?php
// Analytics page CSS is now in assets/css/wahrb-vendor.css (loaded before wp_head)
?>
