/**
 * Admin Trial Bookings JavaScript
 *
 * @package Karate_Club_Manager
 * @since 1.0.61
 */

(function($) {
    'use strict';

    $(document).ready(function() {
        var i18n = macmTrialBookingsAdmin.i18n || {};

        // View details modal
        $('.kcm-view-details-btn').on('click', function(e) {
            e.preventDefault();
            var bookingId = $(this).data('booking-id');

            // Find booking in data
            var booking = null;
            if (typeof macmBookingsData !== 'undefined') {
                for (var i = 0; i < macmBookingsData.length; i++) {
                    if (macmBookingsData[i].id == bookingId) {
                        booking = macmBookingsData[i];
                        break;
                    }
                }
            }

            if (!booking) {
                alert(i18n.bookingNotFound);
                return;
            }

            // Format the details HTML
            var detailsHtml = '<div class="kcm-booking-details">';

            // Student Information
            detailsHtml += '<h3>Student Information</h3>';
            detailsHtml += '<table class="widefat">';
            detailsHtml += '<tr><th>Full Name:</th><td>' + booking.full_name + '</td></tr>';
            detailsHtml += '<tr><th>Is for Child:</th><td>' + (booking.is_for_child ? 'Yes' : 'No') + '</td></tr>';
            detailsHtml += '</table>';

            // Parent/Contact Information
            detailsHtml += '<h3>Contact Information</h3>';
            detailsHtml += '<table class="widefat">';
            if (booking.parent_name) {
                detailsHtml += '<tr><th>Parent Name:</th><td>' + booking.parent_name + '</td></tr>';
            }
            detailsHtml += '<tr><th>Email:</th><td><a href="mailto:' + booking.email + '">' + booking.email + '</a></td></tr>';
            detailsHtml += '<tr><th>Mobile:</th><td><a href="tel:' + booking.mobile + '">' + booking.mobile + '</a></td></tr>';
            detailsHtml += '</table>';

            // Booking Details
            detailsHtml += '<h3>Booking Details</h3>';
            detailsHtml += '<table class="widefat">';
            detailsHtml += '<tr><th>Preferred Class:</th><td>' + (booking.class_name || 'Not specified') + '</td></tr>';
            detailsHtml += '<tr><th>Booking Date:</th><td>' + booking.created_at + '</td></tr>';
            detailsHtml += '<tr><th>Status:</th><td><span class="kcm-status-badge kcm-status-' + booking.status + '">' + booking.status.charAt(0).toUpperCase() + booking.status.slice(1) + '</span></td></tr>';
            if (booking.completed_at) {
                detailsHtml += '<tr><th>Completed At:</th><td>' + booking.completed_at + '</td></tr>';
            }
            detailsHtml += '</table>';

            // Admin Notes Section
            detailsHtml += '<h3 style="margin-top: 25px;">Admin Notes</h3>';
            detailsHtml += '<div class="kcm-admin-note-section">';
            detailsHtml += '<textarea id="kcm-admin-note-' + booking.id + '" class="widefat" rows="4" placeholder="Add notes about this booking (follow-up information, contact attempts, etc.)">' + (booking.admin_note || '') + '</textarea>';
            detailsHtml += '<p style="margin-top: 10px;">';
            detailsHtml += '<button type="button" class="button button-primary kcm-save-note-btn" data-booking-id="' + booking.id + '">Save Note</button>';
            detailsHtml += '</p>';
            detailsHtml += '</div>';

            detailsHtml += '</div>';

            // Insert into modal and show
            $('#kcm-booking-details-content').html(detailsHtml);
            $('#kcm-details-modal').fadeIn();
        });

        // Generic status change handler
        function handleStatusChange($link, action, confirmMsg) {
            if (!confirm(confirmMsg)) {
                return;
            }

            var bookingId = $link.data('booking-id');
            var originalText = $link.text();

            $link.text(i18n.processing);

            $.ajax({
                url: macmTrialBookingsAdmin.ajaxurl,
                type: 'POST',
                data: {
                    action: action,
                    nonce: macmTrialBookingsAdmin.nonce,
                    booking_id: bookingId
                },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert(response.data.message || i18n.updateFailed);
                        $link.text(originalText);
                    }
                },
                error: function() {
                    alert(i18n.errorOccurred);
                    $link.text(originalText);
                }
            });
        }

        // Mark as complete
        $('.kcm-mark-complete-btn').on('click', function(e) {
            e.preventDefault();
            handleStatusChange($(this), 'macm_mark_booking_complete', i18n.confirmComplete);
        });

        // Mark as pending
        $('.kcm-mark-pending-btn').on('click', function(e) {
            e.preventDefault();
            handleStatusChange($(this), 'macm_mark_booking_pending', i18n.confirmPending);
        });

        // Mark as confirmed
        $('.kcm-mark-confirmed-btn').on('click', function(e) {
            e.preventDefault();
            handleStatusChange($(this), 'macm_mark_booking_confirmed', i18n.confirmConfirm);
        });

        // Mark as cancelled
        $('.kcm-mark-cancelled-btn').on('click', function(e) {
            e.preventDefault();
            handleStatusChange($(this), 'macm_mark_booking_cancelled', i18n.confirmCancel);
        });

        // Send email modal
        $('.kcm-send-email-btn').on('click', function(e) {
            e.preventDefault();
            var bookingId = $(this).data('booking-id');
            var email = $(this).data('email');
            var name = $(this).data('name');

            $('#email-booking-id').val(bookingId);
            $('#email-to').val(email);

            // Set default email body with personalization
            if (typeof tinymce !== 'undefined' && tinymce.get('email_body')) {
                tinymce.get('email_body').setContent('Dear ' + name + ',\n\n');
            } else {
                $('#email_body').val('Dear ' + name + ',\n\n');
            }

            $('#kcm-email-modal').fadeIn();
        });

        // Close modals
        $('.kcm-modal-close, .kcm-modal-close-btn').on('click', function() {
            $(this).closest('.kcm-modal').fadeOut();
        });

        // Close modal on outside click
        $(window).on('click', function(e) {
            if ($(e.target).hasClass('kcm-modal')) {
                $(e.target).fadeOut();
            }
        });

        // Send email form submission
        $('#kcm-email-form').on('submit', function(e) {
            e.preventDefault();

            var $form = $(this);
            var $submitBtn = $form.find('button[type="submit"]');
            var bookingId = $('#email-booking-id').val();

            // Get email body from TinyMCE or textarea
            var emailBody = '';
            if (typeof tinymce !== 'undefined' && tinymce.get('email_body')) {
                emailBody = tinymce.get('email_body').getContent();
            } else {
                emailBody = $('#email_body').val();
            }

            if (!emailBody.trim()) {
                alert(i18n.emailRequired);
                return;
            }

            $submitBtn.prop('disabled', true).text(i18n.sending);

            $.ajax({
                url: macmTrialBookingsAdmin.ajaxurl,
                type: 'POST',
                data: {
                    action: 'macm_send_booking_email',
                    nonce: macmTrialBookingsAdmin.nonce,
                    booking_id: bookingId,
                    email_body: emailBody
                },
                success: function(response) {
                    if (response.success) {
                        alert(response.data.message);
                        $('#kcm-email-modal').fadeOut();

                        // Clear form
                        if (typeof tinymce !== 'undefined' && tinymce.get('email_body')) {
                            tinymce.get('email_body').setContent('');
                        } else {
                            $('#email_body').val('');
                        }
                    } else {
                        alert(response.data.message || i18n.emailSendFailed);
                    }
                    $submitBtn.prop('disabled', false).text(i18n.sendEmail);
                },
                error: function() {
                    alert(i18n.errorOccurred);
                    $submitBtn.prop('disabled', false).text(i18n.sendEmail);
                }
            });
        });

        // Save admin note (delegated event handler for dynamically created buttons)
        $(document).on('click', '.kcm-save-note-btn', function(e) {
            e.preventDefault();

            var $button = $(this);
            var bookingId = $button.data('booking-id');
            var $textarea = $('#kcm-admin-note-' + bookingId);
            var noteText = $textarea.val();
            var originalText = $button.text();

            $button.prop('disabled', true).text(i18n.saving);

            $.ajax({
                url: macmTrialBookingsAdmin.ajaxurl,
                type: 'POST',
                data: {
                    action: 'macm_save_admin_note',
                    nonce: macmTrialBookingsAdmin.nonce,
                    booking_id: bookingId,
                    admin_note: noteText
                },
                success: function(response) {
                    if (response.success) {
                        // Update the data in memory
                        if (typeof macmBookingsData !== 'undefined') {
                            for (var i = 0; i < macmBookingsData.length; i++) {
                                if (macmBookingsData[i].id == bookingId) {
                                    macmBookingsData[i].admin_note = noteText;
                                    break;
                                }
                            }
                        }

                        // Show success message
                        alert(response.data.message || i18n.noteSaved);
                        $button.prop('disabled', false).text(originalText);
                    } else {
                        alert(response.data.message || i18n.noteSaveFailed);
                        $button.prop('disabled', false).text(originalText);
                    }
                },
                error: function() {
                    alert(i18n.errorOccurred);
                    $button.prop('disabled', false).text(originalText);
                }
            });
        });

        // =====================================================
        // Reports Tab
        // =====================================================
        if ($('#macm-trial-report-form').length) {
            var statusChart = null;
            var classesChart = null;
            var childrenChart = null;
            var funnelChart = null;

            // Quick date buttons
            $('.macm-quick-date-btn').on('click', function() {
                var range = $(this).data('range');
                var today = new Date();
                var dateFrom = '';
                var dateTo = today.toISOString().split('T')[0];

                switch (range) {
                    case 'today':
                        dateFrom = dateTo;
                        break;
                    case 'week':
                        var dayOfWeek = today.getDay();
                        var monday = new Date(today);
                        monday.setDate(today.getDate() - (dayOfWeek === 0 ? 6 : dayOfWeek - 1));
                        dateFrom = monday.toISOString().split('T')[0];
                        break;
                    case 'month':
                        dateFrom = today.getFullYear() + '-' + String(today.getMonth() + 1).padStart(2, '0') + '-01';
                        break;
                    case '30':
                        var d30 = new Date(today);
                        d30.setDate(today.getDate() - 30);
                        dateFrom = d30.toISOString().split('T')[0];
                        break;
                    case '90':
                        var d90 = new Date(today);
                        d90.setDate(today.getDate() - 90);
                        dateFrom = d90.toISOString().split('T')[0];
                        break;
                    case 'all':
                        dateFrom = '';
                        dateTo = '';
                        break;
                }

                $('#macm-report-date-from').val(dateFrom);
                $('#macm-report-date-to').val(dateTo);

                // Auto-submit
                $('#macm-trial-report-form').trigger('submit');
            });

            // Generate report form submit
            $('#macm-trial-report-form').on('submit', function(e) {
                e.preventDefault();

                var dateFrom = $('#macm-report-date-from').val();
                var dateTo = $('#macm-report-date-to').val();
                var status = $('#macm-report-status').val();
                var classId = $('#macm-report-class').val();

                $('#macm-report-results').hide();
                $('#macm-report-empty').hide();
                $('#macm-report-loading').show();

                $.ajax({
                    url: macmTrialBookingsAdmin.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'macm_generate_trial_report',
                        nonce: macmTrialBookingsAdmin.nonce,
                        date_from: dateFrom,
                        date_to: dateTo,
                        status: status,
                        class_id: classId
                    },
                    success: function(response) {
                        $('#macm-report-loading').hide();

                        if (response.success) {
                            var data = response.data;

                            if (data.records.length === 0) {
                                $('#macm-report-empty').html('<p style="font-size: 16px; color: #6B7280; text-align: center; padding: 40px;">' + i18n.noBookingsFound + '</p>').show();
                                $('#macm-export-csv-btn').prop('disabled', true);
                                return;
                            }

                            renderStats(data.statistics);
                            renderCharts(data.statistics);
                            renderTable(data.records);

                            $('#macm-report-results').show();
                            $('#macm-export-csv-btn').prop('disabled', false);

                            // Store filter values for CSV export
                            $('#macm-csv-date-from').val(dateFrom);
                            $('#macm-csv-date-to').val(dateTo);
                            $('#macm-csv-status').val(status);
                            $('#macm-csv-class-id').val(classId);
                        } else {
                            alert(response.data.message || i18n.reportGenerateFailed);
                        }
                    },
                    error: function() {
                        $('#macm-report-loading').hide();
                        alert(i18n.errorOccurred);
                    }
                });
            });

            // CSV export
            $('#macm-export-csv-btn').on('click', function() {
                $('#macm-csv-export-form').submit();
            });

            function renderStats(stats) {
                var html = '';
                html += macmStatCard(stats.total, 'Total Bookings');
                html += macmStatCard(stats.pending, 'Pending');
                html += macmStatCard(stats.confirmed, 'Confirmed');
                html += macmStatCard(stats.completed, 'Completed');
                html += macmStatCard(stats.cancelled, 'Cancelled');
                html += macmStatCard(stats.completion_rate + '%', 'Completion Rate');
                html += macmStatCard(stats.avg_days, 'Avg Days to Complete');
                html += macmStatCard(stats.children + ' / ' + stats.adults, 'Children / Adults');
                html += macmStatCard(stats.conversion_rate + '%', 'Member Conversion');

                $('#macm-report-stats').html(html);
            }

            function macmStatCard(value, label) {
                return '<div class="macm-stat-card">' +
                    '<div class="macm-stat-value">' + value + '</div>' +
                    '<div class="macm-stat-label">' + label + '</div>' +
                    '</div>';
            }

            function renderCharts(stats) {
                // Destroy existing charts
                if (statusChart) {
                    statusChart.destroy();
                }
                if (classesChart) {
                    classesChart.destroy();
                }
                if (childrenChart) {
                    childrenChart.destroy();
                }
                if (funnelChart) {
                    funnelChart.destroy();
                }

                // Status distribution doughnut chart
                var statusCtx = document.getElementById('macm-status-chart');
                if (statusCtx && typeof Chart !== 'undefined') {
                    statusChart = new Chart(statusCtx.getContext('2d'), {
                        type: 'doughnut',
                        data: {
                            labels: ['Pending', 'Confirmed', 'Completed', 'Cancelled'],
                            datasets: [{
                                data: [stats.pending, stats.confirmed, stats.completed, stats.cancelled],
                                backgroundColor: ['#fff3cd', '#cce5ff', '#d4edda', '#f8d7da'],
                                borderColor: ['#856404', '#004085', '#155724', '#721c24'],
                                borderWidth: 2
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    position: 'bottom'
                                }
                            }
                        }
                    });
                }

                // Top classes bar chart
                var classesCtx = document.getElementById('macm-classes-chart');
                if (classesCtx && typeof Chart !== 'undefined' && stats.top_classes) {
                    var classLabels = Object.keys(stats.top_classes);
                    var classValues = Object.values(stats.top_classes);

                    classesChart = new Chart(classesCtx.getContext('2d'), {
                        type: 'bar',
                        data: {
                            labels: classLabels,
                            datasets: [{
                                label: 'Bookings',
                                data: classValues,
                                backgroundColor: '#B11226',
                                borderRadius: 4
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    display: false
                                }
                            },
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    ticks: {
                                        stepSize: 1
                                    }
                                }
                            }
                        }
                    });
                }

                // Children vs Adults doughnut chart
                var childrenCtx = document.getElementById('macm-children-chart');
                if (childrenCtx && typeof Chart !== 'undefined') {
                    childrenChart = new Chart(childrenCtx.getContext('2d'), {
                        type: 'doughnut',
                        data: {
                            labels: ['Children', 'Adults'],
                            datasets: [{
                                data: [stats.children, stats.adults],
                                backgroundColor: ['#e8d5f5', '#d5e8f5'],
                                borderColor: ['#6c3483', '#2471a3'],
                                borderWidth: 2
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    position: 'bottom'
                                }
                            }
                        }
                    });
                }

                // Conversion funnel horizontal bar chart
                var funnelCtx = document.getElementById('macm-funnel-chart');
                if (funnelCtx && typeof Chart !== 'undefined') {
                    funnelChart = new Chart(funnelCtx.getContext('2d'), {
                        type: 'bar',
                        data: {
                            labels: ['Pending', 'Confirmed', 'Completed'],
                            datasets: [{
                                data: [stats.pending, stats.confirmed, stats.completed],
                                backgroundColor: ['#fff3cd', '#cce5ff', '#d4edda'],
                                borderColor: ['#856404', '#004085', '#155724'],
                                borderWidth: 2,
                                borderRadius: 4
                            }]
                        },
                        options: {
                            indexAxis: 'y',
                            responsive: true,
                            plugins: {
                                legend: {
                                    display: false
                                }
                            },
                            scales: {
                                x: {
                                    beginAtZero: true,
                                    ticks: {
                                        stepSize: 1
                                    }
                                }
                            }
                        }
                    });
                }
            }

            function renderTable(records) {
                var html = '<table class="macm-report-table">';
                html += '<thead><tr>';
                html += '<th>Date</th>';
                html += '<th>Name</th>';
                html += '<th>Email</th>';
                html += '<th>Mobile</th>';
                html += '<th>Child</th>';
                html += '<th>Class</th>';
                html += '<th>Status</th>';
                html += '<th>Completed</th>';
                html += '</tr></thead><tbody>';

                for (var i = 0; i < records.length; i++) {
                    var r = records[i];
                    html += '<tr>';
                    html += '<td>' + r.created_at + '</td>';
                    html += '<td>' + r.full_name + '</td>';
                    html += '<td>' + r.email + '</td>';
                    html += '<td>' + (r.mobile || '—') + '</td>';
                    html += '<td>' + (r.is_for_child ? 'Yes' : 'No') + '</td>';
                    html += '<td>' + r.class_name + '</td>';
                    html += '<td><span class="kcm-status-badge kcm-status-' + r.status + '">' + r.status.charAt(0).toUpperCase() + r.status.slice(1) + '</span></td>';
                    html += '<td>' + (r.completed_at || '—') + '</td>';
                    html += '</tr>';
                }

                html += '</tbody></table>';
                $('#macm-report-table-container').html(html);
            }
        }
    });

})(jQuery);
