<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
if ( ! defined( 'ABSPATH' ) ) exit;
$nonce = wp_create_nonce( 'yatoon_admin_nonce' );
$segment_types = YATOON_Broadcasts::get_segment_types();
?>
<div class="wrap sbs-admin-page" id="yatoon-broadcasts-wrap">
    <h1>Broadcasts</h1>
    <p class="yatoon-admin-subtitle">Send a one-off email or SMS to a group of clients - win back lapsed clients, promote a new service, or reach everyone who's booked something specific.</p>

    <style>
    #yatoon-broadcasts-wrap .yb-toolbar{display:flex;justify-content:flex-end;margin:16px 0;}
    #yatoon-broadcasts-wrap .yb-row{
        display:flex;align-items:center;gap:0;background:#fff;border:1px solid #e5e7eb;border-radius:12px;
        box-shadow:0 1px 4px rgba(15,23,42,.05);margin-bottom:12px;padding:16px 20px;
    }
    #yatoon-broadcasts-wrap .yb-row-main{flex:1;}
    #yatoon-broadcasts-wrap .yb-row-name{font-weight:700;font-size:14px;}
    #yatoon-broadcasts-wrap .yb-row-detail{color:#6b7280;font-size:12.5px;margin-top:3px;}
    #yatoon-broadcasts-wrap .yb-badge{display:inline-block;padding:3px 10px;border-radius:999px;font-size:11px;font-weight:700;text-transform:uppercase;}
    #yatoon-broadcasts-wrap .yb-badge-draft{background:#f3f4f6;color:#6b7280;}
    #yatoon-broadcasts-wrap .yb-badge-sending{background:#fef3c7;color:#92400e;}
    #yatoon-broadcasts-wrap .yb-badge-sent{background:#dcfce7;color:#166534;}
    #yatoon-broadcasts-wrap .yb-empty{text-align:center;padding:60px 20px;background:#fff;border:1px dashed #d1d5db;border-radius:12px;color:#6b7280;}
    /* Modal */
    #yb-modal-overlay{display:none;position:fixed;inset:0;background:rgba(15,23,42,.5);z-index:100000;align-items:center;justify-content:center;padding:20px;}
    #yb-modal-overlay.is-open{display:flex;}
    #yb-modal{background:#fff;border-radius:14px;max-width:560px;width:100%;max-height:88vh;overflow-y:auto;padding:26px;position:relative;}
    #yb-modal h2{margin:0 0 18px;font-size:18px;}
    #yb-modal label{display:block;font-weight:700;font-size:12.5px;color:#374151;margin:14px 0 5px;}
    #yb-modal input[type=text], #yb-modal input[type=number], #yb-modal select, #yb-modal textarea{
        width:100%;box-sizing:border-box;border:1px solid #d1d5db;border-radius:8px;padding:9px 11px;font-size:13.5px;
    }
    #yb-modal textarea{min-height:110px;font-family:inherit;}
    #yb-modal-close{position:absolute;top:16px;right:16px;background:none;border:none;font-size:22px;cursor:pointer;color:#9ca3af;}
    #yb-segment-preview{margin-top:8px;font-size:13px;color:#374151;background:#f9fafb;border-radius:8px;padding:8px 12px;}
    #yb-progress-wrap{display:none;margin-top:16px;}
    #yb-progress-bar-track{background:#e5e7eb;border-radius:999px;height:10px;overflow:hidden;}
    #yb-progress-bar-fill{background:#16a34a;height:100%;width:0%;transition:width .2s;}
    #yb-progress-text{font-size:12.5px;color:#6b7280;margin-top:6px;}
    </style>

    <div class="yb-toolbar">
        <button type="button" class="button button-primary" id="yb-add-btn" style="height:38px;padding:0 20px;">+ New Broadcast</button>
    </div>

    <div id="yb-list">
        <?php if ( empty( $broadcasts ) ) : ?>
            <div class="yb-empty">
                <p style="font-size:15px;font-weight:600;color:#111827;">No broadcasts yet</p>
                <p>Try one: "It's been a while! Come back for 15% off your next Gel Manicure."</p>
            </div>
        <?php else : foreach ( $broadcasts as $b ) :
            $badge_class = 'yb-badge-' . ( $b->status === 'sent' ? 'sent' : ( $b->status === 'sending' ? 'sending' : 'draft' ) );
            $segment_label = $segment_types[ $b->segment_type ] ?? $b->segment_type;
        ?>
        <div class="yb-row" data-id="<?php echo intval( $b->id ); ?>">
            <div class="yb-row-main">
                <div class="yb-row-name"><?php echo esc_html( $b->name ); ?> <span class="yb-badge <?php echo esc_attr( $badge_class ); ?>"><?php echo esc_html( $b->status ); ?></span></div>
                <div class="yb-row-detail">
                    <?php echo esc_html( ucfirst( $b->channel ) ); ?> - <?php echo esc_html( $segment_label ); ?> - <?php echo intval( $b->recipient_count ); ?> recipients
                    <?php if ( $b->status === 'sent' ) : ?>
                        - sent <?php echo intval( $b->sent_count ); ?><?php echo $b->failed_count ? ' (' . intval( $b->failed_count ) . ' failed)' : ''; ?> on <?php echo esc_html( mysql2date( 'M j, Y g:ia', $b->sent_at ) ); ?>
                    <?php endif; ?>
                </div>
            </div>
            <?php if ( $b->status !== 'sent' ) : ?>
                <button type="button" class="button button-primary yb-resume-send" data-id="<?php echo intval( $b->id ); ?>" data-remaining="<?php echo intval( $b->recipient_count - $b->sent_count - $b->failed_count ); ?>">Send</button>
            <?php endif; ?>
            <button type="button" class="button yb-delete" style="color:#dc2626;margin-left:8px;">Delete</button>
        </div>
        <?php endforeach; endif; ?>
    </div>
