@extends('layouts.app')

@section('title', 'Add Advance')
@section('heading', 'Add Salary Advance')

@section('content')
@include('finance.top-submenu')
    <x-card 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="{{ route('pre-payments.store') }}"
            method="post"
            class="space-y-6"
            x-data="advanceForm({
                advanceDate: @js(old('advance_date', now()->toDateString())),
                amount: @js(old('amount', '')),
                installments: @js((int) old('installments', 1)),
                startMonth: @js((int) old('deduction_start_month', $defaultStart['month'])),
                startYear: @js((int) old('deduction_start_year', $defaultStart['year'])),
                options: @js($installmentOptions),
            })"
            @submit="syncDeductionStart"
        >
            @csrf

            <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>
                        @foreach($employees as $employee)
                            <option value="{{ $employee->id }}" {{ (int) old('user_id') === (int) $employee->id ? 'selected' : '' }}>{{ $employee->name }}</option>
                        @endforeach
                    </select>
                    @error('user_id')<p class="mt-1 text-sm text-red-600">{{ $message }}</p>@enderror
                </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"
                    >
                    @error('advance_date')<p class="mt-1 text-sm text-red-600">{{ $message }}</p>@enderror
                </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"
                    >
                    @error('amount')<p class="mt-1 text-sm text-red-600">{{ $message }}</p>@enderror
                </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"
                    >
                        @foreach($installmentOptions as $option)
                            <option value="{{ $option }}">
                                {{ $option === 1 ? '1 month (single deduction)' : $option . ' months' }}
                            </option>
                        @endforeach
                    </select>
                    @error('installments')<p class="mt-1 text-sm text-red-600">{{ $message }}</p>@enderror
                </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"
                        >
                            @for($m = 1; $m <= 12; $m++)
                                <option value="{{ $m }}">{{ date('F', mktime(0, 0, 0, $m, 1)) }}</option>
                            @endfor
                        </select>
                        @error('deduction_start_month')<p class="mt-1 text-sm text-red-600">{{ $message }}</p>@enderror
                    </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">
                        @error('deduction_start_year')<p class="mt-1 text-sm text-red-600">{{ $message }}</p>@enderror
                    </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">{{ 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="{{ 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>
    </x-card>

    <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>
@endsection
