<?php
/**
 * Admin: Payout Batches Subpage
 *
 * Renders the Batches tab of the Payouts page. The batches list is the only
 * content — batch detail is a drawer, deep-linked via `?batch_id=N`. The JS
 * in `affwp-batch-drawer.js` reads the URL on init and opens the drawer.
 *
 * Direct-URL access to `?tab=batches&batch_id=N` therefore still works
 * end-to-end: the list renders, the drawer opens over it, and sharing that
 * URL reproduces the same state on load.
 *
 * @package     AffiliateWP
 * @subpackage  Admin/Payouts
 * @copyright   Copyright (c) 2026, Sandhills Development, LLC
 * @license     http://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       2.33.0
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/*
 * The batch drawer mirrors ?batch_id=X into the URL (and the payout drawer,
 * reachable from a batch, mirrors ?payout_id=X). WP_List_Table builds pagination
 * and sortable-column links from $_SERVER['REQUEST_URI'], so those params would
 * otherwise leak into every page/sort link and re-open the same drawer on each
 * navigation. Strip them before the table renders; both drawers read their id
 * client-side from the address bar, so deep-linking is unaffected.
 */
if ( ! empty( $_SERVER['REQUEST_URI'] ) && ( isset( $_GET['batch_id'] ) || isset( $_GET['payout_id'] ) ) ) {
	$_SERVER['REQUEST_URI'] = remove_query_arg( array( 'batch_id', 'payout_id' ), $_SERVER['REQUEST_URI'] );
}

$batches_table = new AffWP_Payout_Batches_Table();
$batches_table->prepare_items();

/*
 * Empty-state detection: zero batches *ever*, not just zero in the current
 * filtered view. When a status filter is active (e.g. `?status=failed`), let
 * the list table's normal "no items" row render — "no failed batches" is a
 * filter result, not a first-run empty state.
 */
$is_filtered_view = ! empty( $_GET['status'] ) || ! empty( $_GET['s'] );

// Empty state is driven by the batch count, not by the active filter.
$counts           = affwp_payouts_overview_counts( array( 'batches' => (int) ( $batches_table->total_count ?? 0 ) ) );
$show_empty_state = (int) $counts['batches'] < 1 && ! $is_filtered_view;

/**
 * Renders a preview card of two sample batch rows for the empty state.
 *
 * Shows one Stripe Connect completed batch and one Mixed (per-affiliate
 * routing) batch still processing, so the illustration demonstrates two
 * distinctive batch traits at once: status variety + method routing.
 * "Mixed" specifically hints that per-affiliate methods exist without
 * needing to spell that out in copy.
 *
 * Hard-coded demo data so it works on a fresh install. Aria-hidden because
 * it's purely decorative; the surrounding empty-state copy carries the
 * meaning for assistive tech.
 *
 * @since 2.33.0
 */