</div>

<div id="yb-modal-overlay">
    <div id="yb-modal">
        <button type="button" id="yb-modal-close">&times;</button>
        <h2>New Broadcast</h2>

        <label for="yb-field-name">Name (for your reference)</label>
        <input type="text" id="yb-field-name" placeholder="e.g. Win-back 60 days">

        <label for="yb-field-segment">Send to</label>
        <select id="yb-field-segment">
            <?php foreach ( $segment_types as $slug => $label ) : ?>
                <option value="<?php echo esc_attr( $slug ); ?>"><?php echo esc_html( $label ); ?></option>
            <?php endforeach; ?>
        </select>

        <div id="yb-field-days-wrap" style="display:none;">
            <label for="yb-field-days">Days since last visit</label>
            <input type="number" id="yb-field-days" min="1" value="60">
        </div>
        <div id="yb-field-service-wrap" style="display:none;">
            <label for="yb-field-service">Service</label>
            <select id="yb-field-service">
                <?php foreach ( $services as $s ) : ?>
                    <option value="<?php echo intval( $s->id ); ?>"><?php echo esc_html( $s->name ); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div id="yb-field-tag-wrap" style="display:none;">
            <label for="yb-field-tag">Tag</label>
            <input type="text" id="yb-field-tag" placeholder="e.g. VIP">
        </div>
        <div id="yb-segment-preview">Recipients: <strong id="yb-segment-count">-</strong></div>

        <label for="yb-field-channel">Channel</label>
        <select id="yb-field-channel">
            <option value="email">Email</option>
            <option value="sms">SMS</option>
        </select>

        <div id="yb-field-subject-wrap">
            <label for="yb-field-subject">Subject (for emails)</label>
            <input type="text" id="yb-field-subject" placeholder="e.g. We miss you!">
        </div>

        <label for="yb-field-message">Message</label>
        <textarea id="yb-field-message" placeholder="Hi {customer_first_name}, it's been a while! Come back this month for 15% off..."></textarea>
        <p style="font-size:11.5px;color:#6b7280;margin-top:4px;">
            Click to insert:
            <?php foreach ( array( '{customer_first_name}', '{business_name}' ) as $tag ) : ?>
                <code class="yb-tag-insert" style="background:#f3f4f6;padding:1px 5px;border-radius:4px;cursor:pointer;"><?php echo esc_html( $tag ); ?></code>
            <?php endforeach; ?>
        </p>

        <div id="yb-progress-wrap">
            <div id="yb-progress-bar-track"><div id="yb-progress-bar-fill"></div></div>
            <div id="yb-progress-text">Sending...</div>
        </div>

        <div style="margin-top:20px;display:flex;justify-content:space-between;align-items:center;">
            <span id="yb-modal-msg" style="font-size:13px;color:#dc2626;"></span>
            <div>
                <button type="button" class="button" id="yb-modal-cancel">Cancel</button>
                <button type="button" class="button button-primary" id="yb-save-send">Review & Send</button>
            </div>
        </div>
    </div>
</div>

