<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
if ( ! defined( 'ABSPATH' ) ) exit;
$nonce = wp_create_nonce( 'yatoon_admin_nonce' );
?>
<div class="wrap sbs-admin-page" id="yatoon-automations-wrap">
    <h1><?php esc_html_e( 'Automation', 'yatoon-booking-system' ); ?></h1>
    <p class="yatoon-admin-subtitle"><?php esc_html_e( 'When something happens, do something automatically - no more digging through scattered settings toggles.', 'yatoon-booking-system' ); ?></p>

    <style>
    #yatoon-automations-wrap .ya-toolbar{display:flex;justify-content:flex-end;margin:16px 0;}
    #yatoon-automations-wrap .ya-rule{
        display:flex;align-items:stretch;gap:0;background:#fff;border:1px solid #e5e7eb;border-radius:12px;
        box-shadow:0 1px 4px rgba(15,23,42,.05);margin-bottom:14px;overflow:hidden;
    }
    #yatoon-automations-wrap .ya-rule.is-disabled{opacity:.55;}
    #yatoon-automations-wrap .ya-rule-drag{
        display:flex;align-items:center;justify-content:center;width:32px;background:#f8fafc;
        color:#9ca3af;cursor:grab;border-right:1px solid #f0f2f5;
    }
    #yatoon-automations-wrap .ya-rule-body{display:flex;align-items:center;flex-wrap:wrap;gap:0;flex:1;padding:0;}
    #yatoon-automations-wrap .ya-node{
        display:flex;align-items:center;gap:10px;padding:16px 20px;min-width:220px;
    }
    #yatoon-automations-wrap .ya-node-icon{
        width:36px;height:36px;border-radius:10px;display:flex;align-items:center;justify-content:center;flex:0 0 auto;
    }
    #yatoon-automations-wrap .ya-node-trigger .ya-node-icon{background:#eff6ff;color:#2563eb;}
    #yatoon-automations-wrap .ya-node-action .ya-node-icon{background:#fdf2f8;color:#db2777;}
    #yatoon-automations-wrap .ya-node-label{font-size:11px;text-transform:uppercase;letter-spacing:.04em;color:#9ca3af;font-weight:700;margin-bottom:2px;}
    #yatoon-automations-wrap .ya-node-value{font-size:13.5px;font-weight:600;color:#111827;line-height:1.35;}
    #yatoon-automations-wrap .ya-arrow{display:flex;align-items:center;color:#cbd5e1;font-size:20px;padding:0 4px;}
    #yatoon-automations-wrap .ya-rule-name{
        padding:16px 4px 16px 20px;font-weight:700;color:#111827;min-width:170px;border-right:1px solid #f0f2f5;
    }
    #yatoon-automations-wrap .ya-rule-controls{display:flex;align-items:center;gap:6px;padding:0 16px;margin-left:auto;}
    #yatoon-automations-wrap .ya-rule-controls .button{padding:0 10px;height:30px;line-height:28px;}
    #yatoon-automations-wrap .ya-switch{position:relative;width:36px;height:20px;flex:0 0 auto;}
    #yatoon-automations-wrap .ya-switch input{opacity:0;width:0;height:0;}
    #yatoon-automations-wrap .ya-switch-track{position:absolute;inset:0;background:#d1d5db;border-radius:999px;cursor:pointer;transition:background .15s;}
    #yatoon-automations-wrap .ya-switch input:checked + .ya-switch-track{background:#16a34a;}
    #yatoon-automations-wrap .ya-switch-track::before{content:'';position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;background:#fff;transition:transform .15s;}
    #yatoon-automations-wrap .ya-switch input:checked + .ya-switch-track::before{transform:translateX(16px);}
    #yatoon-automations-wrap .ya-empty{
        text-align:center;padding:60px 20px;background:#fff;border:1px dashed #d1d5db;border-radius:12px;color:#6b7280;
    }
    /* Modal */
    #yatoon-automation-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;}
    #yatoon-automation-modal-overlay.is-open{display:flex;}
    #yatoon-automation-modal{background:#fff;border-radius:14px;max-width:560px;width:100%;max-height:88vh;overflow-y:auto;padding:26px;position:relative;}
    #yatoon-automation-modal h2{margin:0 0 18px;font-size:18px;}
    #yatoon-automation-modal label{display:block;font-weight:700;font-size:12.5px;color:#374151;margin:14px 0 5px;}
    #yatoon-automation-modal input[type=text], #yatoon-automation-modal input[type=number], #yatoon-automation-modal select, #yatoon-automation-modal textarea{
        width:100%;box-sizing:border-box;border:1px solid #d1d5db;border-radius:8px;padding:9px 11px;font-size:13.5px;
    }
    #yatoon-automation-modal textarea{min-height:110px;font-family:inherit;}
    #yatoon-automation-modal .ya-merge-tags{font-size:11.5px;color:#6b7280;margin-top:4px;line-height:1.6;}
    #yatoon-automation-modal .ya-merge-tags code{background:#f3f4f6;padding:1px 5px;border-radius:4px;cursor:pointer;}
    #yatoon-automation-modal-close{position:absolute;top:16px;right:16px;background:none;border:none;font-size:22px;cursor:pointer;color:#9ca3af;}
    #yatoon-automation-modal .ya-modal-actions{display:flex;justify-content:space-between;align-items:center;margin-top:20px;gap:10px;}
    #yatoon-automation-modal .ya-row-2{display:grid;grid-template-columns:1fr 1fr;gap:12px;}
    </style>

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

    <div id="ya-rule-list">
        <?php if ( empty( $rules ) ) : ?>
            <div class="ya-empty">
                <p style="font-size:15px;font-weight:600;color:#111827;">No automations yet</p>
                <p>Try one to start: "24 hours after a booking is still Pending, send an SMS asking the client to confirm."</p>
            </div>
        <?php else : ?>
            <?php foreach ( $rules as $rule ) :
                $trigger_meta = $trigger_types[ $rule->trigger_type ] ?? array( 'label' => $rule->trigger_type, 'icon' => 'dashicons-clock' );
                $action_meta  = $action_types[ $rule->action_type ] ?? array( 'label' => $rule->action_type, 'icon' => 'dashicons-email' );

                $trigger_value = $trigger_meta['label'];
                if ( ! empty( $rule->trigger_hours ) ) {
                    $trigger_value = str_replace( 'X', $rule->trigger_hours, $trigger_value );
                }
                if ( $rule->trigger_type === 'status_changed_to' && $rule->trigger_status ) {
                    $status_labels = YATOON_Automations::get_status_options();
                    $trigger_value = 'Booking status changes to ' . ( $status_labels[ $rule->trigger_status ] ?? $rule->trigger_status );
                }
            ?>
            <div class="ya-rule<?php echo $rule->is_enabled ? '' : ' is-disabled'; ?>" data-rule-id="<?php echo intval( $rule->id ); ?>"
                 data-rule='<?php echo esc_attr( wp_json_encode( $rule ) ); ?>'>
                <div class="ya-rule-drag" title="Drag to reorder"><span class="dashicons dashicons-menu"></span></div>
                <div class="ya-rule-name"><?php echo esc_html( $rule->name ); ?></div>
                <div class="ya-rule-body">
                    <div class="ya-node ya-node-trigger">
                        <div class="ya-node-icon"><span class="dashicons <?php echo esc_attr( $trigger_meta['icon'] ); ?>"></span></div>
                        <div>
                            <div class="ya-node-label">When</div>
                            <div class="ya-node-value"><?php echo esc_html( $trigger_value ); ?></div>
                        </div>
                    </div>
                    <div class="ya-arrow">&#8594;</div>
                    <div class="ya-node ya-node-action">
                        <div class="ya-node-icon"><span class="dashicons <?php echo esc_attr( $action_meta['icon'] ); ?>"></span></div>
                        <div>
                            <div class="ya-node-label">Then</div>
                            <div class="ya-node-value"><?php echo esc_html( $action_meta['label'] ); ?></div>
                        </div>
                    </div>
                </div>
                <div class="ya-rule-controls">
                    <label class="ya-switch">
                        <input type="checkbox" class="ya-toggle" <?php checked( $rule->is_enabled, 1 ); ?>>
                        <span class="ya-switch-track"></span>
                    </label>
                    <button type="button" class="button ya-edit-btn">Edit</button>
                    <button type="button" class="button ya-test-btn" title="Send a test using your most recent booking">Test</button>
                    <button type="button" class="button ya-delete-btn" style="color:#dc2626;">Delete</button>
                </div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<div id="yatoon-automation-modal-overlay">
    <div id="yatoon-automation-modal">
        <button type="button" id="yatoon-automation-modal-close">&times;</button>
        <h2 id="ya-modal-title">New Automation</h2>
        <input type="hidden" id="ya-field-id" value="0">

        <label for="ya-field-name">Name (for your reference)</label>
        <input type="text" id="ya-field-name" placeholder="e.g. Confirm reminder">

        <label for="ya-field-trigger">When...</label>
        <select id="ya-field-trigger">
            <?php foreach ( $trigger_types as $slug => $meta ) : ?>
                <option value="<?php echo esc_attr( $slug ); ?>"><?php echo esc_html( $meta['label'] ); ?></option>
            <?php endforeach; ?>
        </select>

        <div class="ya-row-2">
            <div id="ya-field-hours-wrap" style="display:none;">
                <label for="ya-field-hours">Hours</label>
                <input type="number" id="ya-field-hours" min="1" max="720" value="24">
            </div>
            <div id="ya-field-status-wrap" style="display:none;">
                <label for="ya-field-status">Status</label>
                <select id="ya-field-status">
                    <?php foreach ( YATOON_Automations::get_status_options() as $slug => $label ) : ?>
                        <option value="<?php echo esc_attr( $slug ); ?>"><?php echo esc_html( $label ); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <label for="ya-field-action">Then...</label>
        <select id="ya-field-action">
            <?php foreach ( $action_types as $slug => $meta ) : ?>
                <option value="<?php echo esc_attr( $slug ); ?>"><?php echo esc_html( $meta['label'] ); ?></option>
            <?php endforeach; ?>
        </select>

        <div id="ya-field-subject-wrap">
            <label for="ya-field-subject">Subject (for emails)</label>
            <input type="text" id="ya-field-subject" placeholder="e.g. Please confirm your appointment">
        </div>

        <label for="ya-field-message">Message</label>
        <textarea id="ya-field-message" placeholder="Hi {customer_first_name}, just checking in about your {service_name} appointment on {date} at {time}..."></textarea>
        <p class="ya-merge-tags">
            Click to insert:
            <?php foreach ( array( '{customer_first_name}', '{service_name}', '{staff_name}', '{date}', '{time}', '{business_name}', '{manage_link}' ) as $tag ) : ?>
                <code class="ya-tag-insert"><?php echo esc_html( $tag ); ?></code>
            <?php endforeach; ?>
        </p>

        <div class="ya-modal-actions">
            <span id="ya-modal-msg" style="font-size:13px;color:#16a34a;"></span>
            <div>
                <button type="button" class="button" id="ya-modal-cancel">Cancel</button>
                <button type="button" class="button button-primary" id="ya-modal-save">Save Automation</button>
            </div>
        </div>
    </div>
