<?php
/**
 * Autopilot — Campaign Mode.
 * Select a play with the Manual trigger and run it on a customer segment now.
 *
 * @package CartCue
 */
defined('ABSPATH') || exit;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- template scope.

global $wpdb;

use CartCue\CampaignSegments;

// Fetch manual-trigger plays only
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$plays = $wpdb->get_results(
    $wpdb->prepare(
        'SELECT id, name FROM %i WHERE trigger_slug = %s AND status = %s ORDER BY name ASC',
        \CartCue\DB::workflows(),
        'manual',
        'active'
    ),
    ARRAY_A
) ?: [];

$segment_labels = CampaignSegments::labels();
$payment_methods = [];
if ( function_exists( 'WC' ) && WC()->payment_gateways() ) {
    foreach ( WC()->payment_gateways()->payment_gateways() as $id => $gateway ) {
        if ( 'yes' === $gateway->enabled ) {
            $payment_methods[ $id ] = $gateway->get_title();
        }
    }
}

$sent_count    = isset( $_GET['ap_sent'] ) ? absint( wp_unslash( $_GET['ap_sent'] ) ) : ( isset( $_GET['campaign_count'] ) ? absint( wp_unslash( $_GET['campaign_count'] ) ) : 0 ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- admin notice query args only.
$skipped_count = isset( $_GET['ap_skipped'] ) ? absint( wp_unslash( $_GET['ap_skipped'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- admin notice query args only.
$result        = isset( $_GET['ap_sent'] ) ? 'sent' : sanitize_key( wp_unslash( $_GET['campaign_result'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- admin notice query args only.
?>
<div class="ap-wrap">
    <div class="ap-page-header">
        <div>
            <h1 class="ap-page-title"><?php esc_html_e('Send now (manual)', 'cartcue-sales-automation'); ?></h1>
            <p class="ap-page-sub"><?php esc_html_e('Run an automation on a group of customers right now. Use Marketing opt-in to include guest subscribers without a store account. Only Manual-trigger automations appear here.', 'cartcue-sales-automation'); ?></p>
        </div>
    </div>

    <?php if ('sent' === $result) : ?>
    <div class="notice notice-success is-dismissible">
        <p>
            <?php
            if ( $skipped_count > 0 ) {
                printf(
                    /* translators: 1: number of recipients, 2: number skipped */
                    esc_html__( 'Campaign started for %1$d recipients (%2$d skipped — no consent or unsubscribed).', 'cartcue-sales-automation' ),
                    esc_html( (string) $sent_count ),
                    esc_html( (string) $skipped_count )
                );
            } else {
                printf(
                    /* translators: %d: number of recipients */
                    esc_html__( 'Campaign started: automation queued for %d recipients.', 'cartcue-sales-automation' ),
                    esc_html( (string) $sent_count )
                );
            }
            ?>
        </p>
    </div>
    <?php endif; ?>

    <?php if (empty($plays)) : ?>
    <div class="ap-empty-state">
        <div class="ap-empty-icon">🎯</div>
        <h2><?php esc_html_e('No campaign automations yet', 'cartcue-sales-automation'); ?></h2>
        <p><?php esc_html_e('Create an automation using the "Manual" trigger to send to a segment from this page.', 'cartcue-sales-automation'); ?></p>
        <a href="<?php echo esc_url( add_query_arg( [ 'page' => 'cartcue-recipes' ], admin_url( 'admin.php' ) ) ); ?>" class="ap-btn ap-btn-primary">
            <?php esc_html_e('Create an automation →', 'cartcue-sales-automation'); ?>
        </a>
    </div>
    <?php else : ?>
    <div class="ap-card" style="max-width:640px">
        <div class="ap-card__header"><?php esc_html_e('Configure and launch campaign', 'cartcue-sales-automation'); ?></div>
        <div class="ap-card__body">
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" id="ap-campaign-form">
                <?php wp_nonce_field('cartcue_run_campaign'); ?>
                <input type="hidden" name="action" value="cartcue_run_campaign">

                <div class="ap-field-row">
                    <label class="ap-field-label"><?php esc_html_e('Automation to run', 'cartcue-sales-automation'); ?></label>
                    <select name="play_id" class="ap-select" required>
                        <option value="">— <?php esc_html_e('Select an automation', 'cartcue-sales-automation'); ?> —</option>
                        <?php foreach ($plays as $p) : ?>
                        <option value="<?php echo esc_attr($p['id']); ?>"><?php echo esc_html($p['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="ap-field-row">
                    <label class="ap-field-label"><?php esc_html_e('Customer segment', 'cartcue-sales-automation'); ?></label>
                    <select name="segment" class="ap-select" id="ap-campaign-segment">
                        <?php foreach ( $segment_labels as $slug => $label ) : ?>
                        <option value="<?php echo esc_attr( $slug ); ?>"><?php echo esc_html( $label ); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description" id="ap-segment-count" style="margin-top:8px"></p>
                    <p class="description ap-segment-hint" data-segment="marketing_opt_in" hidden style="margin-top:4px">
                        <?php esc_html_e( 'Includes registered customers and guest emails stored in your opt-in list. Unsubscribed addresses are excluded.', 'cartcue-sales-automation' ); ?>
                    </p>
                </div>

                <div class="ap-field-row ap-segment-param" data-segment="payment_method" hidden>
                    <label class="ap-field-label"><?php esc_html_e('Payment method', 'cartcue-sales-automation'); ?></label>
                    <select name="payment_method" class="ap-select">
                        <option value=""><?php esc_html_e('— Select —', 'cartcue-sales-automation'); ?></option>
                        <?php foreach ( $payment_methods as $id => $title ) : ?>
                        <option value="<?php echo esc_attr( $id ); ?>"><?php echo esc_html( $title ); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="ap-field-row ap-segment-param" data-segment="used_coupon" hidden>
                    <label class="ap-field-label"><?php esc_html_e('Coupon code', 'cartcue-sales-automation'); ?></label>
                    <input type="text" name="coupon_code" class="ap-input" placeholder="<?php esc_attr_e( 'SUMMER10', 'cartcue-sales-automation' ); ?>">
                </div>

                <div class="ap-field-row ap-segment-param" data-segment="email_inactive" hidden>
                    <label class="ap-field-label"><?php esc_html_e('No email opens in (days)', 'cartcue-sales-automation'); ?></label>
                    <input type="number" name="email_inactive_days" class="ap-input ap-input--tiny" value="90" min="1" style="width:80px">
                </div>

                <div class="ap-field-row">
                    <label class="ap-field-label"><?php esc_html_e('Limit (0 = no limit)', 'cartcue-sales-automation'); ?></label>
                    <input type="number" name="limit" class="ap-input ap-input--tiny" value="0" min="0" style="width:80px">
                    <span style="font-size:12px;color:#888;margin-left:8px"><?php esc_html_e('recipients maximum (0 = up to 5,000)', 'cartcue-sales-automation'); ?></span>
                </div>

                <button type="submit" class="ap-btn ap-btn-primary" id="ap-campaign-submit">
                    <?php esc_html_e('Send now →', 'cartcue-sales-automation'); ?>
                </button>
            </form>
        </div>
    </div>

    <script>
    jQuery(function($){
        var countNonce = '<?php echo esc_js( wp_create_nonce( 'cartcue_campaign_count' ) ); ?>';

        function segmentParams() {
            return {
                payment_method: $('select[name="payment_method"]').val() || '',
                coupon_code: $('input[name="coupon_code"]').val() || '',
                email_inactive_days: $('input[name="email_inactive_days"]').val() || 90
            };
        }

        var confirmDefault = <?php echo wp_json_encode( __( 'This will fire the selected automation for each matching recipient. Continue?', 'cartcue-sales-automation' ) ); ?>;
        var confirmOptIn = <?php echo wp_json_encode( __( 'Send to everyone in your marketing opt-in list (including guests)? Only contacts with consent will receive email.', 'cartcue-sales-automation' ) ); ?>;

        function toggleSegmentParams() {
            var seg = $('#ap-campaign-segment').val();
            $('.ap-segment-param').each(function(){
                $(this).prop('hidden', $(this).data('segment') !== seg);
            });
            $('.ap-segment-hint').each(function(){
                $(this).toggle($(this).data('segment') === seg);
            });
        }

        function refreshCount() {
            var seg = $('#ap-campaign-segment').val();
            var params = segmentParams();
            $('#ap-segment-count').text('<?php echo esc_js( __( 'Counting…', 'cartcue-sales-automation' ) ); ?>');
            $.post(ajaxurl, $.extend({
                action: 'cartcue_campaign_count',
                segment: seg,
                limit: 0,
                nonce: countNonce
            }, params), function(r){
                if (!r.success || !r.data) {
                    $('#ap-segment-count').text('');
                    return;
                }
                var d = r.data;
                var count = typeof d === 'object' ? (d.count || 0) : d;
                var line = count + ' <?php echo esc_js( __( 'recipients in this segment', 'cartcue-sales-automation' ) ); ?>';
                if (typeof d === 'object' && seg === 'marketing_opt_in') {
                    line += ' (' + (d.registered || 0) + ' <?php echo esc_js( __( 'registered', 'cartcue-sales-automation' ) ); ?>, ' + (d.guests || 0) + ' <?php echo esc_js( __( 'guests', 'cartcue-sales-automation' ) ); ?>)';
                }
                $('#ap-segment-count').text(line);
            });
        }

        $('#ap-campaign-segment').on('change', function(){
            toggleSegmentParams();
            refreshCount();
        });
        $('select[name="payment_method"], input[name="coupon_code"], input[name="email_inactive_days"]').on('change input', refreshCount);

        $('#ap-campaign-submit').on('click', function(e){
            var seg = $('#ap-campaign-segment').val();
            var msg = seg === 'marketing_opt_in' ? confirmOptIn : confirmDefault;
            if (!window.confirm(msg)) {
                e.preventDefault();
            }
        });

        toggleSegmentParams();
        refreshCount();
    });
    </script>
    <?php endif; ?>
</div>
