<?php
$search_type_options = array(
	'' => lang('select') . ' ' . lang('search_type'),
	'period' => lang('by') . ' ' . lang('period'),
	'employee' => lang('by') . ' ' . lang('categories'),
);

$stock_category_options = array('' => lang('select') . ' ' . lang('stock_category'));
if (!empty($all_category_info)) {
	foreach ($all_category_info as $cate_name => $v_category_info) {
		if (empty($v_category_info) || !is_array($v_category_info)) {
			continue;
		}
		$cate_label = !empty($cate_name) ? $cate_name : lang('undefined_category');
		foreach ($v_category_info as $sub_category) {
			if (empty($sub_category->stock_sub_category_id) || empty($sub_category->stock_sub_category)) {
				continue;
			}
			$stock_category_options[$sub_category->stock_sub_category_id] = $cate_label . ' - ' . $sub_category->stock_sub_category;
		}
	}
}

$item_options = array('' => lang('select') . ' ' . lang('item_name'));
if (!empty($stock_info)) {
	foreach ($stock_info as $v_stock_info) {
		if (empty($v_stock_info->stock_id) || empty($v_stock_info->item_name)) {
			continue;
		}
		$item_options[$v_stock_info->stock_id] = $v_stock_info->item_name;
	}
}
?>
<div class="space-y-4">
	<div class="rounded-2xl border border-border bg-card shadow-sm">
		<div class="border-b border-border px-5 py-4">
			<div class="flex items-center gap-2">
				<i data-lucide="search" class="h-5 w-5"></i>
				<h3 class="text-base font-semibold text-foreground"><?= lang('search') ?></h3>
			</div>
		</div>
		<div class="p-5">
			<form id="sales_report" action="<?php echo base_url() ?>admin/stock/report" method="post" class="mx-auto max-w-xl space-y-3">
				<div class="grid grid-cols-1 gap-4 items-end">
					<?= form_select_group(
						'search_type',
						lang('search_type'),
						$search_type_options,
						!empty($search_type) ? $search_type : '',
						true,
						array('id' => 'search_type', 'class' => 'select_box w-full')
					) ?>
				</div>

				<div class="by_employee grid grid-cols-1 md:grid-cols-2 gap-4 items-end" style="display: <?= !empty($search_type) && $search_type == 'employee' ? 'grid' : 'none' ?>">
					<?= form_select_group(
						'stock_sub_category_id',
						lang('stock_category'),
						$stock_category_options,
						!empty($stock_sub_category_id) ? $stock_sub_category_id : '',
						!empty($search_type) && $search_type == 'employee',
						array(
							'id' => 'stock_sub_category_id',
							'class' => 'select_box w-full',
							'onchange' => 'get_item_name_by_id(this.value)'
						)
					) ?>
					<?= form_select_group(
						'stock_id',
						lang('item_name'),
						$item_options,
						!empty($stock_id) ? $stock_id : '',
						!empty($search_type) && $search_type == 'employee',
						array(
							'id' => 'item_name',
							'class' => 'select_box w-full',
							'data-search' => 'true'
						)
					) ?>
				</div>

				<div class="by_period grid grid-cols-1 md:grid-cols-2 gap-4 items-end" style="display: <?= !empty($search_type) && $search_type == 'period' ? 'grid' : 'none' ?>">
					<?= form_datepicker('start_date', lang('start_date'), !empty($date['start_date']) ? $date['start_date'] : '', !empty($search_type) && $search_type == 'period', array('id' => 'start_date', 'class' => 'start_date','data-max' => '#end_date', 'data-auto-close' => 'true')); ?>
					<?= form_datepicker('end_date', lang('end_date'), !empty($date['end_date']) ? $date['end_date'] : '', !empty($search_type) && $search_type == 'period', array('id' => 'end_date', 'class' => 'end_date', 'data-min' => '#start_date', 'data-auto-close' => 'true')); ?>
				</div>

				<div class="flex items-center justify-start">
					<button type="submit" name="flag" value="1" class="inline-flex h-9 items-center gap-2 rounded-lg bg-slate-900 px-4 text-sm font-semibold text-white transition hover:bg-slate-800 dark:bg-slate-100 dark:text-slate-900 dark:hover:bg-white">
						<i data-lucide="search" class="h-4 w-4"></i>
						<?= lang('search') ?>
					</button>
				</div>
			</form>
		</div>
	</div>

	<?php if (!empty($assign_stock) || !empty($purchase_stock)) : ?>
		<div id="printReport" class="rounded-2xl border border-border bg-card shadow-sm">
			<div class="border-b border-border px-5 py-4">
				<div class="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
					<div class="text-sm font-semibold text-foreground"><?= lang('report_list') ?></div>
					<div class="hidden-print flex items-center gap-2">
						<?php if (!empty($search_type) && $search_type == 'employee') { $url = 'name/' . $stock_id; } else { $url = $date['start_date'] . '/' . $date['end_date']; } ?>
						<?= btn_pdf('admin/stock/assign_report_pdf/' . $url); ?>
						<a onclick="print_sales_report('printReport')" class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-xs font-semibold text-foreground hover:bg-muted" data-toggle="tooltip" data-placement="top" title="<?= lang('print') ?>">
							<i data-lucide="printer" class="h-4 w-4"></i>
							<?= lang('print') ?>
						</a>
					</div>
				</div>
			</div>
			<div class="p-5">
				<div class="show_print mb-6 space-y-4">
					<div class="flex items-center gap-3 border-b border-border pb-3">
						<img style="width: 48px;height: 48px;" src="<?= base_url() . config_item('company_logo') ?>" alt="" class="rounded-full" />
						<div class="text-sm text-muted-foreground"><?= config_item('company_name') ?></div>
					</div>
					<div class="mt-4 rounded-lg bg-muted/40 p-3 text-sm">
						<?php if (!empty($search_type) && $search_type == 'employee') {
							$items_name = $this->db->where('stock_id', $stock_id)->get('tbl_stock')->row();
						?>
							<div><?= lang('items_name') ?>: <strong><?= !empty($items_name->item_name) ? html_escape($items_name->item_name) : '-' ?></strong></div>
						<?php } else { ?>
							<div><?= lang('stock') . ' ' . lang('report_from') ?>: <strong><?= display_date($date['start_date']); ?></strong></div>
							<div><?= lang('stock') . ' ' . lang('report_to') ?>: <strong><?= display_date($date['end_date']); ?></strong></div>
						<?php } ?>
					</div>
				</div>

				<?php if (!empty($purchase_stock)) { ?>
					<div class="mb-8">
						<div class="rounded-lg bg-muted/40 px-3 py-2 text-sm font-semibold text-foreground"><?= lang('stock_list') ?></div>
						<div class="overflow-x-auto rounded-xl border border-border bg-card">
							<table class="min-w-full text-sm">
								<?php foreach ($purchase_stock as $item_name => $v_purchase_stoc) : ?>
									<thead class="bg-slate-50 text-slate-600 dark:bg-slate-800 dark:text-slate-300">
										<tr>
											<th colspan="3" class="px-4 py-3 text-left text-sm font-semibold"><strong><?php echo $item_name; ?></strong></th>
										</tr>
										<tr>
											<th class="px-4 py-3 text-left font-semibold"><?= lang('item_name') ?></th>
											<th class="px-4 py-3 text-left font-semibold"><?= lang('inventory') ?></th>
											<th class="px-4 py-3 text-left font-semibold"><?= lang('buying_date') ?></th>
										</tr>
									</thead>
									<tbody class="divide-y divide-border">
										<?php
										$total_inventory = 0;
										if (!empty($v_purchase_stoc)) : foreach ($v_purchase_stoc as $v_stock) : ?>
											<tr class="hover:bg-muted/30">
												<td class="px-4 py-3"><?php echo $v_stock->item_name ?></td>
												<td class="px-4 py-3"><?php echo $v_stock->inventory; ?></td>
												<td class="px-4 py-3"><?= display_date($v_stock->purchase_date); ?></td>
											</tr>
											<?php $total_inventory += $v_stock->inventory; endforeach; ?>
											<tr class="bg-muted/20">
												<th class="px-4 py-3 text-right font-semibold"><?= lang('total') . ' ' . lang('assigned') . ':' ?></th>
												<td class="px-4 py-3 font-semibold"><?= $total_inventory - $v_stock->total_stock ?></td>
												<td class="px-4 py-3 text-right font-semibold"><?= lang('available_stock') ?>: <strong><?php echo $v_stock->total_stock; ?></strong></td>
											</tr>
										<?php endif; ?>
									</tbody>
								<?php endforeach; ?>
							</table>
						</div>
					</div>
				<?php } ?>

				<?php if (!empty($assign_stock)) { ?>
					<div>
						<div class="rounded-lg bg-muted/40 px-3 py-2 text-sm font-semibold text-foreground"><?= lang('assign_stock_list') ?></div>
						<div class="overflow-x-auto rounded-xl border border-border bg-card">
							<table class="min-w-full text-sm">
								<?php foreach ($assign_stock as $item_name => $v_assign_report) : ?>
									<thead class="bg-slate-50 text-slate-600 dark:bg-slate-800 dark:text-slate-300">
										<tr>
											<th colspan="4" class="px-4 py-3 text-left text-sm font-semibold"><strong><?php echo $item_name; ?></strong></th>
										</tr>
										<tr>
											<th class="px-4 py-3 text-left font-semibold"><?= lang('item_name') ?></th>
											<th class="px-4 py-3 text-left font-semibold"><?= lang('assign_quantity') ?></th>
											<th class="px-4 py-3 text-left font-semibold"><?= lang('assign_date') ?></th>
											<th class="px-4 py-3 text-left font-semibold"><?= lang('assigned_user') ?></th>
										</tr>
									</thead>
									<tbody class="divide-y divide-border">
										<?php if (!empty($v_assign_report)) : foreach ($v_assign_report as $v_report) : ?>
											<tr class="hover:bg-muted/30">
												<td class="px-4 py-3"><?= $v_report->item_name ?></td>
												<td class="px-4 py-3"><?= $v_report->assign_inventory ?></td>
												<td class="px-4 py-3"><?= display_date($v_report->assign_date); ?></td>
												<td class="px-4 py-3"><?= $v_report->fullname ?></td>
											</tr>
										<?php endforeach; endif; ?>
									</tbody>
								<?php endforeach; ?>
							</table>
						</div>
					</div>
				<?php } ?>
			</div>
		</div>
	<?php endif; ?>
