<?php
if (! defined('ABSPATH')) exit;
// phpcs:ignoreFile

/**
 * Anbaarak | Best Inventory management plugin for WooCommerce.
 * All rights reserved for WP LEGEND team (wplegend.ir)
 */

use Anbarak\Input;

$_nonce = wp_create_nonce('form_nonce');

$products_list = array();

$args = [];

if (!empty($_COOKIE['anbarak_group_variables']) && $_COOKIE['anbarak_group_variables'] === 'true') {
	$args['group_variables'] = true;
}
?>
<header class="mb-5 flex p-px flex-col lg:flex-row gap-4 overflow-hidden overflow-x-auto">
	<h1 class="!m-0 pt-1"><?php echo esc_html(anbarak_get_current_page_name('inventory')) ?></h1>
	<form class="product-search flex-grow" action="" method="get">
		<div class="search-wrap gap-3 flex flex-col lg:flex-row items-center">
			<div class="search-form-wrapper">
				<input type="hidden" name="action" value="anbarak_product_search">
				<input type="hidden" name="security" value="<?php echo esc_attr(ANBARAK_AJAX_NONCE) ?>">
				<div class="flex border-b border-b-gray-200 xl:border-none">
					<select name="category" id="product-category" class="me-1 max-w-30">
						<option value=""><?php esc_html_e('All Categories', 'anbarak'); ?></option>
						<?php
						$all_categories = get_terms(array(
							'taxonomy' => 'product_cat',
							'hide_empty' => true
						));

						function display_categories_hierarchical($categories, $parent_id = 0, $level = 0)
						{
							foreach ($categories as $category) {
								if ($category->parent == $parent_id) {
									$indent = str_repeat('&nbsp;&nbsp;&nbsp;', $level);
									// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only product filter.
									$current_category = isset($_GET['category']) ? (int) sanitize_text_field(wp_unslash($_GET['category'])) : 0;
									$selected = ($current_category === (int) $category->term_id) ? 'selected' : '';
									echo '<option value="' . esc_attr($category->term_id) . '" ' . esc_attr($selected) . '>'
										. wp_kses_post($indent) . esc_html($category->name) . '</option>';

									display_categories_hierarchical($categories, $category->term_id, $level + 1);
								}
							}
						}

						display_categories_hierarchical($all_categories);
						?>
					</select>

					<select name="t" id="" class="me-1 max-w-30">
						<option value="p-name"><?php esc_html_e('Product Name', 'anbarak'); ?></option>
						<option value="p-stock"><?php esc_html_e('Stock Value', 'anbarak'); ?></option>
						<option value="p-sku"><?php esc_html_e('SKU', 'anbarak'); ?></option>
					</select>
				</div>
				<div class="flex w-full min-w-50">
					<input name="q" type="text" class="ps-4 w-full h-[44px] outline-none" placeholder="<?php esc_attr_e('Search Products...', 'anbarak') ?>">
					<button type="submit" class="button button--primary"><i class="icon icon-search text-xl"></i></button>
				</div>
			</div>

			<div class="flex items-center flex-grow gap-x-4">
				<div class="block">
					<select id="stock-view-select" class=" border bg-white p-2 px-10 text-sm dark:bg-[#1a1a1a] dark:text-gray-200 dark:border-[#2a2a2a]">
						<option value="all"><?php esc_html_e('All', 'anbarak'); ?> (<?php echo esc_html(anbarak_get_total_managed_stock_products_count()) ?>)</option>
						<option value="in-stock"><?php esc_html_e('In Stock', 'anbarak'); ?> (<?php echo count(anbarak_get_in_stock_products()) ?>)</option>
						<option value="low-stock"><?php esc_html_e('Low Stock', 'anbarak'); ?> (<?php echo count(anbarak_get_low_stock_products()) ?>)</option>
						<option value="out-of-stock"><?php esc_html_e('Out Of Stock', 'anbarak'); ?> (<?php echo count(anbarak_get_out_of_stock_products()) ?>)</option>
					</select>
				</div>

				<div class="hidden max-w-[100%] overflow-x-auto">
					<div class="scroll">
						<div class="stock-nav button-group flex items-center whitespace-nowrap text-xs lg:text-sm">
							<div class="button-group__item !p-0">
								<button class="button bg-white active dark:bg-[#1a1a1a]"><?php esc_html_e('All', 'anbarak'); ?> (<?php echo esc_html(anbarak_get_total_managed_stock_products_count()) ?>)</button>
								<input class="sr-text" type="radio" name="view" value="all">
							</div>
							<div class="button-group__item !p-0">
								<button class="button bg-white dark:bg-[#1a1a1a]"><?php esc_html_e('In Stock', 'anbarak'); ?> (<?php echo count(anbarak_get_in_stock_products()) ?>)</button>
								<input class="sr-text" type="radio" name="view" value="in-stock">
							</div>
							<div class="button-group__item !p-0">
								<button class="button bg-white dark:bg-[#1a1a1a]"><?php esc_html_e('Low Stock', 'anbarak'); ?> (<?php echo count(anbarak_get_low_stock_products()) ?>)</button>
								<input class="sr-text" type="radio" name="view" value="low-stock">
							</div>
							<div class="button-group__item !p-0">
								<button class="button bg-white dark:bg-[#1a1a1a]"><?php esc_html_e('Out Of Stock', 'anbarak'); ?> (<?php echo count(anbarak_get_out_of_stock_products()) ?>)</button>
								<input class="sr-text" type="radio" name="view" value="out-of-stock">
							</div>
						</div>
					</div>
				</div>

				<div class="flex items-center whitespace-nowrap justify-center h-[44px] px-3 bg-white rounded-xl border border-gray-300 dark:bg-[#1a1a1a] dark:border-[#2a2a2a]">
					<label class="relative inline-flex items-center cursor-pointer">
						<input id="group-variables-switch" name="group-variables" type="checkbox" class="sr-only peer" <?php echo isset($_COOKIE['anbarak_group_variables']) ? 'checked' : '' ?>>
						<div class="w-10 h-6 bg-gray-300 dark:bg-[#333] rounded-full peer peer-checked:bg-green-500 transition-colors duration-300"></div>
						<div class="absolute start-1 bg-white dark:bg-gray-300 w-4 h-4 rounded-full transition-transform duration-300 peer-checked:ltr:translate-x-4 peer-checked:rtl:-translate-x-4 shadow-md"></div>
						<span class="text-sm mx-2 dark:text-gray-200"><?php esc_html_e('Group Variables', 'anbarak') ?></span>
					</label>
				</div>

				<button class="hidden button clear-form !p-2 !px-3 !leading-1" data-tippy-content="<?php esc_attr_e('Clear Form (ESC)', 'anbarak') ?>">
					<span class="icon icon-delete text-xl pb-0.5"></span>
				</button>
			</div>

			<?php if (anbarak_user_is_admin_or_manager()): ?>
				<button type="button" class="hidden xl:!flex button items-center justify-center p-0 w-[44px] h-[44px]" id="btn-export-excel" data-tippy-content="<?php esc_attr_e('Export To Excel', 'anbarak'); ?>">
					<span class="icon icon-microsoftexcel text-lg"></span>
				</button>
			<?php endif ?>


			<button
				type="button"
				class="hidden xl:!flex button items-center justify-center p-0 w-[44px] h-[44px]"
				id="manage-columns"
				<?php if (!isset($_COOKIE['anbarak_columns'])): ?> data-with-notification="" <?php endif ?>
				data-tippy-content="<?php esc_attr_e('Manage Columns', 'anbarak'); ?>">
				<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24">
					<g fill="none" fill-rule="evenodd">
						<path d="M.66 3.35A2.49 2.49 0 0 1 3.15.86h17.4a2.49 2.49 0 0 1 2.48 2.49v17.4a2.49 2.49 0 0 1-2.48 2.49H3.15a2.49 2.49 0 0 1-2.49-2.49zm13.67 0H9.36v17.4h4.97zm2.49 0h3.73v17.4h-3.73Zm-9.94 17.4V3.35H3.15v17.4Z" style="fill:#333;stroke-width:1.2429378" />
					</g>
				</svg>
			</button>
		</div>
	</form>
