@extends('layouts.master')

@section('content')
    <style>
        body {
            /*zoom: 90%;*/
            background-color: #f5f7fa;
        }

        .card {
            border-radius: 12px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
            border: 1px solid #e3e6ef;
            background-color: #fff;
        }

        .card-title {
            font-weight: 600;
            font-size: 18px;
            color: #2b354f;
            margin-bottom: 15px;
        }

        .form-control {
            border-radius: 8px;
            border-color: #d0d5dd;
            font-size: 14px;
        }

        .form-control:focus {
            border-color: #66c2a5;
            box-shadow: 0 0 0 0.1rem rgba(102, 194, 165, 0.25);
        }

        label.form-label {
            font-weight: 500;
            color: #495057;
        }

        .table {
            border-radius: 8px;
            overflow: hidden;
        }

        .btn {
            border-radius: 6px;
            font-weight: 500;
        }

        .btn-primary {
            background-color: #28a745;
            border-color: #28a745;
        }

        .btn-primary:hover {
            background-color: #218838;
            border-color: #1e7e34;
        }

        .az-content-breadcrumb {
            font-size: 14px;
            padding: 10px 0 5px;
            color: #666;
        }

        .az-content-title {
            font-size: 24px;
            font-weight: 700;
            color: #1a1a1a;
            margin-bottom: 20px;
        }

        .border-end {
            border-right: 1px solid #e9ecef;
        }

        .cheque-field:disabled {
            background-color: #f8f9fa;
            opacity: 0.8;
            cursor: not-allowed;
        }

        .table-bordered th,
        .table-bordered td {
            border-color: #dee2e6;
        }

        .table thead th {
            background-color: #f1f3f5;
            color: #495057;
            font-size: 14px;
            font-weight: 600;
        }
    </style>
    <div class="az-content-breadcrumb">
        <span> Payment Voucher</span>
        <span>Edit Payment Voucher</span>
    </div>
    <h2 class="az-content-title" style="display: inline">Edit Payment Voucher
        <span>
            <a href="{{ route('payment.list') }}" class="btn border" style="float: right">
                <i class="fa-solid fa-bars-staggered"></i> Back to Payment Voucher
            </a>
        </span>
    </h2>

    <div class="row">
        <div class="col-md-12 col-lg-12 col-xl-12">
            <div class="card card-body pd-40">
                <h5 class="card-title mg-b-20">Edit Payment Voucher</h5>
                <hr>
                <form id="myForm" method="post"
                    action="{{ route('payment_voucher.update', Crypt::encrypt($voucher->id_vouchers)) }}">
                    @csrf
                    @method('PUT')

                    @if ($errors->any())
                        <div class="p-1">
                            @foreach ($errors->all() as $error)
                                <div class="alert alert-warning alert-danger fade show" role="alert">{{ $error }}
                                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                                </div>
                            @endforeach
                        </div>
                    @endif
                    <input type="hidden" name="transaction_type" value="Debit">
                    <div class="row">
                        <div class="col-lg-4 mb-3">
                            <label for="voucher_date" class="form-label">Payment Voucher Date <span
                                    style="color:red;">*</span></label>
                            <input type="text" id="voucher_date" name="voucher_date" class="form-control"
                                value="{{ $voucher->voucher_date }}" readonly />
                        </div>

                        <div class="col-lg-4 mb-3">
                            <label for="voucher_rv_no" class="form-label">RV #</label>
                            <input type="text" id="voucher_rv_no" name="voucher_rv_no" class="form-control"
                                value="{{ $voucher->uniqueNumber->voucher_number }}" disabled />
                        </div>

                        <div class="col-lg-4 mb-3"></div>

                        <div class="col-lg-6 p-3 border-end">
                            <h5 class="card-title">Voucher Information</h5>

                            <div class="mb-2 text-center">
                                <label class="form-label d-block mb-2">Mode / موڈ <span style="color:red;">*</span></label>
                                <div class="d-flex justify-content-center">
                                    <div class="me-4 text-center">
                                        <input class="form-check-input" type="radio" id="cash" name="payment_mode"
                                            value="cash" {{ $voucher->payment_mode == 'cash' ? 'checked' : '' }} required>
                                        <label class="form-check-label" for="cash">Cash</label>
                                    </div>
                                    <div class="text-center">
                                        <input class="form-check-input" type="radio" id="bank" name="payment_mode"
                                            value="bank" {{ $voucher->payment_mode == 'bank' ? 'checked' : '' }} required>
                                        <label class="form-check-label" for="bank">Bank</label>
                                    </div>
                                </div>

                                <div class="mt-3">
                                    <select id="account_select" name="account" class="form-control select2"
                                        data-selected="{{ $voucher->account }}">
                                    </select>
                                </div>
                            </div>

                            <div class="my-2">
                                <label for="voucher_details" class="form-label">Details / تفصیلات <span
                                        style="color:red;">*</span></label>
                                <input type="text" id="voucher_details" name="voucher_details" class="form-control"
                                    value="{{ $voucher->voucher_details }}" />
                            </div>
                        </div>

                        <div class="col-lg-6 p-3">
                            <h5 class="card-title">Cheque Details</h5>
                            <div class="mb-3">
                                <label for="voucher_chqno" class="form-label">Chq. #</label>
                                <input type="text" id="voucher_chqno" name="voucher_chqno"
                                    class="form-control cheque-field" value="{{ $voucher->voucher_chqno }}">
                            </div>
                            <div class="mb-3">
                                <label for="voucher_chqdate" class="form-label">Chq. Date<span
                                        style="color:red;">*</span></label>
                                <input type="text" id="voucher_chqdate" name="voucher_chqdate"
                                    class="form-control cheque-field" value="{{ $voucher->voucher_chqdate }}" readonly>
                            </div>
                            <div class="mb-3">
                                <label for="voucher_depdate" class="form-label">Deposite Date<span
                                        style="color:red;">*</span></label>
                                <input type="text" id="voucher_depdate" name="voucher_depdate"
                                    class="form-control cheque-field" value="{{ $voucher->voucher_depdate }}" readonly>
                            </div>
                            <div class="mb-3">
                                <label for="voucher_depslipno" class="form-label">Deposite Slip #</label>
                                <input type="text" id="voucher_depslipno" name="voucher_depslipno"
                                    class="form-control cheque-field" value="{{ $voucher->voucher_depslipno }}">
                            </div>
                        </div>
                    </div>

                    <div class="row my-5 card p-3">
                        <h5 class="card-title">Voucher Details</h5>
                        <div class="col-12">
                            <table class="table table-hover table-bordered align-middle">
                                <thead class="table-light">
                                    <tr>
                                        <th>جمع کھاتہ</th>
                                        <th>رقم Debit</th>
                                        <th>Employee</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody id="itemsTableBody">
                                    @php $items = json_decode($voucher->adaegi_array, true) ?? []; @endphp
                                    @foreach ($items as $index => $item)
                                        <tr>
                                            <td>
                                                <select name="items[{{ $index }}][adaegi_khata]"
                                                    class="form-control supplier-select" style="width: 100%;">
                                                    <option value="{{ $item['adaegi_khata'] }}" selected>
                                                        {{ optional(\App\Suppliers::find($item['adaegi_khata']))->supplier_name ?? 'Suppliers ID #' . $item['adaegi_khata'] }}
                                                    </option>
                                                </select>
                                            </td>
                                            <td>
                                                <input type="text" name="items[{{ $index }}][credit_amount]"
                                                    class="form-control credit-amount"
                                                    value="{{ number_format($item['credit_amount']) }}"
                                                    placeholder="رقم Debit">
                                            </td>
                                            <td>
                                                <input type="text" name="items[{{ $index }}][employee]"
                                                    class="form-control" value="{{ $item['employee'] ?? '' }}">
                                            </td>
                                            <td>
                                                @if (!$loop->first)
                                                    <button type="button"
                                                        class="btn btn-danger btn-sm remove-row">Remove</button>
                                                @endif
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th class="text-end">Grand Total</th>
                                        <th>
                                            <input type="text" id="grandTotal" class="form-control text-end" readonly>
                                        </th>
                                        <th colspan="2"></th>
                                    </tr>
                                </tfoot>
                            </table>
                            <button type="button" id="addRowBtn" class="btn btn-primary mt-2">
                                <i class="fa fa-plus"></i> Add Row
                            </button>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-success btn-block mt-2 float-end" style="color:#fff;">
                        <i class="fa fa-save"></i> Update
                    </button>
                </form>
            </div>
        </div>
    </div>
