<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
?>
<div class="wrap">
    <style>
        .sbs-admin-table-wrap {
            width: 100%;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }
        .sbs-admin-table-wrap .wp-list-table {
            min-width: 1180px;
        }
    </style>
    <h1><?php esc_html_e( 'Waitlist Requests', 'yatoon-booking-system' ); ?></h1>
    <div class="notice notice-info" style="padding:10px 12px;">
        <p style="margin:0 0 8px;">
            <strong><?php esc_html_e( 'Automation:', 'yatoon-booking-system' ); ?></strong>
            <?php echo esc_html( get_option('yatoon_waitlist_auto_notify', '1') === '1' ? 'On' : 'Off' ); ?>.
            The system checks active, not-yet-notified waitlist requests about every 15 minutes and emails the customer when a matching opening appears.
        </p>
        <button type="button" id="yatoon-check-waitlist-now" class="button"><?php esc_html_e( 'Check Openings Now', 'yatoon-booking-system' ); ?></button>
        <?php
        $booking_url = get_option('yatoon_book_new_url', '');
        if (!$booking_url) {
            $booking_page = get_page_by_path('booking');
            $booking_url = $booking_page ? get_permalink($booking_page->ID) : home_url('/');
        }
        ?>
        <a href="<?php echo esc_url($booking_url); ?>" class="button" target="_blank" rel="noreferrer"><?php esc_html_e( 'Open Booking Page', 'yatoon-booking-system' ); ?></a>
        <span id="yatoon-check-waitlist-result" style="margin-left:8px;color:#666;"></span>
    </div>
    
    <?php if (empty($waitlist)) : ?>
        <div class="notice notice-info">
            <p><?php esc_html_e( 'No active waitlist requests.', 'yatoon-booking-system' ); ?></p>
        </div>
    <?php else : ?>
        <div class="tablenav top">
            <div class="alignleft actions bulkactions">
                <button type="button" id="sbs-delete-selected-waitlist" class="button action" disabled>
                    <?php esc_html_e( 'Delete Selected', 'yatoon-booking-system' ); ?>
                </button>
                <button type="button" id="sbs-export-waitlist" class="button action">
                    <?php esc_html_e( 'Export CSV', 'yatoon-booking-system' ); ?>
                </button>
            </div>
        </div>
        <div class="sbs-admin-table-wrap">
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <td class="manage-column check-column">
                        <input type="checkbox" id="sbs-select-all-waitlist">
                    </td>
                    <th style="width: 50px;">ID</th>
                    <th><?php esc_html_e( 'Customer', 'yatoon-booking-system' ); ?></th>
                    <th><?php esc_html_e( 'Contact', 'yatoon-booking-system' ); ?></th>
                    <th><?php esc_html_e( 'Service(s)', 'yatoon-booking-system' ); ?></th>
                    <th><?php esc_html_e( 'Preferred Date', 'yatoon-booking-system' ); ?></th>
                    <th><?php esc_html_e( 'Preferred Time', 'yatoon-booking-system' ); ?></th>
                    <th><?php esc_html_e( 'Flexibility', 'yatoon-booking-system' ); ?></th>
                    <th><?php esc_html_e( 'Notes', 'yatoon-booking-system' ); ?></th>
                    <th><?php esc_html_e( 'Submitted', 'yatoon-booking-system' ); ?></th>
                    <th><?php esc_html_e( 'Automation', 'yatoon-booking-system' ); ?></th>
                    <th style="width: 120px;"><?php esc_html_e( 'Actions', 'yatoon-booking-system' ); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php
                $time_labels = array( // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                    'morning'        => 'Morning (10-12)',
                    'afternoon'      => 'Afternoon (12-4)',
                    'late_afternoon' => 'Late PM (4-7)',
                    'any'            => 'Any Time',
                    ''               => '-',
                );
                foreach ($waitlist as $item) : // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                    $time_label = $time_labels[ $item->preferred_time ?? '' ] ?? ( $item->preferred_time ?: '-' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                ?>
                    <tr>
                        <th class="check-column">
                            <input type="checkbox" class="sbs-waitlist-checkbox" value="<?php echo esc_attr( $item->id ); ?>">
                        </th>
                        <td><?php echo esc_html( $item->id ); ?></td>
                        <td><strong><?php echo esc_html($item->customer_name); ?></strong></td>
                        <td>
                            <?php echo esc_html($item->customer_email); ?><br>
                            <small style="color: #666;"><?php echo esc_html($item->customer_phone); ?></small>
                        </td>
                        <td>
                            <?php
                            // Show service name. Notes may contain "Services: X, Y" for multi-select
                            if (!empty($item->notes) && strpos($item->notes, 'Services:') === 0) {
                                // Multi-service stored in notes
                                $first_line = strtok($item->notes, "\n"); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                                echo '<span style="font-size:12px; color:#374151;">' . esc_html(substr($first_line, 10)) . '</span>';
                            } else {
                                echo esc_html($item->service_name ?: '-');
                            }
                            ?>
                        </td>
                        <td><?php echo esc_html( gmdate( 'M j, Y', strtotime( $item->preferred_date ) ) ); ?></td>
                        <td>
                            <span style="font-size:12px; white-space:nowrap;"><?php echo esc_html($time_label); ?></span>
                        </td>
                        <td>
                            <?php if ($item->flexible_dates) : ?>
                                <span style="display: inline-block; background: #d1fae5; color: #065f46; padding: 2px 8px; border-radius: 12px; font-size: 11px; margin-right: 4px;"><?php esc_html_e( 'Dates flexible', 'yatoon-booking-system' ); ?></span>
                            <?php endif; ?>
                            <?php if ($item->flexible_times) : ?>
                                <span style="display: inline-block; background: #dbeafe; color: #1e40af; padding: 2px 8px; border-radius: 12px; font-size: 11px;"><?php esc_html_e( 'Times flexible', 'yatoon-booking-system' ); ?></span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php
                            // If notes starts with Services: line, show the rest
                            $display_notes = $item->notes; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                            if (!empty($display_notes) && strpos($display_notes, 'Services:') === 0) {
                                $display_notes = trim(substr($display_notes, strpos($display_notes, "\n") ?: strlen($display_notes))); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                            }
                            if ($display_notes) :
                                $trimmed = wp_trim_words($display_notes, 10); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                                $isTrimmed = strlen($display_notes) > strlen($trimmed); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                            ?>
                                <span class="waitlist-notes-preview" style="color: #666; cursor: <?php echo esc_attr( $isTrimmed ? 'pointer' : 'default' ); ?>;"
                                      data-full-notes="<?php echo esc_attr($display_notes); ?>"
                                      onclick="<?php echo esc_attr( $isTrimmed ? 'showFullNotes(this)' : '' ); ?>">
                                    <?php echo esc_html($trimmed); ?>
                                    <?php if ($isTrimmed) : ?>
                                        <span style="color: #2271b1; text-decoration: underline;"><?php esc_html_e( 'Read more', 'yatoon-booking-system' ); ?></span>
                                    <?php endif; ?>
                                </span>
                            <?php else : ?>
                                <small style="color: #999;">-</small>
                            <?php endif; ?>
                        </td>
                        <td>
                            <small style="color: #666;">
                                <?php echo esc_html( human_time_diff( strtotime( $item->created_at ), current_time( 'timestamp' ) ) ); ?> ago
                            </small>
                        </td>
                        <td>
                            <?php if (!empty($item->notified)) : ?>
                                <span style="display:inline-block;background:#dcfce7;color:#166534;padding:2px 8px;border-radius:12px;font-size:11px;font-weight:600;"><?php esc_html_e( 'Notified', 'yatoon-booking-system' ); ?></span><br>
                                <small style="color:#666;">
                                    <?php echo esc_html($item->matched_date ?: ''); ?>
                                    <?php echo esc_html($item->matched_time ?: ''); ?>
                                </small>
                            <?php else : ?>
                                <span style="display:inline-block;background:#fef3c7;color:#92400e;padding:2px 8px;border-radius:12px;font-size:11px;font-weight:600;"><?php esc_html_e( 'Watching', 'yatoon-booking-system' ); ?></span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if (empty($item->notified)) : ?>
                                <button type="button" class="button button-primary button-small yatoon-notify-waitlist" data-id="<?php echo esc_attr($item->id); ?>"><?php esc_html_e( 'Notify', 'yatoon-booking-system' ); ?></button>
                            <?php endif; ?>
                            <a href="mailto:<?php echo esc_attr($item->customer_email); ?>" class="button button-small"><?php esc_html_e( 'Email', 'yatoon-booking-system' ); ?></a>
                            <a href="tel:<?php echo esc_attr($item->customer_phone); ?>" class="button button-small"><?php esc_html_e( 'Call', 'yatoon-booking-system' ); ?></a>
                            <a href="<?php echo esc_url($booking_url); ?>" class="button button-small" target="_blank" rel="noreferrer"><?php esc_html_e( 'Book', 'yatoon-booking-system' ); ?></a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        
        <p class="description" style="margin-top: 20px;">
            <strong><?php esc_html_e( 'Tip:', 'yatoon-booking-system' ); ?></strong> <?php esc_html_e( 'When a slot opens up, use Notify to email the customer first.', 'yatoon-booking-system' ); ?>
        </p>
    <?php endif; ?>
