<?php if ( ! defined( 'ABSPATH' ) ) { exit; } ?>
<div class="wrap sbs-admin-page sbs-messages-page">
    <style>
        .sbs-admin-table-wrap {
            width: 100%;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }
        .sbs-admin-table-wrap .wp-list-table {
            min-width: 980px;
        }
    </style>
    <h1>Contact Messages</h1>
    
    <p class="description">Messages submitted through the "Text Us" button on your booking page.</p>

    <?php if (empty($messages)) : ?>
        <div class="notice notice-info">
            <p>No messages yet. Messages will appear here when customers contact you.</p>
        </div>
    <?php else : ?>
        <div class="sbs-table-toolbar">
            <div class="sbs-table-search">
                <input type="search" id="sbs-message-search" class="regular-text" autocomplete="off" placeholder="Search name, phone, message, or IP">
                <button type="button" id="sbs-message-clear-search" class="button">Clear</button>
            </div>
            <div class="sbs-table-actions">
                <button type="button" id="sbs-delete-selected-messages" class="button action" disabled>Delete Selected</button>
                <button type="button" id="sbs-export-messages" class="button action">Export CSV</button>
            </div>
        </div>
        <div class="sbs-admin-table-wrap">
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr data-search="<?php echo esc_attr(strtolower($msg->id . ' ' . $msg->name . ' ' . $msg->phone . ' ' . $msg->message . ' ' . $msg->ip_address)); ?>">
                    <td class="manage-column check-column">
                        <input type="checkbox" id="sbs-select-all-messages">
                    </td>
                    <th style="width:50px;">ID</th>
                    <th style="width:140px;">Date</th>
                    <th style="width:150px;">Name</th>
                    <th style="width:130px;">Phone</th>
                    <th>Message</th>
                    <?php if (function_exists('yatoon_is_pro') && yatoon_is_pro()) : ?>
                        <th style="width:150px;">AI Draft</th>
                    <?php endif; ?>
                    <th style="width:100px;">IP</th>
                </tr>
            </thead>
            <tbody>
                <?php // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ?>
                <?php foreach ($messages as $msg) : ?>
                <tr>
                    <th class="check-column">
                        <input type="checkbox" class="sbs-message-checkbox" value="<?php echo esc_html( $msg->id ); ?>">
                    </th>
                    <td><?php echo esc_html( $msg->id ); ?></td>
                    <td><?php echo esc_html( gmdate( 'M j, Y g:i A', strtotime( $msg->created_at ) ) ); ?></td>
                    <td><strong><?php echo esc_html($msg->name); ?></strong></td>
                    <td>
                        <a href="tel:<?php echo esc_attr($msg->phone); ?>" style="text-decoration:none;">
                            📱 <?php echo esc_html($msg->phone); ?>
                        </a>
                    </td>
                    <td>
                        <?php 
                        $fullMessage = $msg->message; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                        $trimmed = wp_trim_words($fullMessage, 15); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                        $isTrimmed = strlen($fullMessage) > strlen($trimmed); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                        ?>
                        <span class="message-preview" style="cursor: <?php echo esc_html( $isTrimmed ? 'pointer' : 'default' ); ?>;" 
                              data-full-message="<?php echo esc_attr($fullMessage); ?>"
                              onclick="<?php echo esc_html( $isTrimmed ? 'showFullMessage(this)' : '' ); ?>">
                            <?php echo esc_html( nl2br(esc_html($trimmed)) ); ?>
                            <?php if ($isTrimmed) : ?>
                                <span style="color: #2271b1; text-decoration: underline; margin-left: 4px;">Read more</span>
                            <?php endif; ?>
                        </span>
                    </td>
                    <?php if (function_exists('yatoon_is_pro') && yatoon_is_pro()) : ?>
                    <td>
                        <button type="button" class="button yatoon-ai-draft-btn" data-message-id="<?php echo esc_attr($msg->id); ?>">Generate</button>
                        <div class="yatoon-ai-draft-output" id="yatoon-ai-draft-<?php echo esc_attr($msg->id); ?>" style="display:none;"></div>
                    </td>
                    <?php endif; ?>
                    <td style="font-size:11px; color:#999;"><?php echo esc_html($msg->ip_address); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        </div>
    <?php endif; ?>
