@extends('layouts.master')

@section('content')

    <h2 class="mb-3">
        Add Service Voucher
        <a href="{{ route('service_vouchers.index') }}" class="btn btn-secondary float-end">
            Back
        </a>
    </h2>

    <form method="POST" action="{{ route('service_vouchers.store') }}">
        @csrf
        @if ($errors->any())
            <div class="alert alert-danger">
                <strong>Whoops! Something went wrong:</strong>
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
        {{-- MASTER --}}
        <div class="card mb-3">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3">
                        <label>Voucher Date *</label>
                        <input type="date" name="voucher_date" class="form-control" value="{{ date('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">
                    </div>

                    <div class="col-md-3">
                        <label>Bill No</label>
                        <input type="text" name="bill_no" class="form-control">
                    </div>
                </div>

                <div class="mt-2">
                    <label>Description</label>
                    <textarea name="description" class="form-control"></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="10%">Unit</th>
                            <th width="15%">Price *</th>
                            <th width="15%">Amount</th>
                            <th>Narration</th>
                            <th width="5%">❌</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>
                                <select name="details[0][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[0][qty]"
                                    class="form-control qty" required>
                            </td>
                            <td>
                                {{-- <input type="text" name="details[0][unit]" class="form-control"> --}}
                                <select name="details[0][unit]" class="form-control select2" required>
                                    <option value="">Select Unit</option>
                                    @foreach ($units as $unit)
                                        <option value="{{ $unit->measurement_unit_name }}">
                                            {{ $unit->measurement_unit_name }}</option>
                                    @endforeach
                                </select>
                            </td>
                            <td>
                                <input type="number" step="0.01" name="details[0][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[0][narration]" class="form-control">
                            </td>
                            <td class="text-center">
                                <button type="button" class="btn btn-danger btn-sm removeRow">×</button>
                            </td>
                        </tr>
                    </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>
                    </div>
                </div>
            </div>
        </div>

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

    </form>

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

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

            let rowIndex = 1;

            // 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 }}">{{ $acc->control_account_name }}</option>
                    @endforeach
                </select>
            </td>
            <td><input type="number" step="0.01" 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
            $(document).on('click', '.removeRow', function() {
                $(this).closest('tr').remove();
                calculateTotal();
            });

            // CALCULATE ROW & 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
