<?php
/**
 * Suppliers 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;
}

$is_modal = ! empty( $_GET['rc_modal'] );
$modal_arg = $is_modal ? array( 'rc_modal' => '1' ) : array();

$per_page = isset( $_GET['per_page'] ) ? (int) $_GET['per_page'] : ( isset( $_COOKIE['rc_pp_suppliers'] ) ? (int) $_COOKIE['rc_pp_suppliers'] : 25 );
$search   = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
$orderby  = isset( $_GET['orderby'] ) ? sanitize_text_field( $_GET['orderby'] ) : 'business_name';
$order    = isset( $_GET['order'] ) ? sanitize_text_field( $_GET['order'] ) : 'ASC';

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

$total_all = RC_Supplier_Repository::count();
?>
<div class="wrap">
	<h1 class="wp-heading-inline"><?php esc_html_e( 'Restaurant Costing - Suppliers', 'restaurant-costing' ); ?></h1>
	<div class="rc-version">v<?php echo esc_html( RC_VERSION ); ?></div>
	<button type="button" class="page-title-action" id="rc-add-supplier-btn"><?php esc_html_e( 'Add Supplier', '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-suppliers" />
			<input type="search" name="s" placeholder="<?php esc_attr_e( 'Search suppliers...', '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-suppliers' ) ); ?>" class="button"><?php esc_html_e( 'Reset', 'restaurant-costing' ); ?></a>
		</form>
	</div>

	<table class="wp-list-table widefat fixed striped rc-suppliers-table rc-table-rounded">
		<thead>
			<tr>
				<th>
					<?php
					$dir   = ( $orderby === 'business_name' ) ? ( $order === 'ASC' ? 'desc' : 'asc' ) : 'asc';
					$label = ( $orderby === 'business_name' ) ? ( $order === 'ASC' ? ' ↓' : ' ↑' ) : '';
					printf( '<a href="%s">%s%s</a>',
						esc_url( add_query_arg( array( 'orderby' => 'business_name', 'order' => $dir, 'paged' => false ), $current_base ) ),
						esc_html__( 'Supplier', 'restaurant-costing' ),
						$label
					);
					?>
				</th>
				<th class="rc-hidden" style="display:none;"><?php esc_html_e( 'Address', 'restaurant-costing' ); ?></th>
				<th>
					<?php
					$dir   = ( $orderby === 'phone' ) ? ( $order === 'ASC' ? 'desc' : 'asc' ) : 'asc';
					$label = ( $orderby === 'phone' ) ? ( $order === 'ASC' ? ' ↓' : ' ↑' ) : '';
					printf( '<a href="%s">%s%s</a>',
						esc_url( add_query_arg( array( 'orderby' => 'phone', 'order' => $dir, 'paged' => false ), $current_base ) ),
						esc_html__( 'Phone', 'restaurant-costing' ),
						$label
					);
					?>
				</th>
				<th>
					<?php
					$dir   = ( $orderby === 'email' ) ? ( $order === 'ASC' ? 'desc' : 'asc' ) : 'asc';
					$label = ( $orderby === 'email' ) ? ( $order === 'ASC' ? ' ↓' : ' ↑' ) : '';
					printf( '<a href="%s">%s%s</a>',
						esc_url( add_query_arg( array( 'orderby' => 'email', 'order' => $dir, 'paged' => false ), $current_base ) ),
						esc_html__( 'Email', 'restaurant-costing' ),
						$label
					);
					?>
				</th>
				<th class="rc-hidden" style="display:none;">
					<?php
					$dir   = ( $orderby === 'contact_name' ) ? ( $order === 'ASC' ? 'desc' : 'asc' ) : 'asc';
					$label = ( $orderby === 'contact_name' ) ? ( $order === 'ASC' ? ' ↓' : ' ↑' ) : '';
					printf( '<a href="%s">%s%s</a>',
						esc_url( add_query_arg( array( 'orderby' => 'contact_name', 'order' => $dir, 'paged' => false ), $current_base ) ),
						esc_html__( 'Contact', 'restaurant-costing' ),
						$label
					);
					?>
				</th>
				<th><?php esc_html_e( 'Actions', 'restaurant-costing' ); ?></th>
			</tr>
		</thead>
		<tbody>
			<?php if ( empty( $items ) ) : ?>
				<tr><td colspan="4"><?php esc_html_e( 'No suppliers found.', 'restaurant-costing' ); ?></td></tr>
			<?php else : ?>
				<?php foreach ( $items as $item ) : ?>
					<tr>
						<td><strong><?php echo esc_html( (string) ( $item->business_name ?? '' ) ); ?></strong></td>
						<td style="display:none;"><?php echo esc_html( (string) ( $item->address ?? '' ) ); ?></td>
						<td><?php echo esc_html( (string) ( $item->phone ?? '' ) ); ?></td>
						<td><?php echo esc_html( (string) ( $item->email ?? '' ) ); ?></td>
						<td style="display:none;"><?php echo esc_html( (string) ( $item->contact_name ?? '' ) ); ?></td>
						<td class="rc-actions-cell">
							<a href="#" class="button rc-action-btn rc-edit-supplier" data-id="<?php echo (int) $item->id; ?>"><?php esc_html_e( 'Edit', 'restaurant-costing' ); ?></a>
							<a href="<?php echo esc_url( wp_nonce_url( add_query_arg( array_merge( array( 'action' => 'rc_delete_supplier', 'id' => (int) $item->id ), $modal_arg ), admin_url( 'admin-post.php' ) ), 'rc_delete_supplier_' . (int) $item->id ) ); ?>" class="button rc-action-btn rc-action-btn-danger rc-confirm-supplier-delete"><?php esc_html_e( 'Delete', '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_suppliers' ); ?>
			<input type="hidden" name="action" value="rc_export_suppliers" />
			<button type="submit" class="button"><?php esc_html_e( 'Export CSV', 'restaurant-costing' ); ?></button>
		</form>
	</div>

	<!-- Supplier Edit/Add Modal -->
	<div id="rc-supplier-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-md">
			<header class="rc-modal-header">
				<h2 id="rc-supplier-modal-title"><?php esc_html_e( 'Supplier', 'restaurant-costing' ); ?></h2>
				<button type="button" class="rc-modal-close" aria-label="Close">&times;</button>
			</header>
			<form id="rc-supplier-modal-form">
				<input type="hidden" id="rc-supplier-id" name="id" value="" />
				<div class="rc-modal-body">
					<p class="rc-modal-error" id="rc-supplier-modal-error" hidden></p>

					<table class="form-table">
						<tr>
							<th scope="row"><label for="rc-supplier-business-name"><?php esc_html_e( 'Supplier', 'restaurant-costing' ); ?> *</label></th>
							<td><input type="text" id="rc-supplier-business-name" name="business_name" class="regular-text" required /></td>
						</tr>
						<tr>
							<th scope="row"><label for="rc-supplier-address"><?php esc_html_e( 'Address', 'restaurant-costing' ); ?></label></th>
							<td><textarea id="rc-supplier-address" name="address" class="large-text" rows="3"></textarea></td>
						</tr>
						<tr>
							<th scope="row"><label for="rc-supplier-phone"><?php esc_html_e( 'Phone', 'restaurant-costing' ); ?></label></th>
							<td><input type="text" id="rc-supplier-phone" name="phone" class="regular-text" /></td>
						</tr>
						<tr>
							<th scope="row"><label for="rc-supplier-email"><?php esc_html_e( 'Email', 'restaurant-costing' ); ?></label></th>
							<td><input type="email" id="rc-supplier-email" name="email" class="regular-text" /></td>
						</tr>
						<tr>
							<th scope="row"><label for="rc-supplier-contact-name"><?php esc_html_e( 'Contact Name', 'restaurant-costing' ); ?></label></th>
							<td><input type="text" id="rc-supplier-contact-name" name="contact_name" class="regular-text" /></td>
						</tr>
						<tr>
							<th scope="row"><label for="rc-supplier-email-order"><?php esc_html_e( 'Email Order', 'restaurant-costing' ); ?></label></th>
							<td><label><input type="checkbox" id="rc-supplier-email-order" name="email_order" value="1" /> <?php esc_html_e( 'Send order emails to this supplier', 'restaurant-costing' ); ?></label></td>
						</tr>
					</table>
				</div>
				<footer class="rc-modal-footer">
					<button type="submit" class="button button-primary"><?php esc_html_e( 'Save', 'restaurant-costing' ); ?></button>
					<button type="button" class="button rc-modal-cancel"><?php esc_html_e( 'Cancel', 'restaurant-costing' ); ?></button>
				</footer>
			</form>
		</div>
	</div>

</div>

<script>
(function ($) {
	'use strict';

	var $modal = $('#rc-supplier-modal');
	var $form  = $('#rc-supplier-modal-form');

	$('#rc-add-supplier-btn').on('click', function () {
		$form[0].reset();
		$('#rc-supplier-id').val('');
		$('#rc-supplier-modal-title').text('<?php echo esc_js( __( 'Add Supplier', 'restaurant-costing' ) ); ?>');
		$('#rc-supplier-modal-error').prop('hidden', true).text('');
		$modal.prop('hidden', false);
		$('#rc-supplier-business-name').trigger('focus');
	});

	$(document).on('click', '.rc-edit-supplier', function (e) {
		e.preventDefault();
		var id = $(this).data('id');
		if (!id) return;

		$.getJSON(ajaxurl, {
			action: 'rc_get_supplier',
			nonce: '<?php echo wp_create_nonce( 'rc_recipe_ajax' ); ?>',
			id: id
		}).done(function (resp) {
			if (!resp || !resp.success) {
				$('#rc-supplier-modal-error').text('Could not fetch supplier data.').prop('hidden', false);
				return;
			}
			var item = resp.data;
			$('#rc-supplier-id').val(item.id);
			$('#rc-supplier-business-name').val(item.business_name);
			$('#rc-supplier-address').val(item.address || '');
			$('#rc-supplier-phone').val(item.phone || '');
			$('#rc-supplier-email').val(item.email || '');
			$('#rc-supplier-contact-name').val(item.contact_name || '');
			$('#rc-supplier-email-order').prop('checked', parseInt(item.email_order) === 1);
			$('#rc-supplier-modal-title').text('<?php echo esc_js( __( 'Edit Supplier', 'restaurant-costing' ) ); ?>');
			$('#rc-supplier-modal-error').prop('hidden', true).text('');
			$modal.prop('hidden', false);
		}).fail(function () {
			$('#rc-supplier-modal-error').text('Request failed.').prop('hidden', false);
		});
	});

	$modal.on('click', '.rc-modal-close, .rc-modal-cancel, .rc-modal-backdrop', function () {
		$modal.prop('hidden', true);
	});

	$(document).on('keydown', function (e) {
		if (e.key === 'Escape' && !$modal.prop('hidden')) {
			$modal.prop('hidden', true);
		}
	});

	$form.on('submit', function (e) {
		e.preventDefault();
		var $error = $('#rc-supplier-modal-error');
		$error.prop('hidden', true).text('');

		var $btn = $form.find('button[type="submit"]');
		$btn.prop('disabled', true);

		$.post(ajaxurl, {
			action: 'rc_save_supplier',
			nonce: '<?php echo wp_create_nonce( 'rc_recipe_ajax' ); ?>',
			id: $('#rc-supplier-id').val(),
			business_name: $('#rc-supplier-business-name').val(),
			address: $('#rc-supplier-address').val(),
			phone: $('#rc-supplier-phone').val(),
			email: $('#rc-supplier-email').val(),
			contact_name: $('#rc-supplier-contact-name').val(),
			email_order: $('#rc-supplier-email-order').is(':checked') ? 1 : 0
		}).done(function (resp) {
			if (!resp || !resp.success) {
				$error.text((resp && resp.data && resp.data.message) || 'Could not save.').prop('hidden', false);
				return;
			}
			window.location.reload();
		}).fail(function () {
			$error.text('Request failed.').prop('hidden', false);
		}).always(function () {
			$btn.prop('disabled', false);
		});
	});
})(jQuery);

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

<style>
.rc-suppliers-table.striped tbody tr:nth-child(odd) { background-color: #fff; }
.rc-suppliers-table.striped tbody tr:nth-child(even) { background-color: #ececec; }
.rc-suppliers-table .rc-actions-cell { white-space: nowrap; }

#rc-supplier-modal[hidden] { display: none !important; }
#rc-supplier-modal:not([hidden]) { display: block; }
#rc-supplier-modal .rc-modal-backdrop { position: fixed; inset: 0; background: rgba(0,0,0,0.55); z-index: 100099; }
#rc-supplier-modal .rc-modal-dialog { position: fixed; z-index: 100100; top: 50%; left: 50%; transform: translate(-50%, -50%); background: #fff; border-radius: 4px; box-shadow: 0 8px 32px rgba(0,0,0,0.2); max-height: 85vh; overflow-y: auto; }
#rc-supplier-modal .rc-modal-header { display: flex; align-items: center; justify-content: space-between; padding: 12px 16px; border-bottom: 1px solid #dcdcde; }
#rc-supplier-modal .rc-modal-header h2 { margin: 0; font-size: 1.2em; }
#rc-supplier-modal .rc-modal-close { background: none; border: none; font-size: 24px; line-height: 1; cursor: pointer; padding: 0 4px; color: #50575e; }
#rc-supplier-modal .rc-modal-body { padding: 12px 16px 0; }
#rc-supplier-modal .rc-modal-footer { padding: 12px 16px 16px; }
<?php if ( $is_modal ) : ?>
#adminmenumain, #wpadminbar, #wpfooter { display: none !important; }
html.wp-toolbar { padding-top: 0 !important; }
#wpcontent, #wpbody-content { margin-left: 0 !important; padding-left: 0 !important; }
#wpbody-content { padding-bottom: 0 !important; }
body { background: #fff; }
.wrap { margin: 16px; }
.rc-version { display: none; }
<?php endif; ?>
</style>