</div>

<script>
jQuery(function($) {
    const nonce = '<?php echo esc_js( $nonce ); ?>';
    const triggerMeta = <?php echo wp_json_encode( $trigger_types ); ?>;
    const actionMeta  = <?php echo wp_json_encode( $action_types ); ?>;

    function openModal(rule) {
        $('#ya-field-id').val(rule ? rule.id : 0);
        $('#ya-modal-title').text(rule ? 'Edit Automation' : 'New Automation');
        $('#ya-field-name').val(rule ? rule.name : '');
        $('#ya-field-trigger').val(rule ? rule.trigger_type : 'booking_created');
        $('#ya-field-hours').val(rule && rule.trigger_hours ? rule.trigger_hours : 24);
        $('#ya-field-status').val(rule && rule.trigger_status ? rule.trigger_status : 'confirmed');
        $('#ya-field-action').val(rule ? rule.action_type : 'send_email');
        $('#ya-field-subject').val(rule ? rule.action_subject : '');
        $('#ya-field-message').val(rule ? rule.action_message : '');
        $('#ya-modal-msg').text('');
        syncTriggerFields();
        syncActionFields();
        $('#yatoon-automation-modal-overlay').addClass('is-open');
    }
    function closeModal() { $('#yatoon-automation-modal-overlay').removeClass('is-open'); }

    function syncTriggerFields() {
        const t = triggerMeta[$('#ya-field-trigger').val()] || {};
        $('#ya-field-hours-wrap').toggle(!!t.needs_hours);
        $('#ya-field-status-wrap').toggle(!!t.needs_status);
    }
    function syncActionFields() {
        const a = actionMeta[$('#ya-field-action').val()] || {};
        $('#ya-field-subject-wrap').toggle(a.needs_subject !== false);
    }

    $('#ya-field-trigger').on('change', syncTriggerFields);
    $('#ya-field-action').on('change', syncActionFields);

    $('#ya-add-rule-btn').on('click', function() { openModal(null); });
    $('#yatoon-automation-modal-close, #ya-modal-cancel').on('click', closeModal);
    $('#yatoon-automation-modal-overlay').on('click', function(e) { if (e.target === this) closeModal(); });

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

    $(document).on('click', '.ya-edit-btn', function() {
        const rule = $(this).closest('.ya-rule').data('rule');
        openModal(rule);
    });

    $('#ya-modal-save').on('click', function() {
        const $btn = $(this);
        $btn.prop('disabled', true);
        $.post(ajaxurl, {
            action: 'yatoon_save_automation',
            nonce: nonce,
            id: $('#ya-field-id').val(),
            name: $('#ya-field-name').val(),
            trigger_type: $('#ya-field-trigger').val(),
            trigger_hours: $('#ya-field-hours').val(),
            trigger_status: $('#ya-field-status').val(),
            action_type: $('#ya-field-action').val(),
            action_subject: $('#ya-field-subject').val(),
            action_message: $('#ya-field-message').val(),
        }, function(resp) {
            $btn.prop('disabled', false);
            if (resp.success) {
                location.reload();
            } else {
                $('#ya-modal-msg').css('color', '#dc2626').text((resp.data && resp.data.message) || 'Could not save.');
            }
        });
    });

    $(document).on('change', '.ya-toggle', function() {
        const $rule = $(this).closest('.ya-rule');
        $.post(ajaxurl, {
            action: 'yatoon_toggle_automation',
            nonce: nonce,
            id: $rule.data('rule-id'),
            enabled: this.checked ? 1 : 0,
        }, function(resp) {
            if (resp.success) $rule.toggleClass('is-disabled', !$('.ya-toggle', $rule).is(':checked'));
        });
    });

    $(document).on('click', '.ya-delete-btn', function() {
        if (!confirm('Delete this automation? This cannot be undone.')) return;
        const $rule = $(this).closest('.ya-rule');
        $.post(ajaxurl, {
            action: 'yatoon_delete_automation',
            nonce: nonce,
            id: $rule.data('rule-id'),
        }, function(resp) {
            if (resp.success) $rule.remove();
        });
    });

    $(document).on('click', '.ya-test-btn', function() {
        const $btn = $(this);
        const $rule = $btn.closest('.ya-rule');
        $btn.prop('disabled', true).text('Sending...');
        $.post(ajaxurl, {
            action: 'yatoon_test_automation',
            nonce: nonce,
            id: $rule.data('rule-id'),
        }, function(resp) {
            $btn.prop('disabled', false).text('Test');
            alert((resp.data && resp.data.message) || (resp.success ? 'Sent.' : 'Could not send test.'));
        });
    });

    if ($.fn.sortable) {
        $('#ya-rule-list').sortable({
            handle: '.ya-rule-drag',
            axis: 'y',
            update: function() {
                const order = $('#ya-rule-list .ya-rule').map(function() { return $(this).data('rule-id'); }).get();
                $.post(ajaxurl, { action: 'yatoon_reorder_automations', nonce: nonce, order: order });
            }
        });
    }
});
</script>