</div>

<style>
.wp-list-table td { vertical-align: top; padding: 12px 10px; }
.wp-list-table a[href^="tel:"] { color: #ec4899; font-weight: 600; }
.wp-list-table a[href^="tel:"]:hover { color: #db2777; }
.yatoon-ai-draft-output {
    margin-top: 8px;
    padding: 8px;
    border: 1px solid #dbe4ef;
    border-radius: 6px;
    background: #f8fafc;
    color: #334155;
    white-space: pre-wrap;
}
</style>

<script>
function showFullMessage(element) {
    const fullMessage = element.getAttribute('data-full-message');
    
    // 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 Message</h2>
        <p style="white-space: pre-wrap; line-height: 1.6;">${escapeHtml(fullMessage)}</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;
}

// Messages bulk delete
jQuery(document).ready(function($) {
    $('#sbs-select-all-messages').on('change', function() {
        $('.sbs-message-checkbox').prop('checked', $(this).prop('checked'));
        updateMessagesDeleteButton();
    });
    
    $('.sbs-message-checkbox').on('change', function() {
        updateMessagesDeleteButton();
        const total = $('.sbs-message-checkbox').length;
        const checked = $('.sbs-message-checkbox:checked').length;
        $('#sbs-select-all-messages').prop('checked', total === checked);
    });
    
    function updateMessagesDeleteButton() {
        const checked = $('.sbs-message-checkbox:checked').length;
        $('#sbs-delete-selected-messages')
            .prop('disabled', checked === 0)
            .text(checked > 0 ? 'Delete (' + checked + ')' : 'Delete Selected');
    }

    function applyMessageSearch() {
        const q = ($('#sbs-message-search').val() || '').toLowerCase().trim();
        $('.sbs-message-checkbox').closest('tr').each(function() {
            $(this).toggle(!q || String($(this).data('search') || '').indexOf(q) !== -1);
        });
    }

    $('#sbs-message-search').on('input', applyMessageSearch);
    $('#sbs-message-clear-search').on('click', function() {
        $('#sbs-message-search').val('');
        applyMessageSearch();
    });
    
    $('#sbs-delete-selected-messages').on('click', function() {
        const selected = [];
        $('.sbs-message-checkbox:checked').each(function() {
            selected.push($(this).val());
        });
        
        if (selected.length === 0) return;
        
        if (!confirm('Delete ' + selected.length + ' message(s)?')) return;
        
        const btn = $(this);
        btn.prop('disabled', true).text('Deleting...');
        
        $.post(ajaxurl, {
            action: 'yatoon_delete_messages',
            nonce: '<?php echo esc_html( wp_create_nonce("yatoon_delete_messages") ); ?>',
            ids: selected
        }, function(resp) {
            if (resp.success) {
                selected.forEach(function(id) {
                    $('.sbs-message-checkbox[value="' + id + '"]').closest('tr').fadeOut(300, function() {
                        $(this).remove();
                        if ($('.sbs-message-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-messages').on('click', function() {
        window.location.href = ajaxurl + '?action=yatoon_export_messages&nonce=<?php echo esc_html( wp_create_nonce("yatoon_export_messages") ); ?>';
    });

    $('.yatoon-ai-draft-btn').on('click', function() {
        const btn = $(this);
        const id = btn.data('message-id');
        const out = $('#yatoon-ai-draft-' + id);
        btn.prop('disabled', true).text('Generating...');
        out.hide().empty();

        $.post(ajaxurl, {
            action: 'yatoon_ai_message_reply',
            nonce: '<?php echo esc_js(wp_create_nonce("yatoon_ai_message_reply")); ?>',
            message_id: id
        }, function(resp) {
            if (resp && resp.success && resp.data && resp.data.reply) {
                out.text(resp.data.reply).show();
            } else {
                const msg = resp && resp.data && resp.data.message ? resp.data.message : 'AI could not generate a draft.';
                out.text(msg).show();
            }
        }).fail(function() {
            out.text('AI could not generate a draft.').show();
        }).always(function() {
            btn.prop('disabled', false).text('Regenerate');
        });
    });
});
</script>
