@extends('layouts.master')

@section('content')
    <h2 class="mb-3">
        Edit Service Voucher
        <span class="badge bg-secondary ms-2" style="font-size: 0.75rem;">{{ $voucher->voucher_no }}</span>
        <a href="{{ route('service_vouchers.index') }}" class="btn btn-secondary float-end">
            Back
        </a>
    </h2>

    <form method="POST" action="{{ route('service_vouchers.update', encrypt($voucher->id)) }}">
        @csrf
        @method('PUT')

        {{-- MASTER --}}
        <div class="card mb-3">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3">
                        <label>Voucher No</label>
                        <input type="text" class="form-control" value="{{ $voucher->voucher_no }}" readonly disabled>
                    </div>

                    <div class="col-md-3">
                        <label>Voucher Date *</label>
                        <input type="date" name="voucher_date" class="form-control"
                            value="{{ \Carbon\Carbon::parse($voucher->voucher_date)->format('Y-m-d') }}" required>
                    </div>

                    <div class="col-md-3">
                        <label>Supplier / Purchaser *</label>
                        <select id="partySelect" class="form-control select2" required>
                            <option value="">Select Party</option>
                            @foreach ($parties as $party)
                                <option value="{{ $party['type'] }}|{{ $party['id'] }}" {{-- for edit view: --}}
                                    {{ isset($voucher) && $voucher->party_type === $party['type'] && $voucher->party_id == $party['id'] ? 'selected' : '' }}>
                                    [{{ $party['type'] }}] {{ $party['display_name'] }}
                                </option>
                            @endforeach
                        </select>

                        {{-- These two get submitted with the form --}}
                        <input type="hidden" name="party_type" id="partyType"
                            value="{{ isset($voucher) ? $voucher->party_type : '' }}">
                        <input type="hidden" name="party_id" id="partyId"
                            value="{{ isset($voucher) ? $voucher->party_id : '' }}">
                    </div>
                    <div class="col-md-3">
                        <label>Truck No</label>
                        <input type="text" name="truck_no" class="form-control"
                            value="{{ old('truck_no', $voucher->truck_no) }}">
                    </div>
                </div>

                <div class="row mt-2">
                    <div class="col-md-3">
                        <label>Bill No</label>
                        <input type="text" name="bill_no" class="form-control"
                            value="{{ old('bill_no', $voucher->bill_no) }}">
                    </div>
                </div>

                <div class="mt-2">
                    <label>Description</label>
                    <textarea name="description" class="form-control">{{ old('description', $voucher->description) }}</textarea>
                </div>
            </div>
        </div>

        {{-- DETAILS --}}
        <div class="card">
            <div class="card-body">
                <h5>Service Details</h5>

                <table class="table table-bordered" id="detailsTable">
                    <thead>
                        <tr>
                            <th>Account *</th>
                            <th width="10%">Qty *</th>
                            <th width="12%">Unit *</th>
                            <th width="15%">Price *</th>
                            <th width="15%">Amount</th>
                            <th>Narration</th>
                            <th width="5%">❌</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($voucher->details as $i => $detail)
                            <tr>
                                <td>
                                    <select name="details[{{ $i }}][control_account_id]"
                                        class="form-control select2" required>
                                        <option value="">Select Account</option>
                                        @foreach ($accounts as $acc)
                                            <option value="{{ $acc->id_control_account }}"
                                                {{ $detail->control_account_id == $acc->id_control_account ? 'selected' : '' }}>
                                                {{ $acc->control_account_name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </td>
                                <td>
                                    <input type="number" step="1" min="1"
                                        name="details[{{ $i }}][qty]" class="form-control qty"
                                        value="{{ $detail->qty }}" required>
                                </td>
                                <td>
                                    <select name="details[{{ $i }}][unit]" class="form-control select2"
                                        required>
                                        <option value="">Select Unit</option>
                                        @foreach ($units as $unit)
                                            <option value="{{ $unit->measurement_unit_name }}"
                                                {{ $detail->unit == $unit->measurement_unit_name ? 'selected' : '' }}>
                                                {{ $unit->measurement_unit_name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </td>
                                <td>
                                    <input type="number" step="0.01" name="details[{{ $i }}][price]"
                                        class="form-control price" value="{{ $detail->price }}" required>
                                </td>
                                <td>
                                    <input type="number" step="0.01" class="form-control amount"
                                        value="{{ $detail->amount }}" readonly>
                                </td>
                                <td>
                                    <input type="text" name="details[{{ $i }}][narration]"
                                        class="form-control" value="{{ $detail->narration }}">
                                </td>
                                <td class="text-center">
                                    <button type="button" class="btn btn-danger btn-sm removeRow">×</button>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>

                <button type="button" id="addRow" class="btn btn-success btn-sm">
                    + Add Row
                </button>

                <div class="row mt-3">
                    <div class="col-md-3 offset-md-9">
                        <label>Total Amount</label>
                        <input type="text" id="grandTotal" class="form-control" readonly
                            value="{{ number_format($voucher->total_amount, 2) }}">
                    </div>
                </div>
            </div>
        </div>

        <button type="submit" class="btn btn-primary mt-3 float-end">
            Update Voucher
        </button>

    </form>
@endsection

@push('scripts')
    <script>
        $(document).ready(function() {

            $('.select2').select2();

            // Start index after existing rows
            let rowIndex = {{ $voucher->details->count() }};

            // Recalculate total on page load
            calculateTotal();

            // ADD ROW
            $('#addRow').click(function() {
                let row = `
        <tr>
            <td>
                <select name="details[${rowIndex}][control_account_id]" class="form-control select2" required>
                    <option value="">Select Account</option>
                    @foreach ($accounts as $acc)
                        <option value="{{ $acc->id_control_account }}">{{ $acc->control_account_name }}</option>
                    @endforeach
                </select>
            </td>
            <td>
                <input type="number" step="1" min="1" name="details[${rowIndex}][qty]" class="form-control qty" required>
            </td>
            <td>
                <select name="details[${rowIndex}][unit]" class="form-control select2" required>
                    <option value="">Select Unit</option>
                    @foreach ($units as $unit)
                        <option value="{{ $unit->id_measurement_unit }}">{{ $unit->measurement_unit_name }}</option>
                    @endforeach
                </select>
            </td>
            <td>
                <input type="number" step="0.01" name="details[${rowIndex}][price]" class="form-control price" required>
            </td>
            <td>
                <input type="number" step="0.01" class="form-control amount" readonly>
            </td>
            <td>
                <input type="text" name="details[${rowIndex}][narration]" class="form-control">
            </td>
            <td class="text-center">
                <button type="button" class="btn btn-danger btn-sm removeRow">×</button>
            </td>
        </tr>`;

                $('#detailsTable tbody').append(row);
                $('.select2').select2();
                rowIndex++;
            });

            // REMOVE ROW (prevent removing last row)
            $(document).on('click', '.removeRow', function() {
                if ($('#detailsTable tbody tr').length === 1) {
                    alert('At least one detail row is required.');
                    return;
                }
                $(this).closest('tr').remove();
                calculateTotal();
            });

            // CALCULATE ROW AMOUNT & GRAND TOTAL
            $(document).on('input', '.qty, .price', function() {
                let row = $(this).closest('tr');
                let qty = parseFloat(row.find('.qty').val()) || 0;
                let price = parseFloat(row.find('.price').val()) || 0;
                row.find('.amount').val((qty * price).toFixed(2));
                calculateTotal();
            });

            function calculateTotal() {
                let total = 0;
                $('.amount').each(function() {
                    total += parseFloat($(this).val()) || 0;
                });
                $('#grandTotal').val(total.toFixed(2));
            }
            $('#partySelect').on('change', function() {
                const parts = $(this).val().split('|');
                $('#partyType').val(parts[0] ?? '');
                $('#partyId').val(parts[1] ?? '');
            });
        });
    </script>
@endpush
