<?php
/**
 * Autopilot — Queue Management.
 * Shows all pending scheduled plays with customer, play name, and scheduled time.
 *
 * @package CartCue
 */
defined('ABSPATH') || exit;

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

global $wpdb;

// Get pending actions from Action Scheduler
$pending = [];
if ( function_exists( 'as_get_scheduled_actions' ) ) {
    $pending = as_get_scheduled_actions( [
        'group'    => 'cartcue',
        'status'   => \ActionScheduler_Store::STATUS_PENDING,
        'per_page' => 100,
        'orderby'  => 'date',
        'order'    => 'ASC',
    ] );
}

$play_names = [];
if ( ! empty( $pending ) ) {
    $workflow_ids = [];
    foreach ( $pending as $action ) {
        $args = $action->get_args();
        $wid  = (int) ( $args[0] ?? 0 );
        if ( $wid > 0 ) {
            $workflow_ids[] = $wid;
        }
    }
    $workflow_ids = array_unique( $workflow_ids );
    if ( $workflow_ids ) {
        $workflow_ids = array_values( array_map( 'absint', $workflow_ids ) );
        $in_placeholders = implode( ',', array_fill( 0, count( $workflow_ids ), '%d' ) );
        // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
        $rows            = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT id, name FROM %i WHERE id IN ($in_placeholders)",
                array_merge( [ \CartCue\DB::workflows() ], $workflow_ids )
            ),
            ARRAY_A
        ) ?: [];
        // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
        foreach ( $rows as $row ) {
            $play_names[ (int) $row['id'] ] = (string) $row['name'];
        }
    }
}
?>
<div class="ap-wrap">
    <div class="ap-page-header">
        <div>
            <h1 class="ap-page-title"><?php esc_html_e('Automation queue', 'cartcue-sales-automation'); ?></h1>
            <p class="ap-page-sub"><?php
            printf(
                /* translators: %d: number of scheduled automations */
                esc_html__( '%d automations scheduled to run. These fire automatically at the shown time.', 'cartcue-sales-automation' ),
                esc_html( (string) count( $pending ) )
            );
            ?></p>
        </div>
    </div>

    <?php if (empty($pending)) : ?>
    <div class="ap-empty-state">
        <div class="ap-empty-icon">✓</div>
        <h2><?php esc_html_e('Queue is empty', 'cartcue-sales-automation'); ?></h2>
        <p><?php esc_html_e('No automations are scheduled right now. Delayed automations will appear here after they are triggered.', 'cartcue-sales-automation'); ?></p>
    </div>
    <?php else : ?>
    <table class="wp-list-table widefat fixed striped">
        <thead>
            <tr>
                <th><?php esc_html_e('Scheduled time', 'cartcue-sales-automation'); ?></th>
                <th><?php esc_html_e('Hook / Automation', 'cartcue-sales-automation'); ?></th>
                <th><?php esc_html_e('Customer', 'cartcue-sales-automation'); ?></th>
                <th><?php esc_html_e('Actions', 'cartcue-sales-automation'); ?></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($pending as $action_id => $action) :
            $action_id   = (int) $action_id;
            $args        = $action->get_args();
            $hook        = $action->get_hook();
            $schedule    = $action->get_schedule();
            $next        = $schedule ? $schedule->get_date() : null;
            $time_str    = $next ? $next->format('Y-m-d H:i:s') : '—';
            $workflow_id = (int)($args[0] ?? 0);
            $data        = $args[1] ?? [];
            $email       = $data['customer_email'] ?? '—';
            $play_name   = $workflow_id ? ( $play_names[ $workflow_id ] ?? '' ) : '';
            if ( '' === $play_name ) {
                $play_name = '—';
            }
            ?>
            <tr>
                <td style="white-space:nowrap"><?php echo esc_html($time_str); ?></td>
                <td>
                    <?php if ($play_name && $play_name !== '—') :
                        $edit_url = add_query_arg(['page' => 'cartcue', 'action' => 'edit', 'id' => $workflow_id], admin_url('admin.php')); ?>
                        <a href="<?php echo esc_url($edit_url); ?>"><?php echo esc_html($play_name); ?></a>
                    <?php else : ?>
                        <code style="font-size:11px"><?php echo esc_html($hook); ?></code>
                    <?php endif; ?>
                </td>
                <td><?php echo esc_html($email); ?></td>
                <td>
                    <?php
                    $cancel = wp_nonce_url(
                        add_query_arg(
                            [
                                'action'    => 'cartcue_cancel_queue_item',
                                'action_id' => $action_id,
                            ],
                            admin_url('admin-post.php')
                        ),
                        'cartcue_cancel_queue'
                    );
                    ?>
                    <a href="<?php echo esc_url($cancel); ?>" class="button button-small" onclick="return confirm('<?php echo esc_js(__('Cancel this queued automation?', 'cartcue-sales-automation')); ?>')">
                        <?php esc_html_e('Cancel', 'cartcue-sales-automation'); ?>
                    </a>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>
</div>
