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

(function($) {
    'use strict';

    $(document).ready(function() {
        // 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('Booking not found.');
                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();
        });

        // Mark as complete
        $('.kcm-mark-complete-btn').on('click', function(e) {
            e.preventDefault();

            if (!confirm('Are you sure you want to mark this booking as complete?')) {
                return;
            }

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

            $link.text('Processing...');

            $.ajax({
                url: macmTrialBookingsAdmin.ajaxurl,
                type: 'POST',
                data: {
                    action: 'macm_mark_booking_complete',
                    nonce: macmTrialBookingsAdmin.nonce,
                    booking_id: bookingId
                },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert(response.data.message || 'Failed to update booking.');
                        $link.text(originalText);
                    }
                },
                error: function() {
                    alert('An error occurred. Please try again.');
                    $link.text(originalText);
                }
            });
        });

        // Mark as pending
        $('.kcm-mark-pending-btn').on('click', function(e) {
            e.preventDefault();

            if (!confirm('Are you sure you want to mark this booking as pending?')) {
                return;
            }

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

            $link.text('Processing...');

            $.ajax({
                url: macmTrialBookingsAdmin.ajaxurl,
                type: 'POST',
                data: {
                    action: 'macm_mark_booking_pending',
                    nonce: macmTrialBookingsAdmin.nonce,
                    booking_id: bookingId
                },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert(response.data.message || 'Failed to update booking.');
                        $link.text(originalText);
                    }
                },
                error: function() {
                    alert('An error occurred. Please try again.');
                    $link.text(originalText);
                }
            });
        });

        // 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('Please enter an email message.');
                return;
            }

            $submitBtn.prop('disabled', true).text('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 || 'Failed to send email.');
                    }
                    $submitBtn.prop('disabled', false).text('Send Email');
                },
                error: function() {
                    alert('An error occurred. Please try again.');
                    $submitBtn.prop('disabled', false).text('Send Email');
                }
            });
        });

        // 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('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 || 'Note saved successfully.');
                        $button.prop('disabled', false).text(originalText);
                    } else {
                        alert(response.data.message || 'Failed to save note.');
                        $button.prop('disabled', false).text(originalText);
                    }
                },
                error: function() {
                    alert('An error occurred. Please try again.');
                    $button.prop('disabled', false).text(originalText);
                }
            });
        });
    });

})(jQuery);
