<?php
/**
 * Execution logs table (embedded in Reports).
 *
 * @var \CartCue\Plugin $plugin
 * @package CartCue
 */
defined( 'ABSPATH' ) || exit;

/* phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound */

global $wpdb;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- admin log filter UI.
$filter_status = isset( $_GET['status'] ) ? sanitize_key( wp_unslash( $_GET['status'] ) ) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- admin log filter UI.
$filter_play   = isset( $_GET['play_id'] ) ? absint( wp_unslash( $_GET['play_id'] ) ) : 0;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- admin log filter UI.
$filter_from   = isset( $_GET['date_from'] ) ? sanitize_text_field( wp_unslash( $_GET['date_from'] ) ) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- admin log filter UI.
$filter_to     = isset( $_GET['date_to'] ) ? sanitize_text_field( wp_unslash( $_GET['date_to'] ) ) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- admin log pagination.
$current_page  = isset( $_GET['paged'] ) ? max( 1, absint( wp_unslash( $_GET['paged'] ) ) ) : 1;
$per_page      = 50;
$offset        = ( $current_page - 1 ) * $per_page;

$args  = [
	'status'      => $filter_status,
	'workflow_id' => $filter_play,
	'date_from'   => $filter_from,
	'date_to'     => $filter_to,
	'limit'       => $per_page,
	'offset'      => $offset,
];
$logs  = $plugin->logger->get_logs( $args );
$total = $plugin->logger->count_logs( $args );
$pages = (int) ceil( $total / $per_page );
$has_active_filters = '' !== $filter_status || 0 !== $filter_play || '' !== $filter_from || '' !== $filter_to;

$logs_base = add_query_arg( [ 'page' => 'cartcue-reports', 'tab' => 'logs' ], admin_url( 'admin.php' ) );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$all_plays = $wpdb->get_results(
	$wpdb->prepare( 'SELECT id, name FROM %i ORDER BY name ASC', \CartCue\DB::workflows() ),
	ARRAY_A
) ?: [];
?>
<ul class="subsubsub">
	<?php foreach ( [ '' => __( 'All', 'cartcue-sales-automation' ), 'success' => __( 'Success', 'cartcue-sales-automation' ), 'skipped' => __( 'Skipped', 'cartcue-sales-automation' ), 'error' => __( 'Error', 'cartcue-sales-automation' ) ] as $sk => $sl ) :
		$url = add_query_arg( [ 'status' => $sk, 'play_id' => $filter_play ?: null, 'date_from' => $filter_from ?: null, 'date_to' => $filter_to ?: null ], $logs_base );
		printf( '<li><a href="%s"%s>%s</a> | </li>', esc_url( $url ), $filter_status === $sk ? ' class="current"' : '', esc_html( $sl ) );
	endforeach; ?>
</ul>

<form method="get" class="ap-logs-filter">
	<input type="hidden" name="page" value="cartcue-reports">
	<input type="hidden" name="tab" value="logs">
	<?php if ( $filter_status ) : ?>
	<input type="hidden" name="status" value="<?php echo esc_attr( $filter_status ); ?>">
	<?php endif; ?>
	<select name="play_id" class="ap-select">
		<option value="0"><?php esc_html_e( 'All automations', 'cartcue-sales-automation' ); ?></option>
		<?php foreach ( $all_plays as $play_row ) : ?>
		<option value="<?php echo esc_attr( $play_row['id'] ); ?>" <?php selected( $filter_play, (int) $play_row['id'] ); ?>>
			<?php echo esc_html( $play_row['name'] ); ?>
		</option>
		<?php endforeach; ?>
	</select>
	<input type="date" name="date_from" value="<?php echo esc_attr( $filter_from ); ?>" class="ap-input" aria-label="<?php esc_attr_e( 'From date', 'cartcue-sales-automation' ); ?>">
	<input type="date" name="date_to" value="<?php echo esc_attr( $filter_to ); ?>" class="ap-input" aria-label="<?php esc_attr_e( 'To date', 'cartcue-sales-automation' ); ?>">
	<button type="submit" class="ap-btn ap-btn-sm"><?php esc_html_e( 'Filter logs', 'cartcue-sales-automation' ); ?></button>
</form>

<table class="wp-list-table widefat fixed striped ap-logs-table">
	<thead>
		<tr>
			<th><?php esc_html_e( 'Date', 'cartcue-sales-automation' ); ?></th>
			<th><?php esc_html_e( 'Automation', 'cartcue-sales-automation' ); ?></th>
			<th><?php esc_html_e( 'Trigger', 'cartcue-sales-automation' ); ?></th>
			<th><?php esc_html_e( 'Customer', 'cartcue-sales-automation' ); ?></th>
			<th><?php esc_html_e( 'Result', 'cartcue-sales-automation' ); ?></th>
			<th><?php esc_html_e( 'Detail', 'cartcue-sales-automation' ); ?></th>
		</tr>
	</thead>
	<tbody>
		<?php if ( empty( $logs ) ) : ?>
		<tr>
			<td colspan="6" class="ap-logs-empty">
				<?php
				echo $has_active_filters
					? esc_html__( 'No activity matches your current filters.', 'cartcue-sales-automation' )
					: esc_html__( 'No activity yet. New automation runs will appear here.', 'cartcue-sales-automation' );
				?>
			</td>
		</tr>
		<?php else : foreach ( $logs as $log ) :
			$trigger = $plugin->get_trigger( $log['trigger_slug'] ); ?>
		<tr>
			<td><?php echo esc_html( mysql2date( get_option( 'date_format' ) . ' H:i', $log['created_at'] ) ); ?></td>
			<td><?php echo esc_html( $log['workflow_name'] ); ?></td>
			<td><?php echo $trigger ? esc_html( $trigger->get_label() ) : esc_html( $log['trigger_slug'] ); ?></td>
			<td><?php echo esc_html( $log['customer_email'] ); ?></td>
			<td><span class="ap-badge ap-badge--<?php echo esc_attr( $log['status'] ); ?>"><?php echo esc_html( ucfirst( $log['status'] ) ); ?></span></td>
			<td class="ap-log-detail"><?php echo esc_html( $log['message'] ); ?></td>
		</tr>
		<?php endforeach; endif; ?>
	</tbody>
</table>
<?php
if ( $pages > 1 ) {
	echo wp_kses_post(
		paginate_links(
			[
				'base'    => add_query_arg( 'paged', '%#%', $logs_base ),
				'format'  => '',
				'current' => $current_page,
				'total'   => $pages,
			]
		)
	);
}

/* phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound */
