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

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


$per_page      = isset( $_GET['per_page'] ) ? (int) $_GET['per_page'] : ( isset( $_COOKIE['rc_pp_recipes'] ) ? (int) $_COOKIE['rc_pp_recipes'] : 25 );
$search        = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
$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'] );
$show_menu_items     = ! empty( $_GET['show_menu_items'] );
$show_sub_recipes    = ! empty( $_GET['show_sub_recipes'] );

// Default to Menu Items on fresh page load only
$has_filter = isset( $_GET['per_page'] ) || ! empty( $_GET['s'] ) || ! empty( $_GET['menu_type'] );
if ( ! $has_filter ) {
	$show_menu_items = true;
}
$menu_type_filter    = isset( $_GET['menu_type'] ) ? (int) $_GET['menu_type'] : 0;

$current_base = add_query_arg(
	array(
		'page'           => 'restaurant-costing-recipes',
		's'              => $search,
		'per_page'       => $per_page,
		'show_inactive'  => $show_inactive ? 1 : false,
		'show_menu_items' => $show_menu_items ? 1 : false,
		'show_sub_recipes' => $show_sub_recipes ? 1 : false,
		'menu_type'      => $menu_type_filter ?: false,
	),
	admin_url( 'admin.php' )
);

// Determine is_ingredient_filter string for the repository
if ( $show_menu_items && ! $show_sub_recipes ) {
	$is_ingredient_filter = 'no';
} elseif ( ! $show_menu_items && $show_sub_recipes ) {
	$is_ingredient_filter = 'yes';
} elseif ( ! $show_menu_items && ! $show_sub_recipes ) {
	$is_ingredient_filter = 'none';
} else {
	$is_ingredient_filter = '';
}

$total_all = RC_Recipe_Repository::count( '', false, $is_ingredient_filter, $menu_type_filter );
?>
<div class="wrap">
	<h1 class="wp-heading-inline"><?php esc_html_e( 'Restaurant Costing - Recipes', 'restaurant-costing' ); ?></h1>
	<div class="rc-version">v<?php echo esc_html( RC_VERSION ); ?></div>
	<a href="<?php echo esc_url( admin_url( 'admin.php?page=restaurant-costing-recipe-edit' ) ); ?>" class="page-title-action">
		<?php esc_html_e( 'Add New', 'restaurant-costing' ); ?>
	</a>
	<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">
		<form method="get" class="rc-filter-form">
			<input type="hidden" name="page" value="restaurant-costing-recipes" />
			<input type="search" name="s" placeholder="<?php esc_attr_e( 'Search recipes...', 'restaurant-costing' ); ?>" value="<?php echo esc_attr( $search ); ?>" class="rc-w-240" />
			<label class="rc-flex rc-items-center rc-gap-4">
				<input type="checkbox" name="show_inactive" value="1" <?php checked( $show_inactive ); ?> onchange="this.form.submit()" />
				<span><?php esc_html_e( 'Show Inactive', 'restaurant-costing' ); ?></span>
			</label>

			<label class="rc-flex rc-items-center rc-gap-4">
				<input type="checkbox" name="show_menu_items" value="1" <?php checked( $show_menu_items ); ?> onchange="this.form.submit()" />
				<span><?php esc_html_e( 'Menu Items', 'restaurant-costing' ); ?></span>
			</label>
			<label class="rc-flex rc-items-center rc-gap-4">
				<input type="checkbox" name="show_sub_recipes" value="1" <?php checked( $show_sub_recipes ); ?> onchange="this.form.submit()" />
				<span><?php esc_html_e( 'Sub-recipes', 'restaurant-costing' ); ?></span>
			</label>

			<select name="menu_type" onchange="this.form.submit()">
				<option value=""><?php esc_html_e( 'All Menu Types', 'restaurant-costing' ); ?></option>
				<?php foreach ( RC_Menu_Type_Repository::get_all() as $mt ) : ?>
					<option value="<?php echo (int) $mt->id; ?>" <?php selected( $menu_type_filter, (int) $mt->id ); ?>><?php echo esc_html( $mt->name ); ?></option>
				<?php endforeach; ?>
			</select>
			<?php if ( ! $show_menu_items && ! $show_sub_recipes ) : ?>
				<span style="color:#fff;font-weight:700;font-style:italic;"><?php esc_html_e( 'Select Menu Item or Sub-recipe for view', 'restaurant-costing' ); ?></span>
			<?php endif; ?>

		<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-recipes' ) ); ?>" class="button"><?php esc_html_e( 'Reset', 'restaurant-costing' ); ?></a>
		</form>
	</div>

	<table class="wp-list-table widefat fixed striped rc-recipes-table rc-table-rounded">
		<thead>
			<tr>
				<th>
					<?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__( 'Recipe', 'restaurant-costing' ),
						$label
					);
					?>
				</th>
				<th><?php esc_html_e( 'Menu Type', 'restaurant-costing' ); ?></th>
				<th><?php esc_html_e( 'Cost / portion', 'restaurant-costing' ); ?></th>
				<th><?php esc_html_e( 'Menu price', 'restaurant-costing' ); ?></th>
				<th><?php esc_html_e( 'Food cost %', 'restaurant-costing' ); ?></th>
				<th><?php esc_html_e( 'Actions', 'restaurant-costing' ); ?></th>
					<th class="rc-col-sub rc-text-center">
					<?php
					$dir   = ( $orderby === 'is_ingredient' ) ? ( $order === 'ASC' ? 'desc' : 'asc' ) : 'asc';
					$label = ( $orderby === 'is_ingredient' ) ? ( $order === 'ASC' ? ' ↓' : ' ↑' ) : '';
					printf( '<a href="%s">%s%s</a>',
						esc_url( add_query_arg( array( 'orderby' => 'is_ingredient', 'order' => $dir, 'paged' => false ), $current_base ) ),
						esc_html__( 'Sub-recipe', 'restaurant-costing' ),
						$label
					);
					?>
				</th>
			</tr>
		</thead>
		<tbody>
			<?php if ( empty( $items ) ) : ?>
				<tr><td colspan="7"><?php esc_html_e( 'No recipes yet. Add your first recipe.', 'restaurant-costing' ); ?></td></tr>
			<?php else : ?>
				<?php foreach ( $items as $item ) : ?>
					<?php
					$full   = RC_Recipe_Repository::get_full( (int) $item->id );
					$totals = $full['totals'] ?? array();
					$edit   = admin_url( 'admin.php?page=restaurant-costing-recipe-edit&id=' . (int) $item->id );
					
					$print  = add_query_arg( 
						array( 
							'action' => 'rc_print_recipe', 
							'id'     => (int) $item->id 
						), 
						admin_url( 'admin-post.php' ) 
					);
					?>
					<?php
					$inactive   = (int) ( $item->is_active ?? 1 ) === 0;
					$row_style   = $inactive ? ' background:#fceaea;' : '';
					?>
					<tr class="<?php echo $inactive ? 'rc-row-inactive' : ''; ?>">
						<td><strong><a href="<?php echo esc_url( $edit ); ?>"><?php echo esc_html( (string) $item->name ); ?></a><?php if ( $inactive ) : ?> <span class="rc-color-error rc-fs-0-85em">(☒ inactive)</span><?php endif; ?></strong></td>
						<td><?php $mt_name = RC_Menu_Type_Repository::get_name( (int) ( $item->menu_type_id ?? 0 ) ); echo $mt_name ? esc_html( $mt_name ) : '—'; ?></td>
						<td><?php echo esc_html( '$' . number_format( (float) ( $totals['cost_per_portion'] ?? 0 ), 2 ) ); ?></td>
						<td>
							<?php
								echo $item->menu_price
									? esc_html( '$' . number_format( (float) $item->menu_price, 2 ) )
									: '—';
							?>
						</td>
						<td>
							<?php
								echo ! empty( $totals['menu_price'] )
									? esc_html( rc_fmt_num( $totals['food_cost_pct'] ) . '%' )
									: '—';
							?>
						</td>
						<td class="rc-actions-cell">
							<a href="<?php echo esc_url( $edit ); ?>" class="button rc-action-btn"><?php esc_html_e( 'Edit', 'restaurant-costing' ); ?></a>
							<a href="<?php echo esc_url( $print ); ?>" class="button rc-action-btn" target="_blank"><?php esc_html_e( 'Print', 'restaurant-costing' ); ?></a>
						</td>
						<td class="rc-col-sub rc-text-center"><?php echo (int) ( $item->is_ingredient ?? 0 ) ? '☑' : '☐'; ?></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>

<style>
.rc-recipes-table.striped tbody tr:nth-child(odd) { background-color: #fff; }
.rc-recipes-table.striped tbody tr:nth-child(even) { background-color: #ececec; }
.rc-recipes-table th, .rc-recipes-table td { box-sizing: border-box; }
.rc-recipes-table .rc-col-sub { width: 90px; text-align: center; }
.rc-recipes-table .rc-actions-cell { white-space: nowrap; }
</style>
