/*!
 * Yatoon admin — Bookings screen.
 *
 * 4.6.1 V2: extracted from admin/views/bookings.php. It ran as 499 lines of
 * inline <script>, which meant it could not be linted, minified or cached, and
 * it was invisible to any tool that only looks at .js files.
 *
 * PHP-interpolated values now arrive through wp_localize_script as `yatoonBookingsData`.
 *
 * Two smaller blocks stayed inline on purpose: the Square and diagnostics
 * panels are rendered behind PHP conditions, and their scripts run setup code
 * that assumes those panels exist. Moving them would trade a real bug risk for
 * sixty lines.
 */
jQuery(document).ready(function($) {

    // -- Checkbox helpers -------------------------------------------------------
    $('#sbs-select-all-bookings').on('change', function() {
        $('.sbs-booking-checkbox').prop('checked', $(this).prop('checked'));
        $('.sbs-group-checkbox').prop('checked', $(this).prop('checked'));
        updateDeleteButton();
    });
    $(document).on('change', '.sbs-booking-checkbox', function() {
        updateDeleteButton();
        $(this).closest('tr').toggleClass('is-selected', $(this).is(':checked'));
        // Chromium/Edge can fail to repaint this checkbox's own check-mark
        // when other DOM changes (like the row highlight above) happen in
        // the same handler, even though the underlying checked state is
        // correct. Reading offsetHeight does not fix this reliably; cloning
        // the element and swapping it in does force a correct repaint.
        const cb = this;
        const isChecked = cb.checked;
        const freshCb = cb.cloneNode(true);
        freshCb.checked = isChecked;
        cb.parentNode.replaceChild(freshCb, cb);
        const total   = $('.sbs-booking-checkbox').length;
        const checked = $('.sbs-booking-checkbox:checked').length;
        $('#sbs-select-all-bookings').prop('checked', total === checked);
    });
    // Group checkbox: toggle all hidden sub-checkboxes for the group
    $(document).on('change', '.sbs-group-checkbox', function() {
        const gid = $(this).data('gid');
        const checked = $(this).prop('checked');
        $(this).closest('tr').find('.sbs-booking-checkbox').prop('checked', checked);
        updateDeleteButton();
    });
    function updateDeleteButton() {
        const checked = $('.sbs-booking-checkbox:checked').length;
        $('#sbs-delete-selected-bookings')
            .prop('disabled', checked === 0)
            .text(checked > 0 ? 'Delete (' + checked + ')' : 'Delete Selected');
    }

    function applyBookingFilters() {
        const q = ($('#sbs-booking-search').val() || '').toLowerCase().trim();
        const status = ($('#sbs-booking-status-filter').val() || '').toLowerCase();
        const design = ($('#sbs-booking-design-filter').val() || '');

        $('#sbs-bookings-table tbody tr').each(function() {
            const $row = $(this);
            const matchesText = !q || String($row.data('search') || '').indexOf(q) !== -1;
            const matchesStatus = !status || String($row.data('status') || '').toLowerCase() === status;
            const matchesDesign = !design || String($row.data('design-upload') || '0') === design;
            const visible = matchesText && matchesStatus && matchesDesign;
            if ($row.hasClass('sbs-group-row')) {
                if (!visible) {
                    $row.hide();
                }
                return;
            }
            $row.toggle(visible);
            if ($row.hasClass('sbs-group-header') && !visible) {
                const gid = $row.data('gid');
                $('.sbs-group-' + gid).hide();
            }
        });
    }

    $('#sbs-booking-search, #sbs-booking-status-filter, #sbs-booking-design-filter').on('input change', applyBookingFilters);
    applyBookingFilters();
    $('#sbs-booking-clear-filters').on('click', function() {
        $('#sbs-booking-search').val('');
        $('#sbs-booking-status-filter').val('');
        $('#sbs-booking-design-filter').val('');
        applyBookingFilters();
    });

    function openDesignGallery(images) {
        const unique = [];
        const seen = {};
        images.forEach(function(item) {
            if (!item.url || seen[item.url]) return;
            seen[item.url] = true;
            unique.push(item);
        });
        let html = '<div id="sbs-design-gallery-modal" style="position:fixed;inset:0;background:rgba(15,23,42,.72);z-index:99999;display:flex;align-items:center;justify-content:center;padding:20px;">';
        html += '<div style="background:#fff;border-radius:10px;max-width:860px;width:100%;max-height:86vh;display:flex;flex-direction:column;box-shadow:0 18px 50px rgba(0,0,0,.35);overflow:hidden;">';
        html += '<div style="padding:18px 22px;border-bottom:1px solid #e5e7eb;display:flex;align-items:center;justify-content:space-between;gap:12px;"><h3 style="margin:0;font-size:20px;">Design Images</h3><button type="button" id="sbs-design-gallery-close" class="button">Close</button></div>';
        html += '<div style="padding:18px 22px;overflow:auto;">';
        if (!unique.length) {
            html += '<p style="margin:0;color:#6b7280;">No design images found for the selected or visible bookings.</p>';
        } else {
            html += '<div class="yatoon-design-gallery-grid">';
            unique.forEach(function(item) {
                const safeUrl = $('<div>').text(item.url).html();
                const safeLabel = $('<div>').text(item.label || 'Design image').html();
                html += '<div class="yatoon-design-gallery-card"><a href="' + safeUrl + '" target="_blank" rel="noopener"><img src="' + safeUrl + '" alt=""><span>' + safeLabel + '</span></a></div>';
            });
            html += '</div>';
        }
        html += '</div></div></div>';
        const modal = $(html);
        $('body').append(modal);
        modal.on('click', function(ev) { if ($(ev.target).is(modal)) modal.remove(); });
        modal.find('#sbs-design-gallery-close').on('click', function() { modal.remove(); });
    }

    $('#sbs-view-design-gallery').on('click', function() {
        let images = $('.sbs-booking-checkbox:checked').map(function() {
            return { url: $(this).data('design-url') || '', label: $(this).data('design-label') || '' };
        }).get();
        if (!images.some(function(item) { return item.url; })) {
            images = $('#sbs-bookings-table tbody tr:visible').map(function() {
                return { url: $(this).data('design-url') || '', label: $(this).data('design-label') || '' };
            }).get();
        }
        openDesignGallery(images);
    });

    $(document).on('click', '.yatoon-booking-design-thumb', function(e) {
        e.preventDefault();
        openDesignGallery([{ url: $(this).attr('href'), label: $(this).closest('tr').data('design-label') || 'Design image' }]);
    });

    // -- Expand / Collapse group rows ------------------------------------------
    $(document).on('click', '.sbs-toggle-group, .sbs-group-header', function(e) {
        if ($(e.target).is('.sbs-cancel-booking')) return; // don't expand on cancel click
        const gid = $(this).data('gid') || $(this).closest('tr').data('gid');
        const $rows = $('.sbs-group-' + gid);
        const $btn  = $('.sbs-toggle-group[data-gid="' + gid + '"]');
        const isOpen = $rows.first().is(':visible');
        $rows.toggle(!isOpen);
        $btn.text(isOpen ? 'Expand' : 'Collapse');
    });

    // -- Move service UP (swap with previous in group) -------------------------
    $(document).on('click', '.sbs-move-service-up', function() {
        const gid     = $(this).data('gid');
        const id_b    = $(this).data('id'); // booking to move up
        const $rows   = $('.sbs-group-' + gid + '[data-booking-id]');
        const rowsArr = $rows.toArray();
        const idx     = rowsArr.findIndex(r => parseInt($(r).data('booking-id')) === parseInt(id_b));
        if (idx <= 0) return;
        const id_a = $(rowsArr[idx - 1]).data('booking-id');
        reorderGroup(gid, id_a, id_b);
    });

    // -- Move service DOWN (swap with next in group) ---------------------------
    $(document).on('click', '.sbs-move-service-down', function() {
        const gid   = $(this).data('gid');
        const id_a  = $(this).data('id'); // booking to move down
        const $rows = $('.sbs-group-' + gid + '[data-booking-id]');
        const rowsArr = $rows.toArray();
        const idx   = rowsArr.findIndex(r => parseInt($(r).data('booking-id')) === parseInt(id_a));
        if (idx < 0 || idx >= rowsArr.length - 1) return;
        const id_b  = $(rowsArr[idx + 1]).data('booking-id');
        reorderGroup(gid, id_a, id_b);
    });

    function reorderGroup(gid, id_a, id_b) {
        const btn = $('.sbs-move-service-up[data-gid="'+gid+'"], .sbs-move-service-down[data-gid="'+gid+'"]');
        btn.prop('disabled', true);

        $.post(ajaxurl, {
            action: 'yatoon_reorder_booking_group',
            nonce:         yatoonBookingsData.adminNonce,
            booking_id_a:  id_a,
            booking_id_b:  id_b
        }, function(resp) {
            if (resp.success) {
                // Reload the page to reflect new order + new times
                location.reload();
            } else {
                alert('Reorder failed: ' + (resp.data && resp.data.message ? resp.data.message : 'Unknown error'));
                btn.prop('disabled', false);
            }
        }).fail(function() {
            alert('Network error - could not reorder services.');
            btn.prop('disabled', false);
        });
    }

    $(document).on('change', '.sbs-booking-status-select', function(e) {
        e.stopPropagation();
        const $sel = $(this);
        const previous = $sel.data('previous') || $sel.find('option[selected]').val() || '';
        $sel.prop('disabled', true);
        $.post(ajaxurl, {
            action: 'yatoon_update_booking_status',
            nonce: yatoonBookingsData.adminNonce,
            booking_id: $sel.data('id'),
            status: $sel.val()
        }, function(resp) {
            if (resp.success) {
                location.reload();
            } else {
                alert('Failed: ' + (resp.data || 'Could not update status'));
                if (previous) $sel.val(previous);
                $sel.prop('disabled', false);
            }
        }).fail(function() {
            alert('Network error while updating booking status.');
            if (previous) $sel.val(previous);
            $sel.prop('disabled', false);
        });
    }).on('focus', '.sbs-booking-status-select', function() {
        $(this).data('previous', $(this).val());
    });

    $(document).on('change', '.sbs-payment-status-select', function(e) {
        e.stopPropagation();
        const $sel = $(this);
        const previous = $sel.data('previous') || $sel.find('option[selected]').val() || '';
        const nextStatus = $sel.val();
        const currentNote = $sel.data('note') || '';

        let html = '<div id="sbs-payment-note-modal" style="position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:99999;display:flex;align-items:center;justify-content:center;padding:20px;">';
        html += '<div style="background:#fff;border-radius:10px;max-width:420px;width:100%;box-shadow:0 12px 30px rgba(0,0,0,.25);overflow:hidden;">';
        html += '<div style="padding:20px 22px;border-bottom:1px solid #e5e7eb;"><h3 style="margin:0;font-size:20px;">Update Payment Status</h3></div>';
        html += '<div style="padding:18px 22px;">';
        html += '<p style="margin:0 0 12px;color:#4b5563;font-size:14px;">Optional note for booking #' + $sel.data('id') + ':</p>';
        html += '<textarea id="sbs-payment-note-input" style="width:100%;min-height:100px;border:1px solid #d1d5db;border-radius:8px;padding:10px;font-size:14px;box-sizing:border-box;">' + currentNote + '</textarea>';
        html += '</div>';
        html += '<div style="padding:16px 22px;text-align:right;border-top:1px solid #e5e7eb;display:flex;gap:10px;justify-content:flex-end;">';
        html += '<button type="button" id="sbs-payment-note-cancel" class="button">Cancel</button>';
        html += '<button type="button" id="sbs-payment-note-save" class="button button-primary">Save</button>';
        html += '</div></div></div>';

        const modal = $(html);
        $('body').append(modal);

        const closeModal = function() {
            modal.remove();
        };

        modal.on('click', function(ev) {
            if ($(ev.target).is(modal)) {
                if (previous) $sel.val(previous);
                closeModal();
            }
        });

        modal.find('#sbs-payment-note-cancel').on('click', function() {
            if (previous) $sel.val(previous);
            closeModal();
        });

        modal.find('#sbs-payment-note-save').on('click', function() {
            const note = modal.find('#sbs-payment-note-input').val();
            closeModal();
            $sel.prop('disabled', true);
            $.post(ajaxurl, {
                action: 'yatoon_update_payment_status',
                nonce: yatoonBookingsData.adminNonce,
                booking_id: $sel.data('id'),
                payment_status: nextStatus,
                payment_note: note
            }, function(resp) {
                if (resp.success) {
                    location.reload();
                } else {
                    alert('Failed: ' + (resp.data || 'Could not update payment status'));
                    if (previous) $sel.val(previous);
                    $sel.prop('disabled', false);
                }
            }).fail(function() {
                alert('Network error while updating payment status.');
                if (previous) $sel.val(previous);
                $sel.prop('disabled', false);
            });
        });
    }).on('focus', '.sbs-payment-status-select', function() {
        $(this).data('previous', $(this).val());
    });

    // -- Bulk delete ----------------------------------------------------------
    $('#sbs-delete-selected-bookings').on('click', function() {
        const selected = [];
        $('.sbs-booking-checkbox:checked').each(function() { selected.push($(this).val()); });
        if (!selected.length) return;
        if (!confirm('Delete ' + selected.length + ' booking(s)? This cannot be undone.')) return;
        const btn = $(this).prop('disabled', true).text('Deleting...');
        $.post(ajaxurl, {
            action:      'yatoon_delete_bookings',
            nonce:       yatoonBookingsData.deleteNonce,
            booking_ids: selected
        }, function(resp) {
            if (resp.success) {
                selected.forEach(id => {
                    $('[data-booking-id="'+id+'"]').fadeOut(300, function(){ $(this).remove(); });
                });
                btn.text('Delete Selected').prop('disabled', true);
                $('#sbs-select-all-bookings').prop('checked', false);
                if (!$('.sbs-booking-checkbox').length) location.reload();
            } else {
                alert('Failed: ' + (resp.data || 'Unknown error'));
                btn.text('Delete Selected').prop('disabled', false);
            }
        });
    });

    // -- Export CSV ------------------------------------------------------------
    $('#sbs-export-bookings').on('click', function() {
        window.location.href = ajaxurl + '?action=yatoon_export_bookings&nonce=' + encodeURIComponent(yatoonBookingsData.exportNonce);
    });

    // -- Sync from Square ---------------------------------------------------------
    $('#sbs-sync-from-square').on('click', function(){
        if (!confirm('Sync bookings from Square?\n\nThis will update existing statuses, insert missing Square bookings, and mark removed bookings as cancelled.\n\nContinue?')) return;
        const btn = $(this).prop('disabled', true).text('Syncing...');
        $('#sbs-sync-status').text('');
        $.post(ajaxurl, {
            action: 'yatoon_sync_bookings_from_square',
            nonce: yatoonBookingsData.adminNonce
        }, function(resp) {
            btn.prop('disabled', false).text('Sync from Square');
            if (resp.success) {
                const d = resp.data;
                $('#sbs-sync-status').html('<span style="color:#276749;">OK ' + d.message + '</span>');
                setTimeout(function(){ location.reload(); }, 2000);
            } else {
                $('#sbs-sync-status').html('<span style="color:#c53030;">Error: ' + (resp.data && resp.data.message ? resp.data.message : 'Sync failed') + '</span>');
            }
        }).fail(function(){
            btn.prop('disabled', false).text('Sync from Square');
            $('#sbs-sync-status').html('<span style="color:#c53030;">Error: Request failed</span>');
        });
    });

    // -- Delete booking (permanent local DB removal) ------------------------------
    $(document).on('click', '.sbs-view-booking', function(e) {
        e.stopPropagation();
        const btn = $(this);
        const escapeHtml = function(value) {
            return $('<div>').text(value == null ? '' : String(value)).html();
        };
        const designUrl = btn.attr('data-design-url') || '';
        const clientUrl = btn.attr('data-client-url') || '';
        const rows = [
            ['Booking ID', '#' + btn.data('id')],
            ['Customer', btn.data('customer'), clientUrl],
            ['Email', btn.data('email')],
            ['Phone', btn.data('phone') || '-'],
            ['Service', btn.data('service')],
            ['Staff', btn.data('staff')],
            ['Date', btn.data('date')],
            ['Time', btn.data('time')],
            ['Status', btn.data('status')],
            ['Payment', btn.data('payment')],
            ['Total', '$' + btn.data('total')],
            ['Booked on', btn.data('booked-at') || '-'],
        ];

        if (btn.data('note')) {
            rows.push(['Payment Note', btn.data('note')]);
        }

        let html = '<div id="sbs-booking-view-modal" style="position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:99999;display:flex;align-items:center;justify-content:center;padding:20px;">';
        html += '<div style="background:#fff;border-radius:10px;max-width:420px;width:100%;box-shadow:0 12px 30px rgba(0,0,0,.25);overflow:hidden;">';
        html += '<div style="padding:20px 22px;border-bottom:1px solid #e5e7eb;"><h3 style="margin:0;font-size:20px;">Booking Details</h3></div>';
        html += '<div style="padding:18px 22px;max-height:70vh;overflow:auto;">';
        rows.forEach(function(row) {
            html += '<div style="display:flex;gap:14px;padding:9px 0;border-bottom:1px solid #f3f4f6;">';
            html += '<div style="width:110px;flex-shrink:0;color:#6b7280;font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:.04em;">' + escapeHtml(row[0]) + '</div>';
            if (row[2]) {
                html += '<div style="flex:1;color:#111827;font-size:14px;line-height:1.5;"><a href="' + escapeHtml(row[2]) + '" style="font-weight:700;text-decoration:none;">' + escapeHtml(row[1]) + '</a></div>';
            } else {
                html += '<div style="flex:1;color:#111827;font-size:14px;line-height:1.5;">' + escapeHtml(row[1]) + '</div>';
            }
            html += '</div>';
        });
        if (designUrl) {
            html += '<div style="padding:14px 0 2px;">';
            html += '<div style="color:#6b7280;font-size:12px;font-weight:700;text-transform:uppercase;margin-bottom:8px;">Design Reference</div>';
            html += '<a href="' + escapeHtml(designUrl) + '" target="_blank" rel="noopener" style="display:inline-block;text-decoration:none;">';
            html += '<img src="' + escapeHtml(designUrl) + '" alt="" style="display:block;max-width:240px;max-height:240px;object-fit:contain;border:1px solid #e5e7eb;border-radius:8px;background:#f8fafc;">';
            html += '<span style="display:block;margin-top:7px;">Open image</span></a></div>';
        }
        html += '</div>';
        html += '<div style="padding:16px 22px;text-align:right;border-top:1px solid #e5e7eb;">';
        html += '<button type="button" id="sbs-booking-view-close" class="button button-primary">Close</button>';
        html += '</div></div></div>';

        const modal = $(html);
        $('body').append(modal);
        modal.on('click', function(ev) {
            if ($(ev.target).is(modal)) modal.remove();
        });
        modal.find('#sbs-booking-view-close').on('click', function() {
            modal.remove();
        });
    });

    // -- Delete booking (permanent local DB removal) ------------------------------
    $(document).on('click', '.sbs-delete-booking', function(e) {
        e.stopPropagation();
        const id = $(this).data('id');
        if (!confirm('Permanently DELETE booking #' + id + ' from local database?\nThis does NOT cancel it in Square - use Cancel first if still active in Square.')) return;
        const btn = $(this).prop('disabled', true).text('...');
        $.post(ajaxurl, {
            action: 'yatoon_delete_single_booking',
            nonce:  yatoonBookingsData.deleteNonce,
            id:     id
        }, function(resp) {
            if (resp.success) {
                // Fade out the booking row(s) immediately, then reload for a clean state
                const $rows = $('[data-booking-id="' + id + '"], .sbs-group-row[data-gid]').filter(function() {
                    return $(this).find('[data-id="' + id + '"]').length > 0;
                });
                const $direct = $('tr[data-booking-id="' + id + '"]');
                const $target = $direct.length ? $direct : $('tr').filter(function(){ return $(this).find('.sbs-delete-booking[data-id="'+id+'"]').length; });
                if ($target.length) {
                    $target.fadeOut(250, function(){ location.reload(); });
                } else {
                    location.reload();
                }
            } else {
                alert('Failed: ' + (resp.data && resp.data.message ? resp.data.message : 'Error'));
                btn.prop('disabled', false).text('Delete');
            }
        });
    });

    // -- Cancel booking --------------------------------------------------------
    $(document).on('click', '.sbs-cancel-booking', function(e) {
        e.stopPropagation();
        const id  = $(this).data('id');
        const btn = $(this);
        const smsEnabled = !!(window.sbsAdmin && sbsAdmin.sms_enabled);
        const html = '<div id="yn-cm" style="position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:99999;display:flex;align-items:center;justify-content:center;">' +
            '<div style="background:#fff;border-radius:8px;padding:28px 32px;max-width:360px;width:90%;box-shadow:0 8px 24px rgba(0,0,0,.25);">' +
            '<h3 style="margin:0 0 10px;">Cancel Booking #' + id + '</h3>' +
            '<p style="margin:0 0 14px;color:#555;font-size:14px;">This will cancel the appointment and update its status.</p>' +
            '<div style="margin-bottom:18px;">' +
            '<div style="font-size:13px;font-weight:600;color:#374151;margin-bottom:8px;">Notify the customer?</div>' +
            '<label style="display:flex;align-items:center;gap:8px;font-size:14px;margin-bottom:6px;cursor:pointer;">' +
            '<input type="radio" name="yn-notify-method" value="none" style="width:16px;height:16px;"> Don&rsquo;t notify' +
            '</label>' +
            '<label style="display:flex;align-items:center;gap:8px;font-size:14px;margin-bottom:6px;cursor:pointer;">' +
            '<input type="radio" name="yn-notify-method" value="email" checked style="width:16px;height:16px;"> Email' +
            '</label>' +
            (smsEnabled ? (
            '<label style="display:flex;align-items:center;gap:8px;font-size:14px;margin-bottom:6px;cursor:pointer;">' +
            '<input type="radio" name="yn-notify-method" value="sms" style="width:16px;height:16px;"> Text message' +
            '</label>' +
            '<label style="display:flex;align-items:center;gap:8px;font-size:14px;margin-bottom:6px;cursor:pointer;">' +
            '<input type="radio" name="yn-notify-method" value="both" style="width:16px;height:16px;"> Email &amp; Text' +
            '</label>'
            ) : '') +
            '</div>' +
            '<div style="display:flex;gap:10px;justify-content:flex-end;">' +
            '<button id="yn-cm-no" class="button" style="padding:6px 16px;">Keep</button>' +
            '<button id="yn-cm-yes" class="button button-primary" style="background:#e53e3e;border-color:#c53030;padding:6px 16px;">Yes, Cancel</button>' +
            '</div></div></div>';
        const modal = $(html);
        $('body').append(modal);
        modal.find('#yn-cm-no').on('click', function(){ modal.remove(); });
        modal.on('click', function(ev){ if($(ev.target).is(modal)) modal.remove(); });
        modal.find('#yn-cm-yes').on('click', function(){
            const notifyMethod = modal.find('input[name="yn-notify-method"]:checked').val() || 'none';
            modal.remove();
            btn.prop('disabled', true).text('...');
            $.post(ajaxurl, {
                action:          'yatoon_cancel_booking',
                nonce:           yatoonBookingsData.cancelNonce,
                id:              id,
                notify_method:   notifyMethod
            }, function(resp) {
                if (resp.success) {
                    const $target = $('tr').filter(function(){ return $(this).find('.sbs-cancel-booking[data-id="'+id+'"]').length; });
                    if ($target.length) {
                        $target.css('opacity', 0.4);
                    }
                    location.reload();
                } else {
                    alert('Failed: ' + (resp.data && resp.data.message ? resp.data.message : 'Error'));
                    btn.prop('disabled', false).text('Cancel');
                }
            });
        });
    });
});

jQuery(function($){
    const yatoonOpsNonce = yatoonBookingsData.adminNonce;
    $(document).on('click', '.yatoon-send-payment-request', function(e){
        e.stopPropagation();
        const $btn = $(this).prop('disabled', true).text('Sending...');
        $.post(ajaxurl, {
            action: 'yatoon_send_payment_request',
            nonce: yatoonOpsNonce,
            booking_id: $btn.data('id')
        }, function(resp){
            $btn.text(resp.success ? 'Request Sent' : 'Failed');
            if (!resp.success) {
                alert(resp.data && resp.data.message ? resp.data.message : 'Could not send payment request.');
                $btn.prop('disabled', false).text('Payment Request');
            }
        }).fail(function(){
            alert('Network error.');
            $btn.prop('disabled', false).text('Payment Request');
        });
    });
});
