

<?php $__env->startSection('styles'); ?>
	<!-- FLATPICKR CSS -->
	<link rel="stylesheet" href="<?php echo e(asset('assets/libs/flatpickr/flatpickr.min.css')); ?>">
	<!-- TOM SELECT CSS -->
	<link rel="stylesheet" href="<?php echo e(asset('assets/libs/tom-select/css/tom-select.default.min.css')); ?>">
	<style>
		/* Hide anything marked x-cloak until Alpine is initialized */
		[x-cloak] {
			display: none !important;
		}
	</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
	<div class="content">
		<div class="main-content">
			<div class="block justify-between page-header sm:flex">
				<h3 class="text-2xl font-medium text-gray-700 dark:text-white">
					Nova polisa
				</h3>
				<ol class="flex items-center space-x-2">
					<?php if($entity->entityable_type === 'App\Models\CRM\Company'): ?>
						<a href="<?php echo e(route('crm.companies.edit', $entity->entityable)); ?>" class="ti-btn ti-btn-outline-secondary">
							Profil klijenta
						</a>
					<?php else: ?>
						<a href="<?php echo e(route('crm.individuals.edit', $entity->entityable)); ?>" class="ti-btn ti-btn-outline-secondary">
							Profil klijenta
						</a>
					<?php endif; ?>
					<a href="<?php echo e(route('osiguranje.insurance-policies.index', $entity)); ?>" class="ti-btn ti-btn-outline-secondary">
						Polise klijenta
					</a>
				</ol>
			</div>

			<div class="md:grid md:grid-cols-2 gap-4 space-y-4 md:space-y-0">
				<form action="<?php echo e(route('osiguranje.insurance-policies.store', $entity)); ?>" method="POST">
					<?php echo csrf_field(); ?>

					<div class="box mb-0">
						<div class="box-header flex items-center justify-between !py-1">
							<div class="box-title !py-0 !my-0">
								Broj polise
							</div>

							<input type="text" hidden name="status" value="active" />

							<input type="text"
								class="ti-form-input !py-0 !px-2 h-8 mr-2 text-sm leading-none max-w-xs <?php $__errorArgs = ['policy_number'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
								placeholder="Broj polise <?php $__errorArgs = ['policy_number'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> <?php echo e($message); ?> <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" name="policy_number"
								value="<?php echo e(old('policy_number')); ?>" />

							<button class="ti-btn ti-btn-soft-success !py-0 !px-2 h-8 text-sm leading-none">
								<?php echo e(__('forms.Save')); ?>

							</button>
						</div>

						<div class="box-body pb-4">

							
							<div x-data="commissionFetcher()" x-init="initTom();
	
	// 1) seed the insurer dropdown
	insurerId = '<?php echo e(old('insurer_id')); ?>';
	
	// 2) if we had an old insurer, fetch its defaults
	if (insurerId) {
	    fetchDefaults().then(() => {
	        // 3) after defaults are loaded, re-select old commission_default_id
	        <?php if(old('commission_default_id')): ?>
	        tom.setValue('<?php echo e(old('commission_default_id')); ?>');
	        <?php endif; ?>
	    });
	}" class="space-y-4">

								
								<div>
									<label for="insurer_select" class="block text-sm font-medium">
										<?php $__errorArgs = ['insurer_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
											<?php echo e($message); ?>

										<?php else: ?>
											Izbor osiguravača
										<?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
									</label>
									<select id="insurer_select" x-model="insurerId" @change="fetchDefaults()"
										class="mt-1 block w-full py-2 px-3 ti-form-select <?php $__errorArgs = ['insurer_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
										name="insurer_id">
										<option value="">— Izaberi —</option>
										<?php $__currentLoopData = $insurers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $insurer): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
											<option value="<?php echo e($insurer->id); ?>" <?php echo e(old('insurer_id') == $insurer->id ? 'selected' : ''); ?>>
												<?php echo e($insurer->short_name); ?>

											</option>
										<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
									</select>
								</div>

								
								<div>
									<label for="commission_default_id" class="block text-sm font-medium mb-1">
										<?php $__errorArgs = ['commission_default_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
											<?php echo e($message); ?>

										<?php else: ?>
											Izbor vrste osiguranja
										<?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
									</label>
									<select x-cloak  x-ref="commissionSelect" x-model="selectedDefault" :disabled="loading"
										autocomplete="off" name="commission_default_id"
										class="ti-form-select
										<?php $__errorArgs = ['commission_default_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
										border border-red-500 focus:border-red-500
										<?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
									"></select>
								</div>
								<div class="grid lg:grid-cols-2 gap-6 space-y-4 lg:space-y-0">
									<div class="space-y-2">
										<label for="insured_amount" class="block text-sm font-medium mb-1">
											Osigurana suma <?php $__errorArgs = ['insured_amount'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
												<?php echo e($message); ?>

											<?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
										</label>
										<input type="text" class="my-auto ti-form-input <?php $__errorArgs = ['insured_amount'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
											placeholder="Osigurana suma" name="insured_amount" value="<?php echo e(old('insured_amount')); ?>">
									</div>
									<div class="space-y-2">
										<label for="premium" class="block text-sm font-medium mb-1">
											Premija osiguranja <?php $__errorArgs = ['premium'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
												<?php echo e($message); ?>

											<?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
										</label>
										<input type="text" class="my-auto ti-form-input <?php $__errorArgs = ['premium'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
											placeholder="Premija osiguranja" name="premium" value="<?php echo e(old('premium')); ?>">
									</div>

									<div class="flex rounded-sm shadow-sm">
										<div
											class="px-2 inline-flex items-center min-w-fit ltr:rounded-l-sm rtl:rounded-r-sm border ltr:border-r-0 rtl:border-l-0 border-gray-200 bg-gray-50 dark:bg-black/20 dark:border-white/10 <?php $__errorArgs = ['start_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>">
											<span class="text-xl text-gray-500 dark:text-white/70"><i class="ti ti-player-play"></i></span>
										</div>

										<input type="text"
											class="ti-form-input rounded-l-none focus:z-10 flatpickr-input <?php $__errorArgs = ['start_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
											id="start_date" name="start_date" value="<?php echo e(old('start_date')); ?>"
											placeholder="Početak osiguranja <?php $__errorArgs = ['start_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><?php echo e($message); ?> <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" readonly>
									</div>
									<div class="flex rounded-sm shadow-sm">
										<div
											class="px-2 inline-flex items-center min-w-fit ltr:rounded-l-sm rtl:rounded-r-sm border ltr:border-r-0 rtl:border-l-0 border-gray-200 bg-gray-50 dark:bg-black/20 dark:border-white/10 <?php $__errorArgs = ['start_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>">
											<span class="text-xl text-gray-500 dark:text-white/70"><i class="ti ti-player-stop"></i></span>
										</div>

										<input type="text" id="end_date" name="end_date"
											value="<?php echo e($errors->has('end_date') ? '' : old('end_date')); ?>"
											<?php $__errorArgs = ['end_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
												placeholder="<?php echo e($message); ?>"
											<?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
											placeholder="Kraj osiguranja" readonly
											class="ti-form-input rounded-l-none focus:z-10 flatpickr-input
													<?php echo e($errors->has('end_date') ? 'border border-red-500 focus:border-red-500' : ''); ?>">
									</div>
								</div>
							</div>
						</div>
					</div>
				</form>
				
				<?php if($entity->entityable_type == 'App\Models\CRM\Company'): ?>
					<?php echo $__env->make('backend.insurance.insurance-policies.boxes.company', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
				<?php else: ?>
					<?php echo $__env->make('backend.insurance.insurance-policies.boxes.individual', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
				<?php endif; ?>

			</div>
		</div>
	</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
	<script src="<?php echo e(asset('assets/libs/flatpickr/flatpickr.min.js')); ?>"></script>

	<script>
		document.addEventListener('DOMContentLoaded', function() {
			// basic single-date pickers
			flatpickr('#start_date', {
				dateFormat: 'Y-m-d',
				// you can set minDate, maxDate, locale, etc here
			});

			flatpickr('#end_date', {
				dateFormat: 'Y-m-d',
				// e.g. disallow selecting before the start date
				onOpen: function(selectedDates, dateStr, instance) {
					const start = document.querySelector('#start_date')._flatpickr.selectedDates[0];
					if (start) {
						instance.set('minDate', start);
					}
				}
			});
		});
	</script>

	<!-- Alpine -->
	<script src="//unpkg.com/alpinejs" defer></script>

	<!-- 1) expose route URL -->
	<script>
		window.commissionDefaultsUrl = <?php echo json_encode(url('_cp/insurers/{insurer}/commission-defaults'), 15, 512) ?>;
	</script>

	<!-- 2) TomSelect JS -->
	<script src="<?php echo e(asset('assets/libs/tom-select/js/tom-select.complete.min.js')); ?>"></script>

	<!-- 3) Alpine component + TomSelect integration -->
	<script>
		function commissionFetcher() {
		return {
			insurerId: '',
			defaults: [],
			selectedDefault: null,
			loading: false,
			tom: null,

			initTom() {
			// 1) remove the raw select styling
			this.$refs.commissionSelect.classList.remove('ti-form-select');

			// 2) init TomSelect
			this.tom = new TomSelect(this.$refs.commissionSelect, {
				create: false,
				sortField: { field: "text", direction: "asc" },
				allowEmptyOption: true,
			});

			// 3) strip inherited class off the wrapper
			this.tom.wrapper.classList.remove('ti-form-select');

			// 4) highlight on validation error
			<?php $__errorArgs = ['commission_default_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
				this.tom.wrapper.classList.add('border','rounded-sm','border-red-500','focus:border-red-500');
			<?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>

			// pin full width & disable until loaded
			this.pinWidth();
			this.tom.disable();

			// helper to decide which placeholder to show
			const applyPlaceholder = () => {
				if (this.defaults.length === 0) {
				// no defaults loaded
				this.tom.control_input.setAttribute(
					'placeholder',
					'Nema dostupnih podrazumevanih provizija'
				);
				} else if (!this.selectedDefault) {
				// defaults exist but none picked yet
				this.tom.control_input.setAttribute(
					'placeholder',
					'kucajte da biste pretražili…'
				);
				}
			};

			// re‑apply on blur, focus, or any click
			this.tom.on('blur',  applyPlaceholder);
			this.tom.on('focus', applyPlaceholder);
			document.addEventListener('click', applyPlaceholder);

			// once a user picks one, clear placeholder so the selected item shows
			this.tom.on('item_add', () => {
				this.tom.control_input.removeAttribute('placeholder');
			});
			},

			async fetchDefaults() {
			this.loading = true;

			// fully clear prior selection & options
			this.tom.clear();
			this.tom.clearOptions();
			this.selectedDefault = null;

			if (!this.insurerId) {
				this.tom.disable();
				this.tom.control_input.removeAttribute('placeholder');
				this.loading = false;
				return;
			}

			try {
				const url = window.commissionDefaultsUrl.replace('{insurer}', this.insurerId);
				const res = await fetch(url, {
				headers: {
					'X-Requested-With':'XMLHttpRequest',
					'Accept':'application/json',
				}
				});
				if (!res.ok) throw new Error('Network error');

				this.defaults = await res.json();

				if (this.defaults.length) {
				// populate with real defaults
				this.defaults.forEach(d => {
					this.tom.addOption({
					value: d.id,
					text: `${d.type_name} — ${d.commission_rate}%`
					});
				});
				this.tom.refreshOptions(false);
				this.tom.enable();

				// set & lock in the “search…” placeholder
				this.tom.control_input.setAttribute(
					'placeholder',
					'kucajte da biste pretražili…'
				);
				this.tom.control_input.blur();
				} else {
				// no defaults for this insurer
				this.tom.refreshOptions(false);
				this.tom.disable();
				this.tom.control_input.setAttribute(
					'placeholder',
					'Nema dostupnih podrazumevanih provizija'
				);
				this.tom.control_input.blur();
				}
			} catch (e) {
				console.error(e);
				this.tom.control_input.setAttribute(
				'placeholder',
				'Greška pri učitavanju provizija'
				);
				this.tom.disable();
			} finally {
				this.pinWidth();
				this.loading = false;
			}
			},

			pinWidth() {
			const { wrapper, dropdown } = this.tom;
			if (wrapper) {
				wrapper.style.width = '100%';
				wrapper.style.minWidth = '100%';
			}
			if (dropdown) {
				dropdown.style.width = '100%';
				dropdown.style.minWidth = '100%';
			}
			}
		}
		}


	</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('backend.layouts.master', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\development\www\policypilot\resources\views/backend/insurance/insurance-policies/create.blade.php ENDPATH**/ ?>