<?php
/**
 * Ingredients list admin view.
 *
 * @package RestaurantCosting
 * @var array<int, object> $items
 * @var int                $total
 * @var int                $page
 * @var int                $limit
 * @var string             $search
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Recover parameters for the form
$per_page = isset( $_GET['per_page'] ) ? (int) $_GET['per_page'] : ( isset( $_COOKIE['rc_pp_ingredients'] ) ? (int) $_COOKIE['rc_pp_ingredients'] : 25 );
$search   = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
$f_type   = isset( $_GET['f_type'] ) ? sanitize_text_field( $_GET['f_type'] ) : '';
$f_sup    = isset( $_GET['f_supplier'] ) ? sanitize_text_field( $_GET['f_supplier'] ) : '';
$orderby  = isset( $_GET['orderby'] ) ? sanitize_text_field( $_GET['orderby'] ) : 'name';
$order    = isset( $_GET['order'] ) ? sanitize_text_field( $_GET['order'] ) : 'ASC';
$show_inactive = ! empty( $_GET['show_inactive'] );

// Build a base URL with all current filter params (no paged) for sort links
$current_base = add_query_arg(
	array(
		'page'     => 'restaurant-costing-ingredients',
		's'        => $search,
		'f_type'   => $f_type,
		'f_supplier'=> $f_sup,
		'show_inactive' => $show_inactive ? 1 : false,
		'per_page' => $per_page,
	),
	admin_url( 'admin.php' )
);
?>
<div class="wrap">
	<h1 class="wp-heading-inline"><?php esc_html_e( 'Restaurant Costing - Ingredients', 'restaurant-costing' ); ?></h1>
	<div class="rc-version">v<?php echo esc_html( RC_VERSION ); ?></div>
	<button type="button" class="page-title-action rc-open-ingredient-modal"><?php esc_html_e( 'Add Ingredient', 'restaurant-costing' ); ?></button>
	<span class="subtitle"><?php printf( esc_html__( 'Showing %1$d of %2$d', 'restaurant-costing' ), (int) $total, (int) $total_all ); ?></span>
	<hr class="wp-header-end">

	<div class="rc-filter-bar">
		<strong class="rc-block rc-mb-8"><?php esc_html_e( 'Filters', 'restaurant-costing' ); ?></strong>
		<form method="get" class="rc-filter-form">
			<input type="hidden" name="page" value="restaurant-costing-ingredients" />

			<input type="search" name="s" placeholder="<?php esc_attr_e( 'Food name...', 'restaurant-costing' ); ?>" value="<?php echo esc_attr( $search ); ?>" class="rc-w-200" />

			<select name="f_type" class="rc-w-150">
				<option value=""><?php esc_html_e( 'All Product Types', 'restaurant-costing' ); ?></option>
				<?php foreach ( RC_Ingredient_Repository::food_type_options() as $type ) : ?>
					<option value="<?php echo esc_attr( $type ); ?>" <?php selected( $f_type, $type ); ?>><?php echo esc_html( $type ); ?></option>
				<?php endforeach; ?>
			</select>

			<select name="f_supplier" class="rc-w-180">
				<option value=""><?php esc_html_e( 'All Suppliers', 'restaurant-costing' ); ?></option>
				<?php foreach ( RC_Supplier_Repository::get_all() as $sup ) : ?>
					<option value="<?php echo esc_attr( $sup->business_name ); ?>" <?php selected( $f_sup, $sup->business_name ); ?>><?php echo esc_html( $sup->business_name ); ?></option>
				<?php endforeach; ?>
			</select>

			<?php // Spacer to push buttons to the right ?>
			<div class="rc-filter-spacer"></div>

			<label class="rc-filter-label">
				<span><?php esc_html_e( 'Show', 'restaurant-costing' ); ?></span>
				<select name="per_page" onchange="this.form.submit()">
					<option value="25" <?php selected( $per_page, 25 ); ?>>25</option>
					<option value="50" <?php selected( $per_page, 50 ); ?>>50</option>
					<option value="100" <?php selected( $per_page, 100 ); ?>>100</option>
					<option value="-1" <?php selected( $per_page, -1 ); ?>><?php esc_html_e( 'All', 'restaurant-costing' ); ?></option>
				</select>
			</label>

			<input type="submit" class="button button-primary" value="<?php esc_attr_e( 'Filter', 'restaurant-costing' ); ?>" />
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=restaurant-costing-ingredients' ) ); ?>" class="button"><?php esc_html_e( 'Reset', 'restaurant-costing' ); ?></a>
		</form>
	</div>

	<div class="rc-inventory-summary">
		<label><input type="checkbox" id="rc-show-inactive-ingredients" <?php checked( $show_inactive ); ?> onchange="window.location.href='admin.php?page=restaurant-costing-ingredients&show_inactive=' + (this.checked ? 1 : 0)" /> <?php esc_html_e( 'Show Inactive', 'restaurant-costing' ); ?></label>
	</div>

	<table class="wp-list-table widefat fixed striped rc-ingredients-table rc-table-rounded">
		<colgroup>
			<col class="rc-col-ingredient" />
			<col class="rc-col-type" />
			<col class="rc-col-size" />
			<col class="rc-col-cost" />
			<col class="rc-col-sub-recipe" />
			<col class="rc-col-actions" />
		</colgroup>
		<thead>
			<tr>
				<th class="rc-col-ingredient">
					<?php
					$dir = ( $orderby === 'name' ) ? ( $order === 'ASC' ? 'desc' : 'asc' ) : 'asc';
					$label = ( $orderby === 'name' ) ? ( $order === 'ASC' ? ' ↓' : ' ↑' ) : '';
					printf( '<a href="%s">%s%s</a>',
						esc_url( add_query_arg( array( 'orderby' => 'name', 'order' => $dir, 'paged' => false ), $current_base ) ),
						esc_html__( 'Ingredient', 'restaurant-costing' ),
						$label
					);
					?>
				</th>
				<th class="rc-col-type">
					<?php
					$dir = ( $orderby === 'food_type' ) ? ( $order === 'ASC' ? 'desc' : 'asc' ) : 'asc';
					$label = ( $orderby === 'food_type' ) ? ( $order === 'ASC' ? ' ↓' : ' ↑' ) : '';
					printf( '<a href="%s">%s%s</a>',
						esc_url( add_query_arg( array( 'orderby' => 'food_type', 'order' => $dir, 'paged' => false ), $current_base ) ),
						esc_html__( 'Product Type', 'restaurant-costing' ),
						$label
					);
					?>
				</th>
				<th class="rc-col-size"><?php esc_html_e( 'Product Size', 'restaurant-costing' ); ?></th>
				<th class="rc-col-cost"><?php esc_html_e( 'Food cost', 'restaurant-costing' ); ?></th>
				<th class="rc-col-sub-recipe"><?php esc_html_e( 'Sub Recipe', 'restaurant-costing' ); ?></th>
				<th class="rc-col-actions"><?php esc_html_e( 'Actions', 'restaurant-costing' ); ?></th>
			</tr>
		</thead>
		<tbody>
			<?php if ( empty( $items ) ) : ?>
				<tr><td colspan="6"><?php esc_html_e( 'No ingredients found.', 'restaurant-costing' ); ?></td></tr>
			<?php else :
				$item_keys = array_keys( $items );
				$item_count = count( $items );
			?>
				<?php foreach ( $items as $idx => $item ) :
					$prev_id = $idx > 0 ? (int) $items[ $item_keys[ $idx - 1 ] ]->id : 0;
					$next_id = $idx < $item_count - 1 ? (int) $items[ $item_keys[ $idx + 1 ] ]->id : 0;
					$inactive = isset( $item->is_active ) && (int) $item->is_active === 0;
				?>
					<tr class="<?php echo $inactive ? 'rc-row-inactive' : ''; ?>">
						<td class="rc-col-ingredient">
							<a href="#" class="rc-edit-ingredient" data-id="<?php echo (int) $item->id; ?>" data-prev-id="<?php echo $prev_id; ?>" data-next-id="<?php echo $next_id; ?>">
								<strong><?php echo esc_html( (string) ( $item->name ?? '' ) ); ?></strong>
							</a>
						</td>
						<td class="rc-col-type"><?php echo esc_html( (string) ( $item->food_type ?? '' ) ); ?></td>
						<td class="rc-col-size"><?php echo esc_html( (string) ( $item->size_label ?? '' ) ); ?></td>
						<td class="rc-col-cost"><?php echo esc_html( '$' . number_format( (float) ( $item->food_cost ?? 0 ), 2 ) ); ?></td>
						<td class="rc-col-sub-recipe">
							<?php if ( (int) ( $item->is_recipe ?? 0 ) === 1 ) : ?>
								<span class="rc-sub-recipe-mark" aria-label="<?php esc_attr_e( 'Sub-recipe', 'restaurant-costing' ); ?>">&#10003;</span>
							<?php endif; ?>
						</td>
						<td class="rc-actions-cell">
							<a href="#" class="button rc-action-btn rc-edit-ingredient" data-id="<?php echo (int) $item->id; ?>" data-prev-id="<?php echo $prev_id; ?>" data-next-id="<?php echo $next_id; ?>"><?php esc_html_e( 'Edit', 'restaurant-costing' ); ?></a>
						</td>
					</tr>
				<?php endforeach; ?>
			<?php endif; ?>
		</tbody>
	</table>

	<?php
	$total_pages = (int) ceil( $total / $limit );
	if ( $total_pages > 1 ) :
		$page_links = paginate_links(
			array(
				'base'      => add_query_arg( 'paged', '%#%' ),
				'format'    => '',
				'prev_text' => '&laquo;',
				'next_text' => '&raquo;',
				'total'     => $total_pages,
				'current'   => $page,
			)
		);
		if ( $page_links ) :
			?>
			<div class="tablenav"><div class="tablenav-pages"><?php echo wp_kses_post( $page_links ); ?></div></div>
			<?php
		endif;
	endif;
	?>

<div class="rc-text-right rc-mt-8">
	<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="rc-inline">
			<?php wp_nonce_field( 'rc_export_ingredients' ); ?>
			<input type="hidden" name="action" value="rc_export_ingredients" />
			<button type="submit" class="button"><?php esc_html_e( 'Export CSV', 'restaurant-costing' ); ?></button>
		</form>
	</div>

	<?php require RC_PLUGIN_DIR . 'admin/views/partials/ingredient-modal.php'; ?>
</div>

<style>
.rc-ingredients-table { table-layout: fixed; }
.rc-ingredients-table .rc-col-ingredient { width: 34%; }
.rc-ingredients-table .rc-col-type { width: 14%; }
.rc-ingredients-table .rc-col-size { width: 18%; }
.rc-ingredients-table .rc-col-cost { width: 10%; text-align: center; }
.rc-ingredients-table .rc-col-sub-recipe { width: 7%; text-align: center; }
.rc-ingredients-table .rc-col-actions { width: 17%; }
.rc-ingredients-table .rc-sub-recipe-mark { font-size: 16px; line-height: 1; color: #5897ff; }
body.rc-theme-light .rc-ingredients-table .rc-sub-recipe-mark { color: #2271b1; }
.rc-ingredients-table th,
.rc-ingredients-table td { box-sizing: border-box; overflow-wrap: anywhere; }
</style>