</header>

<?php if (anbarak_get_total_managed_stock_products_count() <= 0) : ?>
	<div class="message p-5 rounded-xl bg-red-100 text-red-500 mb-3 flex items-center gap-4">
		<i class="icon icon-info text-3xl"></i>
		<div>
			<h2><?php esc_html_e('Product Inventory Management', 'anbarak'); ?></h2>
			<p>
				<?php esc_html_e('To view and manage product stock via Anbarak, please enable product stock management and product variations first.', 'anbarak'); ?>
			</p>
		</div>
	</div>
<?php endif; ?>

<div class="anbarak-products-wrapper">
	<form name="form" action="" method="POST">
		<input type="hidden" name="form_nonce" value="<?php echo esc_attr($_nonce) ?>">
		<input name="" type="hidden" class="actionName">
		<input name="pid" type="hidden" value="">
		<input name="vid" type="hidden" value="">

		<div class="anbarak-products-wrapper-table-wrapper table-container">
			<?php anbarak_render_products_table_items($args) ?>
		</div>

	</form>

	<div class="micro-modal micromodal-slide submit-order-modal" id="modal-new-order" aria-hidden="false">
		<div class="modal__overlay" tabindex="-1" data-micromodal-close="">
			<div class="modal__container box" role="dialog" aria-modal="true" aria-labelledby="modal-1-title">
				<header class="modal__header">
					<h2 class="modal__title"><?php esc_html_e('Create An Order', 'anbarak') ?></h2>
					<button class="modal__close" type="button" aria-label="Close modal" data-micromodal-close></button>
				</header>
				<main class="modal__content">
					<div class="new-order-products bg-gray rounded mb-3">
						<legend class="font-bold mb-3"><?php esc_html_e('Products', 'anbarak') ?></legend>
						<form class="submit-order-product-search" action="" method="get">
							<div class="search-wrap flex items-center">
								<div class="search-form-wrapper relative">
									<select name="t" id="" class="me-1">
										<option value="p-sku" data-input-placeholder="<?php esc_attr_e('Enter SKU or Scan Barcode... ', 'anbarak') ?>"><?php esc_html_e('SKU', 'anbarak'); ?></option>
										<option value="p-name" data-input-placeholder="<?php esc_attr_e('Enter Product Name... ', 'anbarak') ?>"><?php esc_html_e('Product Name', 'anbarak'); ?></option>
									</select>
									<input name="q" type="text" class="w-full h-[44px] min-w-20 me-1 outline-none" placeholder="<?php esc_attr_e('Search Products...', 'anbarak') ?>">
									<input type="hidden" name="action" value="anbarak_new_order_product_search">
									<input type="hidden" name="security" value="<?php echo esc_attr(ANBARAK_AJAX_NONCE) ?>">
									<button type="submit" class="button button--primary"><i class="icon icon-search text-xl"></i></button>
									<kbd class="absolute end-20 opacity-50 text-xs">Ctrl+K</kbd>
								</div>
							</div>
							<ul class="product-select-list"> </ul>
						</form>

					</div>
					<form action="" id="new-order-form">
						<div class="new-order__products-list table-container mb-2">
							<table class="table">
								<thead>
									<tr>
										<th></th>
										<th><?php esc_html_e('Product Name', 'anbarak') ?></th>
										<th>SKU</th>
										<th><?php esc_html_e('Quantity', 'anbarak') ?></th>
										<th><?php esc_html_e('Price', 'anbarak') ?></th>
									</tr>
								</thead>
								<tbody>

								</tbody>
							</table>
							<template id="new-order-product-item">
								<tr class="product" data-id="" data-unit-price="" data-qty="1">
									<td>
										<button class="button delete p-0 w-[44px] h-[44px] rounded-full border-none bg-red-50 text-red-400 text-base">
											<i class="icon icon-trash"></i>
										</button>
									</td>
									<td class="name">
										<span class="title"></span>
										<bdi><small class="vars"></small></bdi>
									</td>
									<td class="sku"> </td>
									<td width="10%" class="qty">
										<?php echo wp_kses_post(Input::render([
											'name' => 'qty',
											'class' => 'text-center thousand-separator',
											'label' => esc_html__('Quantity', 'anbarak'),
										])); ?>
									</td>
									<td class="price">
										<?php echo wp_kses_post(Input::render([
											'name' => 'price',
											'class' => 'text-center thousand-separator',
											'label' => esc_html__('Price', 'anbarak'),
										])); ?>
									</td>
								</tr>
							</template>
						</div>

						<div class="totals flex mb-2 items-center">
							<div class="discount-wrapper flex-grow flex items-center gap-x-2">
								<span class="me-2"><?php esc_html_e('Discount', 'anbarak') ?></span>
								<div class="flex items-center">
									<b class="pe-1">٪</b>
									<?php echo wp_kses_post(Input::render([
										'name' => 'discount_percent',
										'id' => 'new-order-discount-percent',
										'class' => ' thousand-separator buy-tax',
										'label' => esc_html__('Discount Percent', 'anbarak'),
										'placeholder' => esc_html__('Enter Value', 'anbarak'),
										'form' => 'new-order-form',
									])); ?>
								</div>
								<?php echo wp_kses_post(Input::render([
									'name' => 'discount',
									'id' => 'new-order-discount',
									'class' => 'thousand-separator buy-tax',
									'label' => esc_html__('Discount', 'anbarak'),
									'placeholder' => esc_html__('Enter Value', 'anbarak'),
									'form' => 'new-order-form',
								])); ?>
							</div>
							<div class="px-2">
								<?php esc_html_e('Total Price', 'anbarak') ?>:
							</div>
							<div class="total-price font-bold me-1">0</div> <?php echo esc_html(get_woocommerce_currency_symbol()) ?>
						</div>
						<div class="my-5">
							<legend class="font-bold mb-3"><?php esc_html_e('Order Information', 'anbarak') ?></legend>
							<div class="flex gap-x-5">
								<div class="w-8/12 grid grid-cols-3 gap-3">
									<div class="">
										<?php echo wp_kses_post(Input::renderSearchDropdown([
											'name' => 'buyer_phone',
											'id' => 'phone',
											'class' => 'ltr',
											'parent_class' => 'w-full buyer-phone-selectx',
											'action' => 'anbarak_search_customers_by_phone',
											'hidden_name' => 'buyer_user_id',
											'attrs' => 'autocomplete="off" inputmode="tel"',
											'readonly_on_select' => true,
											'label' => esc_html__('Buyer Phone', 'anbarak'),
										])); ?>
									</div>
									<div class="">
										<?php echo wp_kses_post(Input::render([
											'name' => 'buyer_name',
											'label' => esc_html__('Name', 'anbarak'),
										])); ?>
									</div>
									<div class="">
										<?php echo wp_kses_post(Input::render([
											'name' => 'buyer_last_name',
											'label' => esc_html__('Last Name', 'anbarak'),
										])); ?>
									</div>
									<div class="">
										<?php echo wp_kses_post(Input::render([
											'name' => 'buyer_email',
											'type' => 'email',
											'label' => esc_html__('Buyer Email', 'anbarak'),
										])); ?>
									</div>

									<?php
									$show_country = anbarak_get_option('country_selector_mode', 'default') === 'dropdown';
									if ($show_country) {
										$all_countries = WC()->countries->get_shipping_countries();
										asort($all_countries);
										$current_country = anbarak_get_order_default_country();
									}
									?>
									<?php if ($show_country): ?>
										<div class="">
											<select name="buyer_country" id="buyer_country" class="border rounded p-2 w-full">
												<option value=""><?php esc_html_e('Select Country', 'anbarak') ?></option>
												<?php foreach ($all_countries as $code => $name): ?>
													<option value="<?php echo esc_attr($code); ?>" <?php selected($current_country, $code); ?>><?php echo esc_html($name); ?></option>
												<?php endforeach; ?>
											</select>
										</div>
									<?php endif; ?>
									<div class="">
										<?php $provinces = anbarak_wc_provinces($show_country ? $current_country : ''); ?>
										<select name="buyer_province" id="buyer-province" class="border rounded p-2 w-full">
											<option value=""><?php esc_html_e('Select Province', 'anbarak') ?></option>
											<?php foreach ($provinces as $code => $name): ?>
												<option value="<?php echo esc_attr($code); ?>"><?php echo esc_html($name); ?></option>
											<?php endforeach; ?>
										</select>
									</div>
									<div class="">
										<?php echo wp_kses_post(Input::render([
											'name' => 'buyer_postal',
											'label' => esc_html__('Buyer Postal Code', 'anbarak'),
										])); ?>
									</div>
									<div class="col-span-<?php echo $show_country ? '2' : '3' ?>">
										<?php echo wp_kses_post(Input::render([
											'name' => 'buyer_address',
											'parent_class' => 'w-full',
											'label' => esc_html__('Buyer Address', 'anbarak'),
										])); ?>
									</div>
								</div>
								<div class="w-4/12 flex flex-col gap-2">
									<div class="">
										<textarea rows="4" name="customer_notes" placeholder="<?php esc_attr_e('Customer Notes...', 'anbarak'); ?>" class="w-full w-100"></textarea>
									</div>
									<div class="">
										<label class="form-checkbox">
											<input type="checkbox" name="create_user" <?php echo isset($_COOKIE['anbaarak_opt_sell_create_user']) ? 'checked="true"' : '' ?>>
											<i class="form-icon"></i>
											<?php esc_html_e('Create user for order', 'anbarak') ?>
										</label>
									</div>
								</div>
							</div>
						</div>
						<button disabled type="button" id="submit-sell" class="button button--primary me-2"><i class="icon space icon-sell"></i><?php esc_html_e('Submit', 'anbarak'); ?></button>
						<span id="new-order-result" class="hidden text-bold text-sm mx-2 text-green-500"><?php esc_html_e('Order successfully created', 'anbarak') ?></span>
					</form>
				</main>
			</div>
		</div>
	</div>
	<div class="micro-modal micromodal-slide" id="modal-columns" aria-hidden="false">
		<div class="modal__overlay" tabindex="-1" data-micromodal-close="">
			<div class="modal__container box" role="dialog" aria-modal="true" aria-labelledby="modal-1-title">
				<header class="modal__header">
					<h2 class="modal__title"><?php esc_html_e('Manage Columns', 'anbarak'); ?> </h2>
					<button class="modal__close" type="button" aria-label="Close modal" data-micromodal-close></button>
				</header>
				<main class="modal__content">
					<form id="form-manage-columns" action="/" method="post">
						<?php anbarak_nonce() ?>
						<div class="grid grid-cols-2 gap-2">
							<div class="form-group">
								<label class="form-checkbox">
									<input type="checkbox" name="col_sku" <?php echo anbarak_is_inventory_column_active('sku') ? 'checked="true"' : '' ?>>
									<i class="form-icon"></i><?php esc_html_e('SKU', 'anbarak'); ?>
								</label>
							</div>
							<div class="form-group">
								<label class="form-checkbox">
									<input type="checkbox" name="col_weight" <?php echo anbarak_is_inventory_column_active('weight') ? 'checked="true"' : '' ?>>
									<i class="form-icon"></i><?php esc_html_e('Weight', 'anbarak'); ?>
								</label>
							</div>
							<div class="form-group">
								<label class="form-checkbox">
									<input type="checkbox" name="col_online_sell" <?php echo anbarak_is_inventory_column_active('online_sell') ? 'checked="true"' : '' ?>>
									<i class="form-icon"></i><?php esc_html_e('Online Sell', 'anbarak') ?>
								</label>
							</div>
							<div class="form-group">
								<label class="form-checkbox">
									<input type="checkbox" name="col_backorders" <?php echo anbarak_is_inventory_column_active('backorders') ? 'checked="true"' : '' ?>>
									<i class="form-icon"></i><?php esc_html_e('Backorders', 'anbarak') ?>
								</label>
							</div>
							<div class="form-group">
								<label class="form-checkbox">
									<input type="checkbox" name="col_last_buy_price" <?php echo anbarak_is_inventory_column_active('last_buy_price') ? 'checked="true"' : '' ?>>
									<i class="form-icon"></i><?php esc_html_e('Buy Price', 'anbarak') ?>
								</label>
							</div>
							<div class="form-group">
								<label class="form-checkbox">
									<input type="checkbox" name="col_submit_sell" <?php echo anbarak_is_inventory_column_active('submit_sell') ? 'checked="true"' : '' ?>>
									<i class="form-icon"></i><?php esc_html_e('Submit Sell', 'anbarak') ?>
								</label>
							</div>
						</div>
						<input type="hidden" name="action" value="anbarak_columns_save">
						<input type="hidden" name="security" value="<?php echo esc_attr(ANBARAK_AJAX_NONCE) ?>">
						<button type="button" id="confirm-columns" class="button button--primary mt-4 w-full"><?php esc_html_e('Confirm', 'anbarak'); ?></button>
					</form>
				</main>
			</div>
		</div>
	</div>
</div>
