/**
 * Dokan Vendor Dashboard Scripts
 * 
 * @package DokanRentalsBookings
 */

(function ($) {
    'use strict';

    // Global WAHRB Vendor object
    window.WAHRBVendor = {
        config: window.wahrbVendorConfig || {},

        /**
         * Get i18n string with fallback
         */
        __: function (key, fallback) {
            return (this.config.i18n && this.config.i18n[key]) || fallback || key;
        },

        init: function () {
            this.bindEvents();
            this.initTooltips();
        },

        bindEvents: function () {
            // Note: Toggle rental options visibility is handled by wahrb-rental-fields.js

            // Booking action buttons
            $(document).on('click', '.wahrb-action-confirm', this.confirmBooking);
            $(document).on('click', '.wahrb-action-cancel', this.cancelBooking);
            $(document).on('click', '.wahrb-action-checkin', this.checkinBooking);
            $(document).on('click', '.wahrb-action-checkout', this.checkoutBooking);
        },

        initTooltips: function () {
            $('[data-tooltip]').each(function () {
                $(this).attr('title', $(this).data('tooltip'));
            });
        },

        // API helper
        api: function (endpoint, method, data) {
            return $.ajax({
                url: this.config.apiUrl + endpoint,
                method: method || 'GET',
                data: data,
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', WAHRBVendor.config.nonce);
                }
            });
        },

        // Confirm booking
        confirmBooking: function (e) {
            e.preventDefault();
            var bookingId = $(this).data('booking-id');

            if (!confirm(WAHRBVendor.__('confirmBooking', 'Confirm this booking?'))) {
                return;
            }

            WAHRBVendor.api('/bookings/' + bookingId + '/confirm', 'POST')
                .done(function (response) {
                    location.reload();
                })
                .fail(function (error) {
                    alert(WAHRBVendor.__('error', 'Error') + ': ' + (error.responseJSON?.message || WAHRBVendor.__('unknownError', 'An error occurred')));
                });
        },

        // Cancel booking
        cancelBooking: function (e) {
            e.preventDefault();
            var bookingId = $(this).data('booking-id');
            var reason = prompt(WAHRBVendor.__('cancelReason', 'Cancellation reason (optional):'));

            if (reason === null) {
                return; // User cancelled prompt
            }

            WAHRBVendor.api('/bookings/' + bookingId + '/cancel', 'POST', { reason: reason })
                .done(function (response) {
                    location.reload();
                })
                .fail(function (error) {
                    alert(WAHRBVendor.__('error', 'Error') + ': ' + (error.responseJSON?.message || WAHRBVendor.__('unknownError', 'An error occurred')));
                });
        },

        // Check-in booking
        checkinBooking: function (e) {
            e.preventDefault();
            var bookingId = $(this).data('booking-id');
            var notes = prompt(WAHRBVendor.__('checkinNotes', 'Check-in notes (optional):'));

            if (notes === null) {
                return;
            }

            WAHRBVendor.api('/bookings/' + bookingId + '/checkin', 'POST', { notes: notes })
                .done(function (response) {
                    location.reload();
                })
                .fail(function (error) {
                    alert(error.responseJSON?.message || WAHRBVendor.__('unknownError', 'An error occurred'));
                });
        },

        // Check-out booking
        checkoutBooking: function (e) {
            e.preventDefault();
            var bookingId = $(this).data('booking-id');
            var notes = prompt(WAHRBVendor.__('checkoutNotes', 'Check-out notes (product condition, damages...):'));

            if (notes === null) {
                return;
            }

            WAHRBVendor.api('/bookings/' + bookingId + '/checkout', 'POST', { notes: notes })
                .done(function (response) {
                    location.reload();
                })
                .fail(function (error) {
                    alert(WAHRBVendor.__('error', 'Error') + ': ' + (error.responseJSON?.message || WAHRBVendor.__('unknownError', 'An error occurred')));
                });
        },

        // Load bookings list via AJAX
        loadBookings: function (status, page) {
            var $container = $('#wahrb-bookings-list');
            $container.html('<tr><td colspan="7" class="text-center">' + WAHRBVendor.__('loading', 'Loading...') + '</td></tr>');

            this.api('/vendor/bookings', 'GET', { status: status, page: page })
                .done(function (response) {
                    WAHRBVendor.renderBookings(response.data);
                })
                .fail(function () {
                    $container.html('<tr><td colspan="7" class="text-center">' + WAHRBVendor.__('loadError', 'Loading error') + '</td></tr>');
                });
        },

        // Init Analytics Page
        initAnalytics: function () {
            if ($('#wahrb-total-bookings').length === 0) return;

            this.loadStats('year'); // Default to year view

            // Period selectors
            $('#wahrb-bookings-period, #wahrb-revenue-period').on('change', function () {
                var period = $(this).val() == '6' ? 'month' : 'year'; // Map value to API period
                // Simplification: Refresh all stats for now
                WAHRBVendor.loadStats(period);
            });
        },

        // Load Stats
        loadStats: function (period) {
            this.api('/vendor/bookings/stats', 'GET', { period: period })
                .done(function (response) {
                    WAHRBVendor.renderStats(response.data);
                })
                .fail(function () {
                    console.error('Failed to load stats');
                });
        },

        // Render Stats & Charts
        renderStats: function (data) {
            // Update Summary Cards
            $('#wahrb-total-bookings').text(data.total_bookings);
            $('#wahrb-total-revenue').html(data.total_revenue_formatted);
            $('#wahrb-occupancy-rate').text(data.occupancy_rate + '%');
            $('#wahrb-avg-rating').text(data.average_rating || '-');

            // Render Charts if Chart.js is loaded
            if (typeof Chart !== 'undefined') {
                this.renderCharts(data);
            }

            // Top Products Table
            var $topProducts = $('#wahrb-top-products');
            if (data.top_products && data.top_products.length > 0) {
                var html = '';
                data.top_products.forEach(function (p) {
                    html += '<tr>';
                    html += '<td>' + p.name + '</td>';
                    html += '<td>' + p.bookings_count + '</td>';
                    html += '<td>' + p.revenue_formatted + '</td>';
                    html += '<td>' + p.occupancy + '%</td>';
                    html += '</tr>';
                });
                $topProducts.html(html);
            } else {
                $topProducts.html('<tr><td colspan="4" class="text-center">' + WAHRBVendor.__('noData', 'No data') + '</td></tr>');
            }
        },

        renderCharts: function (data) {
            // Bookings Chart
            var bookingsCtx = document.getElementById('wahrb-bookings-chart').getContext('2d');

            // Destroy existing if any
            if (window.wahrbBookingsChart) window.wahrbBookingsChart.destroy();

            window.wahrbBookingsChart = new Chart(bookingsCtx, {
                type: 'bar',
                data: {
                    labels: data.chart_data.labels,
                    datasets: [{
                        label: WAHRBVendor.__('bookings', 'Bookings'),
                        data: data.chart_data.bookings,
                        backgroundColor: '#3b82f6',
                        borderRadius: 4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: { legend: { display: false } },
                    scales: { y: { beginAtZero: true, ticks: { precision: 0 } } }
                }
            });

            // Revenue Chart
            var revenueCtx = document.getElementById('wahrb-revenue-chart').getContext('2d');

            if (window.wahrbRevenueChart) window.wahrbRevenueChart.destroy();

            window.wahrbRevenueChart = new Chart(revenueCtx, {
                type: 'line',
                data: {
                    labels: data.chart_data.labels,
                    datasets: [{
                        label: WAHRBVendor.__('revenue', 'Revenue'),
                        data: data.chart_data.revenue,
                        borderColor: '#10b981',
                        backgroundColor: 'rgba(16, 185, 129, 0.1)',
                        fill: true,
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: { legend: { display: false } },
                    scales: { y: { beginAtZero: true } }
                }
            });
        },

        // Render bookings table
        renderBookings: function (bookings) {
            var $container = $('#wahrb-bookings-list');

            if (!bookings || bookings.length === 0) {
                $container.html('<tr><td colspan="7" class="text-center">' + WAHRBVendor.__('noBookings', 'No bookings') + '</td></tr>');
                return;
            }

            var html = '';
            bookings.forEach(function (booking) {
                html += '<tr>';
                html += '<td>#' + booking.booking_number + '</td>';
                html += '<td>' + booking.product_name + '</td>';
                html += '<td>' + booking.customer_name + '</td>';
                html += '<td>' + booking.start_date + ' - ' + booking.end_date + '</td>';
                html += '<td>' + booking.total_formatted + '</td>';
                html += '<td><span class="wahrb-status wahrb-status-' + booking.status + '">' + booking.status_label + '</span></td>';
                html += '<td class="wahrb-actions">';
                html += '  <button class="wahrb-action-btn wahrb-action-btn-secondary" data-booking-id="' + booking.id + '">' + WAHRBVendor.__('view', 'View') + '</button>';
                html += '</td>';
                html += '</tr>';
            });

            $container.html(html);
        }
    };

    // Initialize on document ready
    $(document).ready(function () {
        WAHRBVendor.init();
    });

})(jQuery);
