<?php

declare(strict_types=1);

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

$highlight_inventory = isset( $_GET['inventory_id'] ) ? (int) $_GET['inventory_id'] : 0;

$per_page = isset( $_GET['per_page'] ) ? (int) $_GET['per_page'] : ( isset( $_COOKIE['rc_pp_inventory'] ) ? (int) $_COOKIE['rc_pp_inventory'] : 25 );
$search   = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
$orderby  = isset( $_GET['orderby'] ) ? sanitize_text_field( wp_unslash( $_GET['orderby'] ) ) : 'created_at';
$order    = isset( $_GET['order'] ) ? sanitize_text_field( wp_unslash( $_GET['order'] ) ) : 'DESC';

$current_base = add_query_arg(
	array(
		'page'     => 'restaurant-costing-inventory',
		's'        => $search,
		'per_page' => $per_page,
	),
	admin_url( 'admin.php' )
);

$total_all = RC_Inventory_Repository::count();
?>
<div class="wrap">
	<h1 class="wp-heading-inline"><?php esc_html_e( 'Restaurant Costing - Inventories', '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-inventory-we' ) ); ?>" class="page-title-action"><?php esc_html_e( 'New Inventory', 'restaurant-costing' ); ?></a>
	<button type="button" class="page-title-action" id="rc-edit-areas-page"><?php esc_html_e( 'Edit Areas', '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">
		<form method="get" class="rc-filter-form">
			<input type="hidden" name="page" value="restaurant-costing-inventory" />
			<input type="search" name="s" placeholder="<?php esc_attr_e( 'Search inventories...', 'restaurant-costing' ); ?>" value="<?php echo esc_attr( $search ); ?>" class="rc-w-240" />
			<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-inventory' ) ); ?>" class="button"><?php esc_html_e( 'Reset', 'restaurant-costing' ); ?></a>
		</form>
	</div>

	<div class="rc-inventory-summary">
		<label><input type="checkbox" id="rc-print-hide-blank" checked /> <?php esc_html_e( 'Print/Order/Email: Omit Empty Rows', 'restaurant-costing' ); ?></label>
	</div>

	<table class="wp-list-table widefat fixed striped rc-inventory-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__( 'Name', 'restaurant-costing' ),
						$label
					);
					?>
				</th>
				<th>
					<?php
					$dir   = ( $orderby === 'created_at' ) ? ( $order === 'ASC' ? 'desc' : 'asc' ) : 'desc';
					$label = ( $orderby === 'created_at' ) ? ( $order === 'ASC' ? ' ↑' : ' ↓' ) : '';
					printf( '<a href="%s">%s%s</a>',
						esc_url( add_query_arg( array( 'orderby' => 'created_at', 'order' => $dir, 'paged' => false ), $current_base ) ),
						esc_html__( 'Date', 'restaurant-costing' ),
						$label
					);
					?>
				</th>
				<th><?php esc_html_e( 'Actions', 'restaurant-costing' ); ?></th>
			</tr>
		</thead>
		<tbody>
			<?php if ( empty( $items ) ) : ?>
				<tr><td colspan="3"><?php esc_html_e( 'No inventories found.', 'restaurant-costing' ); ?></td></tr>
			<?php else : ?>
				<?php foreach ( $items as $item ) : ?>
					<?php $is_highlighted = $highlight_inventory === (int) $item->id; ?>
					<tr class="<?php echo $is_highlighted ? 'rc-highlight-row' : ''; ?>">
						<td><strong><?php echo esc_html( (string) ( $item->name ?? '' ) ); ?></strong></td>
						<td><?php echo esc_html( (string) ( $item->created_at ?? '' ) ); ?></td>
						<td class="rc-actions-cell">
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=restaurant-costing-inventory-we&id=' . (int) $item->id ) ); ?>" class="button rc-action-btn"><?php esc_html_e( 'Edit', 'restaurant-costing' ); ?></a>
							<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=rc_delete_inventory&id=' . (int) $item->id ), 'rc_delete_inventory_' . (int) $item->id ) ); ?>" class="button rc-action-btn rc-action-btn-danger rc-confirm-inventory-delete"><?php esc_html_e( 'Delete', 'restaurant-costing' ); ?></a>
							<a href="#" class="button rc-action-btn rc-order-inventory" data-id="<?php echo (int) $item->id; ?>"><?php esc_html_e( 'Print/Order', '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 id="rc-order-modal" class="rc-modal" role="dialog" aria-modal="true" hidden>
		<div class="rc-modal-backdrop" tabindex="-1"></div>
		<div class="rc-modal-dialog rc-modal-dialog-xl">
			<header class="rc-modal-header">
				<h2 id="rc-order-modal-title"><?php esc_html_e( 'Print and Order', 'restaurant-costing' ); ?></h2>
				<button type="button" class="rc-modal-close" aria-label="Close">&times;</button>
			</header>
			<div class="rc-modal-body">
				<div id="rc-order-loading" class="rc-order-loading"><?php esc_html_e( 'Loading...', 'restaurant-costing' ); ?></div>
				<div id="rc-order-content" class="rc-hidden">
					<h3><?php esc_html_e( 'Inventory Items by Supplier', 'restaurant-costing' ); ?></h3>
					<div id="rc-order-supplier-list"></div>
				</div>
			</div>
			<footer class="rc-modal-footer">
				<button type="button" class="button button-primary rc-print-all" data-id="0"><?php esc_html_e( 'Print All', 'restaurant-costing' ); ?></button>
				<button type="button" class="button rc-print-not-ordered" data-id="0"><?php esc_html_e( 'Print Not Ordered', 'restaurant-costing' ); ?></button>
				<div style="flex:1;"></div>
				<button type="button" class="button rc-modal-cancel"><?php esc_html_e( 'Close', 'restaurant-costing' ); ?></button>
			</footer>
		</div>
	</div>

	<div id="rc-areas-page-modal" class="rc-modal" role="dialog" aria-modal="true" hidden>
		<div class="rc-modal-backdrop" tabindex="-1"></div>
		<div class="rc-modal-dialog rc-modal-dialog-xl rc-areas-page-dialog">
			<header class="rc-modal-header">
				<h2><?php esc_html_e( 'Edit Areas', 'restaurant-costing' ); ?></h2>
				<button type="button" class="rc-modal-close" aria-label="Close">&times;</button>
			</header>
			<div class="rc-modal-body rc-areas-page-body">
				<iframe id="rc-areas-page-frame" title="<?php esc_attr_e( 'Edit Areas', 'restaurant-costing' ); ?>" data-src="<?php echo esc_url( admin_url( 'admin.php?page=restaurant-costing-areas&rc_modal=1' ) ); ?>"></iframe>
			</div>
			<footer class="rc-modal-footer">
				<button type="button" class="button rc-modal-cancel"><?php esc_html_e( 'Close', 'restaurant-costing' ); ?></button>
			</footer>
		</div>
	</div>
</div>

<style>
.rc-inventory-table.striped tbody tr:nth-child(odd) { background-color: #fff; }
.rc-inventory-table.striped tbody tr:nth-child(even) { background-color: #ececec; }
.rc-highlight-row td { background-color: #d4edda !important; }
.rc-supplier-group { margin-bottom: 16px; border: 1px solid #c3c4c7; border-radius: 4px; overflow: hidden; }
.rc-supplier-header { background: #f0f0f1; padding: 8px 12px; display: flex; justify-content: space-between; align-items: center; font-weight: 600; cursor: pointer; }
.rc-supplier-header:hover { background: #e0e0e0; }
.rc-supplier-items { padding: 8px 12px; }
.rc-supplier-items table { width: 100%; border-collapse: collapse; }
.rc-supplier-items th, .rc-supplier-items td { padding: 4px 8px; text-align: left; border-bottom: 1px solid #eee; font-size: 13px; }
.rc-supplier-items .rc-ordered-row { background-color: #d4edda; }
.rc-prompt-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 100000; display: flex; align-items: center; justify-content: center; }
.rc-prompt-box { background: #fff; border-radius: 6px; padding: 24px; max-width: 400px; box-shadow: 0 4px 12px rgba(0,0,0,0.2); text-align: center; }
.rc-prompt-box p { margin: 0 0 16px; font-size: 14px; }
.rc-prompt-box .rc-prompt-buttons { margin-bottom: 0; display: flex; gap: 8px; justify-content: center; }
.rc-supplier-actions { padding: 6px 12px; border-top: 1px solid #e0e0e0; background: #fafafa; display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }
.btn-print-supplier { background: #2271b1; color: #fff; border: 1px solid #2271b1; }
.btn-print-supplier:hover { background: #135e96; border-color: #135e96; }
.btn-email-supplier { background: #46b450; color: #fff; border: 1px solid #46b450; }
.btn-email-supplier:hover { background: #389a41; border-color: #389a41; }
.btn-email-supplier .dashicons { font-size: 16px; width: 16px; height: 16px; vertical-align: text-bottom; margin-right: 2px; }
.rc-emailed-msg { color: #46b450; font-weight: 600; font-size: 12px; }
.rc-print-all { background: #2271b1; color: #fff; border-color: #2271b1; }
.rc-print-all:hover { background: #135e96; }
.rc-print-not-ordered { background: #f6f7f7; border-color: #2271b1; color: #2271b1; }
.rc-print-not-ordered:hover { background: #f0f0f1; }
.rc-areas-page-dialog { max-width: 920px; width: calc(100vw - 80px); }
.rc-areas-page-body { padding: 0; height: 620px; }
#rc-areas-page-frame { border: 0; width: 100%; height: 100%; display: block; }
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
	if (typeof rcConfirm === 'undefined') return;
	document.querySelectorAll('.rc-confirm-inventory-delete').forEach(function (el) {
		el.addEventListener('click', function (e) {
			e.preventDefault();
			var href = this.getAttribute('href');
			rcConfirm('<?php echo esc_js( __( 'Delete this inventory?', 'restaurant-costing' ) ); ?>', function (ok) {
				if (ok) window.location.href = href;
			});
		});
	});
});
</script>
