

<?php $__env->startSection('title', 'Add Advance'); ?>
<?php $__env->startSection('heading', 'Add Salary Advance'); ?>

<?php $__env->startSection('content'); ?>
<?php echo $__env->make('finance.top-submenu', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
    <?php if (isset($component)) { $__componentOriginal53747ceb358d30c0105769f8471417f6 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal53747ceb358d30c0105769f8471417f6 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.card','data' => ['class' => 'max-w-4xl']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('card'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['class' => 'max-w-4xl']); ?>
        <p class="mb-6 text-sm text-slate-600">
            Record when an employee receives a salary advance and how it will be recovered through monthly payroll deductions.
        </p>

        <form
            action="<?php echo e(route('pre-payments.store')); ?>"
            method="post"
            class="space-y-6"
            x-data="advanceForm({
                advanceDate: <?php echo \Illuminate\Support\Js::from(old('advance_date', now()->toDateString()))->toHtml() ?>,
                amount: <?php echo \Illuminate\Support\Js::from(old('amount', ''))->toHtml() ?>,
                installments: <?php echo \Illuminate\Support\Js::from((int) old('installments', 1))->toHtml() ?>,
                startMonth: <?php echo \Illuminate\Support\Js::from((int) old('deduction_start_month', $defaultStart['month']))->toHtml() ?>,
                startYear: <?php echo \Illuminate\Support\Js::from((int) old('deduction_start_year', $defaultStart['year']))->toHtml() ?>,
                options: <?php echo \Illuminate\Support\Js::from($installmentOptions)->toHtml() ?>,
            })"
            @submit="syncDeductionStart"
        >
            <?php echo csrf_field(); ?>

            <div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                <div>
                    <label class="block text-sm font-medium text-slate-700">Employee</label>
                    <select name="user_id" required class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm js-select2 js-select2-search">
                        <option value="">Select employee</option>
                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__currentLoopData = $employees; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $employee): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($employee->id); ?>" <?php echo e((int) old('user_id') === (int) $employee->id ? 'selected' : ''); ?>><?php echo e($employee->name); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                    </select>
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__errorArgs = ['user_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><p class="mt-1 text-sm text-red-600"><?php echo e($message); ?></p><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700">Advance given on</label>
                    <input
                        type="date"
                        name="advance_date"
                        x-model="advanceDate"
                        @change="onAdvanceDateChange"
                        required
                        class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
                    >
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__errorArgs = ['advance_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><p class="mt-1 text-sm text-red-600"><?php echo e($message); ?></p><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                </div>
            </div>

            <div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                <div>
                    <label class="block text-sm font-medium text-slate-700">Total advance amount</label>
                    <input
                        type="number"
                        step="0.01"
                        min="0.01"
                        name="amount"
                        x-model="amount"
                        required
                        placeholder="e.g. 30000"
                        class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
                    >
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__errorArgs = ['amount'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><p class="mt-1 text-sm text-red-600"><?php echo e($message); ?></p><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700">Repay in installments</label>
                    <select
                        name="installments"
                        x-model.number="installments"
                        @change="installments = parseInt($event.target.value, 10)"
                        required
                        class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm js-select2"
                    >
                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__currentLoopData = $installmentOptions; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $option): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($option); ?>">
                                <?php echo e($option === 1 ? '1 month (single deduction)' : $option . ' months'); ?>

                            </option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                    </select>
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__errorArgs = ['installments'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><p class="mt-1 text-sm text-red-600"><?php echo e($message); ?></p><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                </div>
            </div>

            <div class="rounded-lg border border-slate-200 bg-slate-50 p-4">
                <h3 class="text-sm font-semibold text-slate-800">First payroll deduction</h3>
                <p class="mt-1 text-xs text-slate-500">Monthly repayments start from this payroll month (defaults to the month after the advance date).</p>
                <div class="mt-3 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                    <div>
                        <label class="block text-sm font-medium text-slate-700">Month</label>
                        <select
                            name="deduction_start_month"
                            x-model.number="startMonth"
                            @change="startMonth = parseInt($event.target.value, 10)"
                            required
                            class="mt-1 w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm js-select2"
                        >
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php for($m = 1; $m <= 12; $m++): ?>
                                <option value="<?php echo e($m); ?>"><?php echo e(date('F', mktime(0, 0, 0, $m, 1))); ?></option>
                            <?php endfor; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                        </select>
                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__errorArgs = ['deduction_start_month'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><p class="mt-1 text-sm text-red-600"><?php echo e($message); ?></p><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-slate-700">Year</label>
                        <input type="number" name="deduction_start_year" x-model.number="startYear" required class="mt-1 w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm">
                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__errorArgs = ['deduction_start_year'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><p class="mt-1 text-sm text-red-600"><?php echo e($message); ?></p><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                    </div>
                </div>
            </div>

            <div>
                <label class="block text-sm font-medium text-slate-700">Notes</label>
                <textarea name="notes" rows="2" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" placeholder="Optional reason or reference"><?php echo e(old('notes')); ?></textarea>
            </div>

            <div class="rounded-lg border border-primary/20 bg-primary/5 p-4" x-show="schedule.length" x-cloak>
                <h3 class="text-sm font-semibold text-slate-800">Repayment schedule</h3>
                <p class="mt-1 text-xs text-slate-500" x-text="scheduleSummary"></p>
                <div class="mt-3 overflow-x-auto">
                    <table class="min-w-full text-sm">
                        <thead>
                            <tr class="text-left text-xs uppercase tracking-wide text-slate-500">
                                <th class="pb-2 pr-4">#</th>
                                <th class="pb-2 pr-4">Payroll month</th>
                                <th class="pb-2">Deduction</th>
                            </tr>
                        </thead>
                        <tbody>
                            <template x-for="row in schedule" :key="row.installment_number">
                                <tr class="border-t border-slate-200/80">
                                    <td class="py-2 pr-4 text-slate-600" x-text="row.installment_number"></td>
                                    <td class="py-2 pr-4 text-slate-900" x-text="row.period_label"></td>
                                    <td class="py-2 font-medium text-slate-900" x-text="formatMoney(row.amount)"></td>
                                </tr>
                            </template>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="flex gap-2">
                <button type="submit" class="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-white">Save advance</button>
                <a href="<?php echo e(route('pre-payments.index')); ?>" class="rounded-lg bg-slate-100 px-4 py-2 text-sm font-medium text-slate-700">Cancel</a>
            </div>
        </form>
     <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal53747ceb358d30c0105769f8471417f6)): ?>
<?php $attributes = $__attributesOriginal53747ceb358d30c0105769f8471417f6; ?>
<?php unset($__attributesOriginal53747ceb358d30c0105769f8471417f6); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal53747ceb358d30c0105769f8471417f6)): ?>
<?php $component = $__componentOriginal53747ceb358d30c0105769f8471417f6; ?>
<?php unset($__componentOriginal53747ceb358d30c0105769f8471417f6); ?>
<?php endif; ?>

    <script>
        function advanceForm(config) {
            const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

            return {
                advanceDate: config.advanceDate,
                amount: config.amount,
                installments: config.installments,
                startMonth: config.startMonth,
                startYear: config.startYear,
                options: config.options,

                get schedule() {
                    const total = parseFloat(this.amount);
                    const count = parseInt(this.installments, 10);
                    const month = parseInt(this.startMonth, 10);
                    const year = parseInt(this.startYear, 10);

                    if (!total || total <= 0 || !count || !month || !year) {
                        return [];
                    }

                    const base = Math.floor((total / count) * 100) / 100;
                    const amounts = Array(count).fill(base);
                    amounts[count - 1] = Math.round((total - (base * (count - 1))) * 100) / 100;

                    const rows = [];
                    let cursorMonth = month;
                    let cursorYear = year;

                    for (let i = 0; i < count; i++) {
                        rows.push({
                            installment_number: i + 1,
                            amount: amounts[i],
                            period_label: `${monthNames[cursorMonth - 1]} ${cursorYear}`,
                        });

                        cursorMonth++;
                        if (cursorMonth > 12) {
                            cursorMonth = 1;
                            cursorYear++;
                        }
                    }

                    return rows;
                },

                get scheduleSummary() {
                    if (!this.schedule.length) {
                        return '';
                    }

                    const total = parseFloat(this.amount) || 0;
                    const per = this.schedule[0]?.amount || 0;

                    if (Number(this.installments) === 1) {
                        return `One deduction of ${this.formatMoney(total)} in ${this.schedule[0].period_label}.`;
                    }

                    return `${this.installments} monthly deductions of about ${this.formatMoney(per)} each (total ${this.formatMoney(total)}).`;
                },

                formatMoney(value) {
                    return new Intl.NumberFormat(undefined, {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2,
                    }).format(value);
                },

                onAdvanceDateChange() {
                    if (!this.advanceDate) {
                        return;
                    }

                    const date = new Date(this.advanceDate + 'T00:00:00');
                    date.setMonth(date.getMonth() + 1);

                    this.startMonth = date.getMonth() + 1;
                    this.startYear = date.getFullYear();
                },

                syncDeductionStart() {
                    // Ensure Alpine-bound values are submitted even if the browser caches old selects.
                },
            };
        }
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /var/www/html/kiyohr/v2_version/resources/views/pre-payments/create.blade.php ENDPATH**/ ?>