@endsection
@push('scripts')
    <script>
        function updateAccountDropdown(method) {
            $.ajax({
                url: '{{ route('get-transaction-accounts') }}',
                type: 'GET',
                data: {
                    type: method
                },
                dataType: 'json',
                success: function(data) {
                    const $accountSelect = $('#account_select');
                    const currentValue = $accountSelect.data('selected');

                    $accountSelect.empty();

                    $.each(data, function(key, value) {
                        const selected = key == currentValue ? 'selected' : '';
                        $accountSelect.append(
                            `<option value="${key}" ${selected}>${key} | ${value}</option>`);
                    });

                    $accountSelect.trigger('change'); // Reflect selection in UI
                },
                error: function(xhr) {
                    alert("Error loading accounts: " + xhr.responseText);
                }
            });
        }

        function formatNumberWithCommas(x) {
            const parts = x.toString().replace(/,/g, '').split('.');
            parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
            return parts.join('.');
        }

        function stripCommas(value) {
            return value.replace(/,/g, '');
        }

        function initCustomerSelect(selector) {
            $(selector).select2({
                placeholder: 'Search supplier',
                minimumInputLength: 0,
                ajax: {
                    url: '{{ url('get-supplier-data') }}',
                    dataType: 'json',
                    delay: 250,
                    data: params => ({
                        query: params.term || ''
                    }),
                    processResults: data => ({
                        results: data
                    })
                }
            }).on('select2:open', () => {
                $('.select2-search__field').trigger('input');
            });
        }

        function initCreditField() {
            $('.credit-amount').off('input').on('input', function() {
                const clean = stripCommas(this.value);
                if (!/^\d*\.?\d*$/.test(clean)) return;
                this.value = formatNumberWithCommas(clean);
            });
        }

        function initRemoveRow() {
            $('#itemsTableBody').on('click', '.remove-row', function() {
                if ($('#itemsTableBody tr').length > 1) {
                    $(this).closest('tr').remove();
                    $('#itemsTableBody tr').each((i, row) => {
                        $(row).find('select, input').each(function() {
                            const input = $(this);
                            const name = input.attr('name');
                            if (name) {
                                const newName = name.replace(/items\[\d+]/, `items[${i}]`);
                                input.attr('name', newName);
                            }
                        });
                    });
                }
            });
        }

        function initAddRow() {
            $('#addRowBtn').on('click', function() {
                const rowCount = $('#itemsTableBody tr').length;
                const newRow = $(`
                <tr>
                    <td>
                        <select name="items[${rowCount}][adaegi_khata]" class="form-control supplier-select" style="width:100%;"></select>
                    </td>
                    <td>
                        <input type="text" name="items[${rowCount}][credit_amount]" class="form-control credit-amount" placeholder="رقم Debit">
                    </td>
                    <td>
                        <input type="text" name="items[${rowCount}][employee]" class="form-control">
                    </td>
                    <td>
                        <button type="button" class="btn btn-danger btn-sm remove-row">Remove</button>
                    </td>
                </tr>
            `);
                $('#itemsTableBody').append(newRow);
                initCustomerSelect(newRow.find('.supplier-select'));
                initCreditField();
            });
        }

        function initAccountDropdown() {
            function updateAccountDropdown(method) {
                $.ajax({
                    url: '{{ route('get-transaction-accounts') }}',
                    type: 'GET',
                    data: {
                        type: method
                    },
                    dataType: 'json',
                    success: function(data) {
                        const $accountSelect = $('#account_select').empty();
                        $.each(data, function(key, value) {
                            $accountSelect.append(`<option value="${key}">${key} | ${value}</option>`);
                        });
                        $accountSelect.val($accountSelect.data('selected')).trigger('change');
                    },
                    error: function(xhr) {
                        alert("Error loading accounts: " + xhr.responseText);
                    }
                });
            }

            const selected = $('input[name="payment_mode"]:checked').val();
            updateAccountDropdown(selected);

            $('input[name="payment_mode"]').on('change', function() {
                updateAccountDropdown($(this).val());
            });
        }

        function initChequeToggle() {
            function toggleChequeFields() {
                const mode = $('input[name="payment_mode"]:checked').val();
                $('.cheque-field').prop('disabled', mode !== 'bank');
            }

            toggleChequeFields();

            $('input[name="payment_mode"]').change(function() {
                toggleChequeFields();
            });
        }

        function initShortcutsAndSanitize() {
            $(document).on('keydown', function(e) {
                if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {
                    e.preventDefault();
                    $('#myForm').submit();
                }
                if (e.key === 'Enter') {
                    e.preventDefault();
                }
            });

            $('#myForm').on('submit', function() {
                $('.credit-amount').each(function() {
                    this.value = stripCommas(this.value);
                });
            });
        }

        $(document).ready(function() {
            initCustomerSelect('.supplier-select');
            initCreditField();
            initAddRow();
            initRemoveRow();
            initChequeToggle();
            initShortcutsAndSanitize();
            initAccountDropdown();

            // Init datepickers
            $("#voucher_date, #voucher_chqdate, #voucher_depdate, #voucher_hondate, #voucher_dishondate")
                .datepicker({
                    dateFormat: "yy-mm-dd"
                });
        });
    </script>
    {{-- Calculate Grand Total  --}}
    <script>
        function parseNumber(value) {
            return parseFloat(value.replace(/,/g, '')) || 0;
        }

        function formatNumber(num) {
            return num.toLocaleString('en-US', {
                minimumFractionDigits: 0,
                maximumFractionDigits: 2
            });
        }

        function calculateGrandTotal() {
            let total = 0;

            $('.credit-amount').each(function() {
                total += parseNumber($(this).val());
            });

            $('#grandTotal').val(formatNumber(total));
        }

        // Recalculate on typing
        $(document).on('input', '.credit-amount', function() {
            calculateGrandTotal();
        });

        // Recalculate on row remove
        $(document).on('click', '.remove-row', function() {
            setTimeout(calculateGrandTotal, 50);
        });

        // Recalculate on add row
        $('#addRowBtn').on('click', function() {
            setTimeout(calculateGrandTotal, 50);
        });

        // Initial load
        $(document).ready(function() {
            calculateGrandTotal();
        });
    </script>
@endpush