function affwp_payout_batches_render_ghost_rows_card() {

	$rows = array(
		array(
			'id'     => 142,
			'status' => 'completed',
			'method' => __( 'Stripe Connect', 'affiliate-wp' ),
			'amount' => '$1,247.50',
			'count'  => 8,
		),
		array(
			'id'     => 141,
			'status' => 'processing',
			'method' => __( 'Mixed', 'affiliate-wp' ),
			'amount' => '$642.30',
			'count'  => 5,
		),
	);

	$last = count( $rows ) - 1;
	?>
	<div class="mx-auto max-w-xl mt-8 rounded-2xl bg-white shadow-sm text-left overflow-hidden mask-[linear-gradient(to_right,black_70%,transparent_100%)]" aria-hidden="true">
		<?php foreach ( $rows as $i => $row ) : ?>
			<div class="flex items-center gap-4 px-5 py-4 <?php echo $i === $last ? '' : 'border-b border-gray-100'; ?>">
				<p class="font-semibold text-gray-900 tabular-nums m-0 shrink-0 w-16">#<?php echo (int) $row['id']; ?></p>
				<span class="shrink-0">
					<?php echo affwp_get_payout_status_badge( $row['status'] ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- helper returns trusted HTML. ?>
				</span>
				<p class="text-gray-700 m-0 ml-auto tabular-nums whitespace-nowrap">
					<?php echo esc_html( $row['method'] ); ?>
					<span class="text-gray-400">·</span>
					<?php echo esc_html( $row['amount'] ); ?>
					<span class="text-gray-400">·</span>
					<?php echo esc_html( sprintf( '%d affiliates', (int) $row['count'] ) ); ?>
				</p>
			</div>
		<?php endforeach; ?>
	</div>
	<?php
}
?>
<div class="wrap">

	<h1>
		<?php esc_html_e( 'Payouts', 'affiliate-wp' ); ?>
		<?php echo affwp_admin_link( 'reports', _x( 'Reports', 'payouts', 'affiliate-wp' ), [ 'tab' => 'payouts' ], [ 'class' => 'button action button-small' ] ); ?>
		<?php echo affwp_admin_link( 'referrals', __( 'Manage Referrals', 'affiliate-wp' ), [], [ 'class' => 'button action button-small' ] ); ?>
		<?php if ( current_user_can( 'manage_payouts' ) ) : ?>
			<a href="<?php echo esc_url( affwp_admin_url( 'payouts', [ 'action' => 'new_payout' ] ) ); ?>" class="button action button-primary button-small"><?php esc_html_e( 'Pay Affiliates', 'affiliate-wp' ); ?></a>
		<?php endif; ?>
	</h1>

	<?php affwp_payouts_render_tabs( 'batches' ); ?>

	<?php if ( $show_empty_state ) : ?>

		<div class="min-h-[60vh] flex items-center justify-center">
			<div class="w-full">
				<?php
				affwp_list_page_empty_state(
					array(
						'title'       => __( 'No payout batches yet', 'affiliate-wp' ),
						'title_class' => 'text-4xl font-semibold text-gray-900 m-0 tracking-tight',
						'description' => __( 'Every time you pay affiliates, AffiliateWP groups the payouts into a single batch you can reconcile, retry failures, and audit.', 'affiliate-wp' ),
						'content'     => 'affwp_payout_batches_render_ghost_rows_card',
						'button_text' => current_user_can( 'manage_payouts' ) ? __( 'Pay Affiliates', 'affiliate-wp' ) : '',
						'button_url'  => current_user_can( 'manage_payouts' ) ? affwp_admin_url( 'payouts', array( 'action' => 'new_payout' ) ) : '',
						'footer'      => sprintf(
							/* translators: %s: link to the individual payouts list */
							__( 'Looking for a specific payout? %s.', 'affiliate-wp' ),
							sprintf(
								'<a href="%s" class="text-affwp-link hover:text-affwp-link-hover">%s</a>',
								esc_url( affwp_admin_url( 'payouts' ) ),
								esc_html__( 'View individual payouts', 'affiliate-wp' )
							)
						),
					)
				);
				?>
			</div>
		</div>

	<?php else : ?>

		<form id="affwp-payout-batches-filter" method="get" action="<?php echo esc_url( affwp_admin_url( 'payouts', [ 'tab' => 'batches' ] ) ); ?>">
			<input type="hidden" name="page" value="affiliate-wp-payouts" />
			<input type="hidden" name="tab" value="batches" />

			<?php $batches_table->search_box( __( 'Search batches', 'affiliate-wp' ), 'affwp-batches' ); ?>

			<?php $batches_table->views(); ?>
			<?php $batches_table->display(); ?>
		</form>

	<?php endif; ?>

</div>

<?php
/*
 * Batch drawer — auto-opens when URL carries `?batch_id=X`.
 * Row-click intercept is in affwp-batch-drawer.js.
 */
affwp_render_batch_drawer();

/*
 * Payout drawer also gets rendered here so clicking a payout inside the
 * batch drawer can open it (single-drawer invariant: batch closes, payout
 * opens — both drawers coexist in the DOM, only one is visible at a time).
 */
affwp_render_payout_drawer();

/*
 * Post-submit toast. When the batch process action redirects here it appends
 * `affwp_notice=batch_submitted`; we acknowledge the action via the existing
 * affwpToast helper (no dedicated success page needed) and scrub the notice
 * param from the URL so a refresh doesn't re-fire the toast.
 */
if ( isset( $_REQUEST['affwp_notice'] ) && 'batch_submitted' === $_REQUEST['affwp_notice'] ) :
	$_toast_batch_id = isset( $_REQUEST['batch_id'] ) ? absint( $_REQUEST['batch_id'] ) : 0;
	?>
	<script>
		( function () {
			var fire = function () {
				if ( ! window.affwpToast ) {
					return;
				}
				window.affwpToast( {
					message: <?php echo wp_json_encode( sprintf( __( 'Batch #%d submitted', 'affiliate-wp' ), $_toast_batch_id ) ); ?>,
					type: 'success'
				} );
				// Scrub the notice from the URL so a refresh doesn't re-toast.
				try {
					var url = new URL( window.location.href );
					url.searchParams.delete( 'affwp_notice' );
					window.history.replaceState( {}, '', url.toString() );
				} catch ( e ) { /* History API unavailable — leave the URL alone. */ }
			};
			if ( document.readyState === 'loading' ) {
				document.addEventListener( 'DOMContentLoaded', fire );
			} else {
				fire();
			}
		} )();
	</script>
<?php endif;
