{{ Form::open(['route' => 'Admin.Shop.PriceLists.store', 'id' => 'price_list-form', 'autocomplete' => 'off', 'files' => true]) }}

	<input type="hidden" name="id" value="{{ $price_list['id'] ?? null }}">
	<input type="hidden" name="tariff_id" value="{{ $price_list['tariff_id'] ?? null }}">

	<div class="row mb-3">
		<div class="col-8">
			{{ Form::label('name', 'Nom') }}
			@include('components.form.input', ['name' => 'name', 'value' => $price_list['name'] ?? null, 'required' => true])
		</div>
		<div class="col-4">
			{{ Form::label('status_id', 'Etat') }}
			@include('components.form.select', ['name' => 'status_id', 'list' => $statuses ?? [], 'value' => $price_list['status_id'] ?? null, 'required' => true])
		</div>
	</div>

	<div class="row mb-3">
		<div class="col-6">
			{{ Form::label('sale_channel_id', 'Canal de vente') }}
			@include('components.form.select', ['name' => 'sale_channel_id', 'list' => $sale_channels ?? [], 'value' => $price_list['sale_channel_id'] ?? null, 'required' => true, 'with_empty' => ''])
		</div>
	</div>

	@component('components.card', ['title' => 'Prix'])
		<table class="table table-bordered table-hover table-striped w-100 mb-0 dataTable" id="prices-table">
			<thead>
				<tr>
					<th>Code</th>
					<th>Seuil</th>
					<th>Unit. HT</th>
					<th>TVA</th>
					<th>Unit. TTC</th>
					<th class="text-center" style="width: 60px;">Actions</th>
				</tr>
			</thead>
			<tbody>
				@php($priceListValues = $price_list['price_list_values'] ?? [])
				@php($nextIndex = count($priceListValues))

				@foreach ($priceListValues as $index => $price_list_value)
					@include('Admin.Shop.PriceListValues.partials.row_price', ['index' => $index, 'price_list_value' => $price_list_value])
				@endforeach

				@include('Admin.Shop.PriceListValues.partials.row_price', ['index' => $nextIndex, 'price_list_value' => []])
			</tbody>
			<tfoot>
				<tr>
					<td colspan="3">
						<button type='button' class='btn btn-primary btn-xs' id='add_price'>
							Ajouter un seuil
							<i class='pl-2 fa fa-plus'></i>
						</button>
					</td>
				</tr>
			</tfoot>
		</table>
	@endcomponent
	<div id="deleted-price-list-values"></div>
</form>


<script>
	var priceRowIndex = 0;
	var lastRemovedIndex = null;

	function handleAddPrice() {
		$('#add_price').click( function () {
			addEmptyPriceRow();
		})
	}

	function addEmptyPriceRow() {
		var index = nextPriceRowIndex();
		$.get("{{ route('Admin.Shop.PriceListValues.addPrice') }}/" + index, function(data) {
			$("#prices-table tbody").append(data);
			handlePrices();
			handleRemovePrice();
			lastRemovedIndex = null;
		});
	}

	function handle_prices() {
		$('.price').change(function() {
			$col_tax = $(this).parent().parent().find('.tax');
			tax_selected = $col_tax.find('option:selected').text();
			price_taxed = $(this).val() * (1 + (tax_selected / 100));
			price_taxed = price_taxed.toFixed(2);
			console.log(price_taxed);
			$(this).parent().parent().find('.price_taxed').val(price_taxed);
		})
	}

	function handle_taxes() {
		$('.tax').change(function() {
			tax_selected = $(this).find('option:selected').text();
			price = $(this).parent().parent().find('.price').val();
			price_taxed = price * (1 + (tax_selected / 100));
			price_taxed = price_taxed.toFixed(2);
			$(this).parent().parent().find('.price_taxed').val(price_taxed);
		})
	}

	function handle_prices_taxed() {
		$('.price_taxed').change(function() {
			$col_tax = $(this).parent().parent().find('.tax');
			tax_selected = $col_tax.find('option:selected').text();
			price = $(this).val() / (1 + (tax_selected / 100));
			price = price.toFixed(2);
			$(this).parent().parent().find('.price').val(price);
		})
	}

	function handlePrices() {
		handle_prices();
		handle_taxes();
		handle_prices_taxed();
	}

	function handleRemovePrice() {
		$('#prices-table').off('click', '.remove-price').on('click', '.remove-price', function() {
			var $row = $(this).closest('tr');
			var idx = extractRowIndex($row);
			var id = $row.find('input[name$="[id]"]').val();
			if (id) {
				registerDeletedPrice(id);
			}
			$row.remove();
			lastRemovedIndex = idx;
			ensureAtLeastOneRow();
		});
	}

	function registerDeletedPrice(id) {
		var $container = $('#deleted-price-list-values');
		if ($container.find('input[value="' + id + '"]').length === 0) {
			$container.append('<input type="hidden" name="deleted_price_list_value_ids[]" value="' + id + '">');
		}
	}

	function ensureAtLeastOneRow() {
		if ($('#prices-table tbody tr').length === 0) {
			if (lastRemovedIndex !== null) {
				$.get("{{ route('Admin.Shop.PriceListValues.addPrice') }}/" + lastRemovedIndex, function(data) {
					$("#prices-table tbody").append(data);
					handlePrices();
					handleRemovePrice();
				});
			} else {
				addEmptyPriceRow();
			}
		}
	}

	function computeStartingIndex() {
		var maxIndex = -1;
		$('#prices-table tbody tr').each(function() {
			var $idInput = $(this).find('input[name$="[id]"]');
			var name = $idInput.attr('name');
			if (name) {
				var matches = name.match(/price_list_values\[(\d+)\]\[id\]/);
				if (matches && matches[1]) {
					var idx = parseInt(matches[1], 10);
					if (!isNaN(idx) && idx > maxIndex) {
						maxIndex = idx;
					}
				}
			}
		});

		return maxIndex + 1;
	}

	function nextPriceRowIndex() {
		return priceRowIndex++;
	}

	function extractRowIndex($row) {
		var $idInput = $row.find('input[name$="[id]"]');
		var name = $idInput.attr('name');
		if (!name) {
			return priceRowIndex;
		}

		var matches = name.match(/price_list_values\[(\d+)\]\[id\]/);

		return matches && matches[1] ? parseInt(matches[1], 10) : priceRowIndex;
	}

	$(function() {
		priceRowIndex = computeStartingIndex();
		handleAddPrice();
		handlePrices();
		handleRemovePrice();
		ensureAtLeastOneRow();
	});

</script>