</div>

<style>
.wp-list-table td {
    vertical-align: middle;
}
</style>

<script>
function showFullNotes(element) {
    const fullNotes = element.getAttribute('data-full-notes');
    
    // Create modal
    const modal = document.createElement('div');
    modal.style.cssText = 'position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 100000; display: flex; align-items: center; justify-content: center;';
    
    const content = document.createElement('div');
    content.style.cssText = 'background: white; padding: 30px; border-radius: 8px; max-width: 600px; width: 90%; max-height: 80vh; overflow-y: auto; box-shadow: 0 4px 20px rgba(0,0,0,0.3);';
    
    content.innerHTML = `
        <h2 style="margin-top: 0;">Customer Notes</h2>
        <p style="white-space: pre-wrap; line-height: 1.6;">${escapeHtml(fullNotes)}</p>
        <button onclick="this.closest('[style*=fixed]').remove()" style="margin-top: 20px; padding: 8px 16px; background: #2271b1; color: white; border: none; border-radius: 4px; cursor: pointer;">Close</button>
    `;
    
    modal.appendChild(content);
    document.body.appendChild(modal);
    
    // Click background to close
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            modal.remove();
        }
    });
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Waitlist bulk delete
jQuery(document).ready(function($) {
    $('#sbs-select-all-waitlist').on('change', function() {
        $('.sbs-waitlist-checkbox').prop('checked', $(this).prop('checked'));
        updateWaitlistDeleteButton();
    });
    
    $('.sbs-waitlist-checkbox').on('change', function() {
        updateWaitlistDeleteButton();
        const total = $('.sbs-waitlist-checkbox').length;
        const checked = $('.sbs-waitlist-checkbox:checked').length;
        $('#sbs-select-all-waitlist').prop('checked', total === checked);
    });
    
    function updateWaitlistDeleteButton() {
        const checked = $('.sbs-waitlist-checkbox:checked').length;
        $('#sbs-delete-selected-waitlist')
            .prop('disabled', checked === 0)
            .text(checked > 0 ? 'Delete (' + checked + ')' : 'Delete Selected');
    }
    
    $('#sbs-delete-selected-waitlist').on('click', function() {
        const selected = [];
        $('.sbs-waitlist-checkbox:checked').each(function() {
            selected.push($(this).val());
        });
        
        if (selected.length === 0) return;
        
        if (!confirm('Delete ' + selected.length + ' waitlist request(s)?')) return;
        
        const btn = $(this);
        btn.prop('disabled', true).text('Deleting...');
        
        $.post(ajaxurl, {
            action: 'yatoon_delete_waitlist',
            nonce: '<?php echo esc_js( wp_create_nonce('yatoon_delete_waitlist') ); ?>',
            ids: selected
        }, function(resp) {
            if (resp.success) {
                selected.forEach(function(id) {
                    $('.sbs-waitlist-checkbox[value="' + id + '"]').closest('tr').fadeOut(300, function() {
                        $(this).remove();
                        if ($('.sbs-waitlist-checkbox').length === 0) location.reload();
                    });
                });
                btn.text('Delete Selected').prop('disabled', true);
            } else {
                alert('Failed: ' + (resp.data || 'Unknown error'));
                btn.text('Delete Selected').prop('disabled', false);
            }
        });
    });
    
    $('#sbs-export-waitlist').on('click', function() {
        window.location.href = ajaxurl + '?action=yatoon_export_waitlist&nonce=<?php echo esc_js( wp_create_nonce('yatoon_export_waitlist') ); ?>';
    });

    $('#yatoon-check-waitlist-now').on('click', function() {
        const btn = $(this);
        const result = $('#yatoon-check-waitlist-result');
        btn.prop('disabled', true).text('Checking...');
        result.text('');
        $.post(ajaxurl, {
            action: 'yatoon_check_waitlist_now',
            nonce: '<?php echo esc_js( wp_create_nonce('yatoon_waitlist_check') ); ?>'
        }, function(resp) {
            btn.prop('disabled', false).text('Check Openings Now');
            if (resp.success) {
                result.text('Checked ' + (resp.data.checked || 0) + ', notified ' + (resp.data.notified || 0) + '.');
                if ((resp.data.notified || 0) > 0) {
                    setTimeout(function(){ location.reload(); }, 1200);
                }
            } else {
                result.text('Check failed.');
            }
        });
    });
    $('.yatoon-notify-waitlist').on('click', function() {
        const btn = $(this);
        const id = btn.data('id');
        if (!id) return;
                if (!confirm(<?php echo wp_json_encode( __( 'Email this customer that an opening may be available?', 'yatoon-booking-system' ) ); ?>)) return;
        btn.prop('disabled', true).text('Sending...');
        $.post(ajaxurl, {
            action: 'yatoon_notify_waitlist_customer',
            nonce: '<?php echo esc_js( wp_create_nonce('yatoon_waitlist_notify') ); ?>',
            id: id
        }, function(resp) {
            if (resp.success) {
                btn.closest('tr').find('td').eq(9).html('<span style="display:inline-block;background:#dcfce7;color:#166534;padding:2px 8px;border-radius:12px;font-size:11px;font-weight:600;">Notified</span>');
                btn.remove();
            } else {
                    alert((resp.data && resp.data.message) ? resp.data.message : <?php echo wp_json_encode( __( 'Could not notify customer.', 'yatoon-booking-system' ) ); ?>);
                btn.prop('disabled', false).text('Notify');
            }
        });
    });
});
</script>
