<?php
$breadcrumbs = [
    [
        'url' => 'dashboard.store.orders.index',
        'text' => t__('Orders')
    ],
    [
        'url' => 'dashboard.store.orders.create',
        'text' => t__('Add')
    ]
];
$this->layout('layouts/main', [
    'title' => t__('Create Order'),
		'category' => 'store.orders',
    'breadcrumbs' => $breadcrumbs
]) ?>

<section
	class="los-container py-9"
	x-data="{
		products: <?php echo htmlentities(json_encode($listingTree)) ?>,
		findProductRecursive(productId, category) {
	    if (!category) return null;
	
	    if (category.products) {
        for (let product of category.products) {
          if (product.id == productId) {
            return product;
          }
        }
	    }
	
	    if (category.subcategories) {
        for (let subcategory of category.subcategories) {
          let found = this.findProductRecursive(productId, subcategory);
          if (found) return found;
        }
	    }
	
	    return null;
		},
		findProductById(productId) {
	    if (Array.isArray(this.products)) {
        for (let category of this.products) {
          let found = this.findProductRecursive(productId, category);
          if (found) return found;
        }
	    }
	
	    return null;
		}
	}"
>
    <div class="los-page-heading">
        <h1 class="text-gray-950"><?php e__('Create Order') ?></h1>
		    <div class="flex gap-2">
			    <a href="<?php echo leaderosHelpUrl() ?>/using-leaderos/store/orders" class="btn btn-dark" target="_blank">
				    <?php e__('Help') ?>
			    </a>
	        <a href="<?php echo url('dashboard.store.orders.index') ?>" class="btn btn-default">
	            <?php e__('Back') ?>
	        </a>
		    </div>
    </div>

    <?php _message(); ?>
	
		<form method="post" action="<?php echo url('dashboard.store.orders.store') ?>">
			<div class="mt-10 grid grid-cols-1 lg:grid-cols-10 gap-6">
				<div class="col-span-7">
					<div class="card py-4 px-6">
						<?php
							$defaultInputs = array_map(function($product, $quantity, $unitPrice, $priceTotal) {
								return [
									'product' => $product,
									'quantity' => $quantity,
									'unitPrice' => $unitPrice,
									'priceTotal' => $priceTotal
								];
							}, old('product', []), old('quantity', ["1"]), old('unitPrice', ["0.00"]), old('priceTotal', ["0.00"]));
						?>
						<div x-data="inputArray({
	              product: '',
	              quantity: '1',
	              unitPrice: '0.00',
	              priceTotal: '0.00'
              }, <?php echo htmlentities(json_encode($defaultInputs)) ?>)"
						     x-init="$nextTick(() => {
                   onDelete = (index) => {
                    inputs.map((input, i) => {
                      $('#input_' + i + ' select').val(input.product).trigger('change');
                    })
                 }})"
						>
							<div class="flex justify-between items-center">
								<div class="card-title">
									<?php e__('Products') ?>
								</div>
								<span @click="addInput()" class="btn btn-sm btn-sheer btn-primary cursor-pointer flex items-center justify-center gap-1">
									<i data-feather="add" class="w-4 h-4 -ml-1"></i>
									<?php e__('Add') ?>
								</span>
							</div>
							<table class="mt-3 table">
								<thead class="">
								<tr class="table-header !text-xs !text-gray-500">
									<th scope="col" class="!text-left">
										<?php e__('Product') ?>
									</th>
									<th scope="col" style="width: 90px;">
										<?php e__('Quantity') ?>
									</th>
									<th scope="col" style="width: 110px;">
										<?php e__('Unit Price') ?>
									</th>
									<th scope="col" style="width: 100px;">
										<?php e__('Amount') ?>
									</th>
									<th scope="col" style="width: 40px">
										<span class="sr-only">
											<?php e__('Actions') ?>
										</span>
									</th>
								</tr>
								</thead>
								<tbody class="divide-y divide-gray-200/20 text-center">
								<template x-for="(input, index) in inputs" :key="index">
									<tr x-bind:id="'input_' + index">
										<td class="!text-left !pl-0">
											<label class="sr-only">
												<?php e__('Product') ?>
											</label>
											<?php $this->insert('components/select-product', [
												'name' => 'product[]',
												'placeholder' => t__('Select product'),
												'selectedJS' => 'input.product',
												'list' => $listingTree,
												'onChange' => '(selected) => { const product = findProductById(selected); input.unitPrice = product.price; }'
											]); ?>
										</td>
										<td class="!pl-0">
											<input type="text" class="form-control" name="quantity[]" x-model="input.quantity" style="text-align: center;">
										</td>
										<td class="!pl-0">
											<input type="text" class="form-control" name="unitPrice[]" x-model="input.unitPrice" style="text-align: center;">
										</td>
										<td class="!pl-0">
											<span x-text="(input.unitPrice * input.quantity).toFixed(2)"></span>
											<span><?php echo settings('currency') ?></span>
										</td>
										<td class="justify-end flex items-center !px-0" style="width: 40px;">
											<div @click="deleteInput(index)" class="btn btn-sheer btn-danger">
												<i class="stroke-red-500 stroke-2 w-4" data-feather="trash"></i>
											</div>
										</td>
									</tr>
								</template>
								</tbody>
							</table>
						</div>
					</div>
				</div>
				<div class="col-span-7 lg:col-span-3">
					<div class="card">
						<div class="py-4 px-6 grid gap-4">
							<div>
								<label for="total" class="form-label">
									<?php e__('Total') ?>:
								</label>
								<div class="input-absolute-group-right">
									<div class="text-gray-500 text-sm">
										<?php echo settings('currency') ?>
									</div>
									<input value="<?php _old('total', '0.00') ?>" type="text" id="total" name="total" class="form-control" required>
								</div>
							</div>
							
							<div>
								<label for="userID" class="form-label">
									<?php echo t__('User') ?>:
								</label>
								<?php $this->insert('components/search-user', [
									'userID' => old('userID'),
								]); ?>
							</div>
							
							<div>
								<label for="status" class="form-label">
									<?php echo t__('Status') ?>:
								</label>
								<select x-data="select2Alpine()" name="status" id="status">
									<option value="success" <?php _selected(old('status') == 'status'); ?>>
										<?php e__('Success') ?>
									</option>
									<option value="waiting" <?php _selected(old('status') == 'waiting'); ?>>
										<?php e__('Waiting') ?>
									</option>
								</select>
							</div>
							
							<div>
								<?php _csrf(); ?>
								<button type="submit" class="btn btn-success w-full !py-3 flex items-center justify-center gap-1.5">
									<i data-feather="add" class="w-4 h-4"></i>
									<?php e__('Create') ?>
								</button>
							</div>
						</div>
					</div>
				</div>
			</div>
		</form>
</section>