</div>

<script type="text/javascript">
$(document).ready(function () {
	function syncStockReportValidation(val) {
		var isEmployee = val === 'employee';
		var isPeriod = val === 'period';
		var stockSubCategory = document.getElementById('stock_sub_category_id');
		var stockItem = document.getElementById('item_name');
		var startDate = document.getElementById('start_date');
		var endDate = document.getElementById('end_date');

		if (stockSubCategory) {
			stockSubCategory.required = isEmployee;
		}
		if (stockItem) {
			stockItem.required = isEmployee;
		}
		if (startDate) {
			startDate.required = isPeriod;
		}
		if (endDate) {
			endDate.required = isPeriod;
		}
	}

	$('#search_type').on('change', function () {
		var val = $(this).val();
		if (val === 'employee') {
			$('.by_employee').show();
			$('.by_period').hide();
		} else if (val === 'period') {
			$('.by_period').show();
			$('.by_employee').hide();
		} else {
			$('.by_period').hide();
			$('.by_employee').hide();
		}
		syncStockReportValidation(val);
	});

	syncStockReportValidation($('#search_type').val());
});

function get_item_name_by_id(stockSubCategoryId) {
	var $itemSelect = $('#item_name');
	var emptyOption = '<option value=""><?= html_escape(lang('select') . ' ' . lang('item_name')) ?></option>';

	if (!$itemSelect.length) {
		return;
	}

	$itemSelect.html(emptyOption);

	if (!stockSubCategoryId) {
		if (typeof init_selectpicker === 'function') {
			init_selectpicker();
		}
		return;
	}

	$.ajax({
		url: '<?= base_url('admin/stock/get_item_name_by_id') ?>/' + stockSubCategoryId,
		type: 'GET',
		success: function (response) {
			$itemSelect.html(response);
			if (typeof init_selectpicker === 'function') {
				init_selectpicker();
			}
		},
		error: function () {
			$itemSelect.html(emptyOption);
			if (typeof init_selectpicker === 'function') {
				init_selectpicker();
			}
		}
	});
}
</script>