<script>
jQuery(function($) {
    const nonce = '<?php echo esc_js( $nonce ); ?>';
    let currentBroadcastId = null;

    function openModal() {
        $('#yb-field-name').val('');
        $('#yb-field-segment').val('all');
        $('#yb-field-days').val(60);
        $('#yb-field-tag').val('');
        $('#yb-field-channel').val('email');
        $('#yb-field-subject').val('');
        $('#yb-field-message').val('');
        $('#yb-modal-msg').text('');
        $('#yb-progress-wrap').hide();
        $('#yb-save-send').show().prop('disabled', false).text('Review & Send');
        syncSegmentFields();
        refreshSegmentCount();
        $('#yb-modal-overlay').addClass('is-open');
    }
    function closeModal() { $('#yb-modal-overlay').removeClass('is-open'); }

    function syncSegmentFields() {
        const seg = $('#yb-field-segment').val();
        $('#yb-field-days-wrap').toggle(seg === 'inactive_days');
        $('#yb-field-service-wrap').toggle(seg === 'service_history');
        $('#yb-field-tag-wrap').toggle(seg === 'tag');
    }

    function refreshSegmentCount() {
        $('#yb-segment-count').text('...');
        $.post(ajaxurl, {
            action: 'yatoon_broadcast_segment_count',
            nonce: nonce,
            segment_type: $('#yb-field-segment').val(),
            days: $('#yb-field-days').val(),
            service_id: $('#yb-field-service').val(),
            tag: $('#yb-field-tag').val(),
        }, function(resp) {
            $('#yb-segment-count').text(resp.success ? resp.data.count : '?');
        });
    }

    $('#yb-add-btn').on('click', openModal);
    $('#yb-modal-close, #yb-modal-cancel').on('click', closeModal);
    $('#yb-modal-overlay').on('click', function(e) { if (e.target === this) closeModal(); });
    $('#yb-field-segment, #yb-field-days, #yb-field-service, #yb-field-tag').on('change input', function() {
        syncSegmentFields();
        refreshSegmentCount();
    });

    $(document).on('click', '.yb-tag-insert', function() {
        const $ta = $('#yb-field-message');
        const tag = $(this).text();
        const el = $ta.get(0);
        const start = el.selectionStart || $ta.val().length;
        const val = $ta.val();
        $ta.val(val.slice(0, start) + tag + val.slice(start));
        el.focus();
    });

    function sendNextBatch(broadcastId, totalCount) {
        $.post(ajaxurl, {
            action: 'yatoon_broadcast_send_batch',
            nonce: nonce,
            broadcast_id: broadcastId,
        }, function(resp) {
            if (!resp.success) {
                $('#yb-progress-text').text('Error sending - stopped.');
                return;
            }
            const sentSoFar = resp.data.sent_count + resp.data.failed_count;
            const pct = totalCount ? Math.round((sentSoFar / totalCount) * 100) : 100;
            $('#yb-progress-bar-fill').css('width', pct + '%');
            $('#yb-progress-text').text(`Sent ${resp.data.sent_count} of ${totalCount}${resp.data.failed_count ? ', ' + resp.data.failed_count + ' failed' : ''}...`);
            if (resp.data.done) {
                $('#yb-progress-text').text(`Done - sent ${resp.data.sent_count} of ${totalCount}${resp.data.failed_count ? ', ' + resp.data.failed_count + ' failed' : ''}.`);
                setTimeout(() => location.reload(), 1200);
            } else {
                sendNextBatch(broadcastId, totalCount);
            }
        });
    }

    $('#yb-save-send').on('click', function() {
        const $btn = $(this);
        const name = $('#yb-field-name').val().trim();
        const message = $('#yb-field-message').val().trim();
        if (!name || !message) {
            $('#yb-modal-msg').text('Please fill in a name and message.');
            return;
        }
        const count = parseInt($('#yb-segment-count').text(), 10) || 0;
        if (!confirm(`Send this to ${count} recipient(s)? This can't be undone.`)) return;

        $btn.prop('disabled', true).text('Sending...');
        $.post(ajaxurl, {
            action: 'yatoon_broadcast_save_draft',
            nonce: nonce,
            name: name,
            channel: $('#yb-field-channel').val(),
            subject: $('#yb-field-subject').val(),
            message: message,
            segment_type: $('#yb-field-segment').val(),
            days: $('#yb-field-days').val(),
            service_id: $('#yb-field-service').val(),
            tag: $('#yb-field-tag').val(),
        }, function(resp) {
            if (!resp.success) {
                $('#yb-modal-msg').text((resp.data && resp.data.message) || 'Could not save.');
                $btn.prop('disabled', false).text('Review & Send');
                return;
            }
            $btn.hide();
            $('#yb-progress-wrap').show();
            sendNextBatch(resp.data.broadcast_id, resp.data.recipient_count);
        });
    });

    $(document).on('click', '.yb-resume-send', function() {
        const id = $(this).data('id');
        const remaining = $(this).data('remaining');
        if (!confirm(`Resume sending to the remaining ${remaining} recipient(s)?`)) return;
        openModal();
        $('#yb-modal h2').text('Sending...');
        $('#yb-save-send').hide();
        $('#yb-progress-wrap').show();
        sendNextBatch(id, remaining);
    });

    $(document).on('click', '.yb-delete', function() {
        if (!confirm('Delete this broadcast? This cannot be undone.')) return;
        const $row = $(this).closest('.yb-row');
        $.post(ajaxurl, {
            action: 'yatoon_broadcast_delete',
            nonce: nonce,
            id: $row.data('id'),
        }, function(resp) {
            if (resp.success) $row.remove();
        });
    });
});
</script>
