@extends('layouts.master')
@section('content')
    <div class="az-content-breadcrumb">
        <span>Service Voucher</span>
        <span>Edit Service Voucher </span>
        {{-- <span>Forms</span> --}}
        {{-- <span>Form Layouts</span> --}}
    </div>
    <h2 class="az-content-title" style="display: inline">Edit New Service Voucher
        <span>
            <a href="{{ route('voucher.list') }}" class="btn border" style="float: right"><i
                    class="fa-solid fa-bars-staggered"></i>
                Back to Service 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">Create Service Voucher</h5>
                <hr>
                <form method="post"
                    action="{{ route('service_voucher.update', ['id' => Crypt::encrypt($vouchersNumber->id_vouchers_unique_number)]) }}">
                    @csrf
                    @method('PUT')
                    @if (count($errors) > 0)
                        <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" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                            @endforeach
                        </div>
                    @endif


                    <div class="row">
                        <!-- Left Column -->
                        <div class="col-md-6">
                            <div class="card shadow-sm">
                                <div class="card-body">
                                    <div class="">
                                        @foreach ($vouchersNumber->vouchers as $voucher)
                                            <input type="hidden" name="voucherIds[]" value="{{ $voucher->id_vouchers }}">
                                        @endforeach
                                    </div>
                                    <div class="mb-3">
                                        <label for="voucher_date" class="form-label">Service Voucher Date</label>
                                        <input type="text" id="voucher_date" name="voucher_date" class="form-control"
                                            placeholder="Enter Service Voucher Date" required autocomplete="off" />
                                    </div>

                                    <div class="mb-3">
                                        <label for="description" class="form-label">Description</label>
                                        <textarea id="description" name="description" class="form-control" placeholder="Enter Description"></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Right Column -->
                        <div class="col-md-6">
                            <div class="card shadow-sm">
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="business_partner" class="form-label">Business Partner</label>
                                        <select onchange="getPartnerData();" id="business_partner" name="business_partner"
                                            class="form-control select2" tabindex="-1" aria-hidden="true">
                                            <option value="">Select</option>
                                            <option value="employee">Employee</option>
                                            <option value="customer">Customer</option>
                                            <option value="other">Other</option>
                                        </select>
                                    </div>

                                    <div class="mb-3">
                                        <label for="partner_name" class="form-label">Partner Name</label>
                                        <select id="partner_name" name="partner_name" class="form-control select2"
                                            tabindex="-1" aria-hidden="true">
                                            <option value="">Select</option>
                                        </select>
                                    </div>

                                    <div class="mb-3" id="addVendorButtonContainer" style="display: none;">
                                        <button type="button" class="btn btn-primary" data-bs-toggle="modal"
                                            data-bs-target="#addVendorModal">
                                            Edit Vendor
                                        </button>
                                    </div>
                                    <div class="mb-4 text-center">
                                        <label class="form-label d-block mb-2">Payment Method</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_method" value="cash" 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_method" value="bank" 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">
                                                <option value="">Select Account</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Bottom Row -->
                    <div class="row my-4">
                        <div class="col-md-6">
                            <div class="card shadow-sm">
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="transaction_type" class="form-label">Transaction Type</label>
                                        <select name="transaction_type" class="form-control" id="transaction_type">
                                            <option value="Credit">Credit</option>
                                            <option value="Debit">Debit</option>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label for="tax_debit" class="form-label">Tax Debit</label>
                                        <select name="tax_debit" class="form-control" id="tax_debit">
                                            <option value="No">No</option>
                                            <option value="Yes">Yes</option>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label for="transaction_account" class="form-label">Transaction Account</label>
                                        <select name="transaction_account" name="account" class="form-control select2"
                                            id="transaction_account">
                                            <option value="">- Select -</option>
                                            @foreach ($accounts as $acc)
                                                <option value="{{ $acc->id_transaction_account }}">
                                                    {{ $acc->id_transaction_account }} |
                                                    {{ $acc->transaction_account_name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="card shadow-sm">
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="payment_mode" class="form-label">Payment Mode</label>
                                        <select name="payment_mode" class="form-control" id="payment_mode">
                                            <option value="Cash">Cash</option>
                                            <option value="Cheque">Cheque</option>
                                            <option value="Pay Order">Pay Order</option>
                                            <option value="Credit Card">Credit Card</option>
                                            <option value="Other">Other</option>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label for="amount" class="form-label">Amount</label>
                                        <input type="text" id="amount" name="amount" class="form-control"
                                            placeholder="Enter Amount" required />
                                    </div>
                                    <div class="mb-3">
                                        <label for="instrument" class="form-label">Instrument</label>
                                        <input type="text" id="instrument" name="instrument" class="form-control"
                                            placeholder="Enter Instrument" required />
                                    </div>
                                    <div class="mb-3">
                                        <label for="remarks" class="form-label">Remarks</label>
                                        <textarea id="remarks" name="remarks" class="form-control" placeholder="Enter Remarks"></textarea>
                                    </div>
                                    <div class="mt-3">
                                        <label for="voucher_status" class="form-label">Status</label>
                                        <select id="voucher_status" name="voucher_status" class="form-control">
                                            <option value="">- Select -</option>
                                            <option value="1" selected>Active</option>
                                            <option value="0">InActive</option>
                                        </select>
                                    </div>
                                    <button type="button" id="addButton"
                                        class="btn btn-success text-white mt-2 float-end">
                                        Add <i class="fas fa-arrow-down"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>


                    <br>
                    <div class="row mt-4">
                        <div class="col-12">
                            <table id="example2" class="table table-hover table-bordered align-middle">
                                <thead class="table-light">
                                    <tr>
                                        <th class="text-center">#</th>
                                        <th>Account No</th>
                                        <th>Account Title</th>
                                        <th>Payment Mode</th>
                                        <th>Instrument</th>
                                        <th>Amount</th>
                                        <th>Remarks</th>
                                        <th>Debit</th>
                                        <th>Credit</th>
                                        <th>Partner Name</th>
                                        <th>Tax Debit</th>
                                        <th>Transaction Acc No</th>
                                        <th>Transaction Acc Name</th>
                                        <th>Description</th>
                                        <th class="text-center">Status</th>
                                        <th>Created</th>
                                        <th class="text-center">Actions</th>
                                    </tr>
                                </thead>
                                {{-- {{dd($vouchersNumber->vouchers)}} --}}
                                <tbody id="voucherTableBody">
                                    {{-- @foreach ($vouchersNumber->vouchers as $index => $voucher)
                                        <tr>
                                            <td>{{ $loop->iteration }}</td>
                                            <!-- Displaying static text for existing vouchers -->
                                            <td>{{ $voucher->account_no }}</td>
                                            <td>{{ $voucher->account_title }}</td>
                                            <td>{{ $voucher->payment_mode }}</td>
                                            <td>{{ $voucher->instrument }}</td>
                                            <td>{{ $voucher->amount }}</td>
                                            <td>{{ $voucher->remarks }}</td>
                                            <td>{{ $voucher->debit }}</td>
                                            <td>{{ $voucher->credit }}</td>
                                            <td>{{ $voucher->partner_name }}</td>
                                            <td>{{ $voucher->tax_debit }}</td>
                                            <td>{{ $voucher->transaction_acc_no }}</td>
                                            <td>{{ $voucher->transaction_acc_name }}</td>
                                            <td>{{ $voucher->desciption }}</td>
                                            <td>{{ $voucher->status }}</td>
                                            <td>{{ $voucher->date }}</td>

                                            <td class="text-center">
                                                <button type="button" class="btn btn-danger btn-sm delete-row">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </td>
                                            <input type="hidden" name="deletedVoucherIds" id="deletedVoucherIds">

                                            <!-- Hidden input to keep track of voucher IDs -->
                                            <input type="hidden" name="voucherIds[]"
                                                value="{{ $voucher->id_vouchers }}">
                                        </tr>
                                    @endforeach --}}


                                    <input type="hidden" name="deletedVouchers" id="deletedVouchers">
                                    @foreach ($vouchersNumber->vouchers as $index => $voucher)
                                        <tr data-voucher-id="{{ $voucher->id_vouchers }}">
                                            <td>{{ $loop->iteration }}</td>
                                            <td>{{ $voucher->account_no }}</td>
                                            <td>{{ $voucher->account_title }}</td>
                                            <td>{{ $voucher->payment_mode }}</td>
                                            <td>{{ $voucher->instrument }}</td>
                                            <td>{{ $voucher->amount }}</td>
                                            <td>{{ $voucher->remarks }}</td>
                                            <td>{{ $voucher->debit }}</td>
                                            <td>{{ $voucher->credit }}</td>
                                            <td>{{ $voucher->partner_name }}</td>
                                            <td>{{ $voucher->tax_debit }}</td>
                                            <td>{{ $voucher->transaction_acc_no }}</td>
                                            <td>{{ $voucher->transaction_acc_name }}</td>
                                            <td>{{ $voucher->desciption }}</td>
                                            <td><?= $voucher->status == 1 ? 'Active' : 'Inactive' ?></td>
                                            <td>{{ $voucher->date }}</td>
                                            <td>
                                                <button type="button" class="btn btn-danger btn-sm delete-row">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    @endforeach




                                </tbody>
                            </table>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-az-primary btn-block mt-2" style="float: right">
                        <i class="fa fa-save"></i> Update
                    </button>
                </form>
                <!-- col -->
            </div>
        </div>
    </div>

    <!-- Edit Vendor Modal -->
    <div class="modal fade" id="addVendorModal" tabindex="-1" aria-labelledby="addVendorModalLabel"
        aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addVendorModalLabel">Edit Vendor</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addVendorForm">
                        <meta name="csrf-token" content="{{ csrf_token() }}">
                        <div class="mb-3">
                            <label for="vendorName" class="form-label">Vendor Name</label>
                            <input type="text" class="form-control" id="vendorName" name="vendor_name"
                                placeholder="Enter Vendor Name" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" onclick="saveVendor()">Save</button>
                </div>
            </div>
        </div>
    </div>

    <div id="errorNotification" class="alert alert-danger position-fixed top-0 end-0 m-3" style="display: none;">
        <strong>Error!</strong> <span id="errorMessage">Empty Field(s) Found.</span>
    </div>

@endsection
@push('scripts')
    <script>
        $(document).ready(function() {
            $('#transaction_account').select2();
        });

        function updateAccountDropdown(paymentMethod) {
            $.ajax({
                url: '{{ route('get-transaction-accounts') }}',
                type: 'GET',
                data: {
                    type: paymentMethod
                },
                dataType: 'json',
                success: function(data) {
                    var $accountSelect = $('#account_select');

                    $accountSelect.empty();
                    $accountSelect.append('<option value="">Select Account</option>');

                    $.each(data, function(key, value) {
                        $accountSelect.append('<option value="' + key + '">' + key + ' | ' + value +
                            '</option>');
                    });

                    $accountSelect.select2();
                },
                error: function(xhr, status, error) {
                    console.error("An error occurred: " + xhr.responseText);
                    alert("An error occurred while fetching accounts. Please try again.");
                }
            });
        }

        $('input[name="payment_method"]').change(function() {
            var selectedMethod = $(this).val();
            updateAccountDropdown(selectedMethod);

            if (selectedMethod === 'cash') {
                $('#payment_mode').val('Cash').trigger('change');
            } else if (selectedMethod === 'bank') {
                $('#payment_mode').val('Cheque').trigger('change');
            }
        });

        $(document).ready(function() {
            $('#account_select').select2();
        });
    </script>

    <script>
        function getPartnerData() {
            var selectedPartnerType = $('#business_partner').val();

            if (selectedPartnerType === 'employee' || selectedPartnerType === 'customer') {
                $.ajax({
                    url: '{{ route('get-partner-data') }}',
                    type: 'GET',
                    data: {
                        type: selectedPartnerType
                    },
                    dataType: 'json',
                    success: function(data) {
                        $('#partner_name').empty();
                        $('#partner_name').append('<option value="">Select</option>');

                        if (data && Object.keys(data).length > 0) {
                            $.each(data, function(key, value) {
                                $('#partner_name').append('<option value="' + key + '">' + value +
                                    '</option>');
                            });
                        } else {
                            alert("No partners found for the selected type.");
                        }

                        $('#addVendorButtonContainer').hide();
                    },
                    error: function(xhr, status, error) {
                        console.error("An error occurred: " + xhr.responseText);
                        alert("An error occurred while fetching partner data. Please try again.");
                    }
                });
            } else if (selectedPartnerType === 'other') {
                $('#addVendorButtonContainer').show();
                $('#partner_name').empty();
                $('#partner_name').append('<option value="">Select</option>');

                // Load existing vendors to the partner_name dropdown
                $.ajax({
                    url: '{{ route('get-partner-data') }}',
                    type: 'GET',
                    data: {
                        type: 'other'
                    },
                    dataType: 'json',
                    success: function(data) {
                        $.each(data, function(key, value) {
                            $('#partner_name').append('<option value="' + key + '">' + value +
                                '</option>');
                        });
                    },
                    error: function(xhr, status, error) {
                        console.error("An error occurred: " + xhr.responseText);
                        alert("An error occurred while fetching vendor data. Please try again.");
                    }
                });
            } else {
                $('#addVendorButtonContainer').hide();
                $('#partner_name').empty();
                $('#partner_name').append('<option value="">Select</option>');
            }
        }

        function saveVendor() {
            var vendorName = $('#vendorName').val();

            if (vendorName.trim() === "") {
                alert("Vendor Name cannot be empty.");
                return;
            }

            $.ajax({
                url: '{{ route('save-vendor') }}',
                type: 'POST',
                data: {
                    name: vendorName,
                    _token: $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {
                        $('#addVendorModal').modal('hide');

                        $('#partner_name').append('<option value="' + response.vendor_id + '">' + vendorName +
                            '</option>');
                    } else {
                        alert("Failed to add the vendor. Please try again.");
                    }
                },
                error: function(xhr, status, error) {
                    console.error(xhr.responseText);
                    alert("An error occurred while adding the vendor.");
                }
            });
        }
    </script>

    <script>
        $('#business_partner').select2({
            theme: 'default'
        });
        $('#partner_name').select2({
            theme: 'default'
        });
        $(document).ready(function() {
            $("#voucher_date").datepicker({
                dateFormat: "yy-mm-dd"
            });
        });

        $(document).ready(function() {
            let counter = 1;
            let deletedVoucherIds = [];

            $('#addButton').click(function() {
                let voucherDate = $('#voucher_date').val().trim();
                let accountid = $('select[name="account"] option:selected').val();
                let accountname = $('select[name="account"] option:selected').text().split('|')[1]
                    ?.trim() || '';
                let transactionAccountId = $('select[name="transaction_account"] option:selected').val();
                let transactionAccountName = $('select[name="transaction_account"] option:selected').text()
                    .split('|')[1]?.trim() || '';
                let paymentMode = $('select[name="payment_mode"] option:selected').text().trim();
                let instrument = $('#instrument').val().trim();
                let amount = $('#amount').val().trim();
                let remarks = $('#remarks').val().trim();
                let transactionType = $('select[name="transaction_type"] option:selected').val().trim();
                let voucherStatusValue = $('select[name="voucher_status"]').val();
                let businessPartner = $('select[name="partner_name"] option:selected').text().trim();
                let taxDebit = $('select[name="tax_debit"] option:selected').text().trim();
                let description = $('#description').val().trim();

                let errorMessages = [];

                if (!voucherDate) errorMessages.push('Service Voucher Date');
                if (!accountid) errorMessages.push('Account');
                if (!paymentMode) errorMessages.push('Payment Mode');
                if (!instrument) errorMessages.push('Instrument');
                if (!amount) errorMessages.push('Amount');
                if (!transactionType) errorMessages.push('Transaction Type');

                if (errorMessages.length > 0) {
                    showErrorNotification(errorMessages);
                    return;
                }

                let debit = transactionType === 'Debit' ? amount : '';
                let credit = transactionType === 'Credit' ? amount : '';

                $('#voucherTableBody').append(`
            <tr>
                <td class="text-center">${counter++}</td>
                <td><input type="hidden" name="accountNo[]" value="${accountid}">${accountid}</td>
                <td><input type="hidden" name="accountName[]" value="${accountname}">${accountname}</td>
                <td><input type="hidden" name="paymentMode[]" value="${paymentMode}">${paymentMode}</td>
                <td><input type="hidden" name="instrumentAmount[]" value="${instrument}">${instrument}</td>
                <td><input type="hidden" name="netAmount[]" value="${amount}">${amount}</td>
                <td><input type="hidden" name="noteRemarks[]" value="${remarks}">${remarks}</td>
                <td><input type="hidden" name="debitAMount[]" value="${debit}">${debit}</td>
                <td><input type="hidden" name="creditAmount[]" value="${credit}">${credit}</td>
                <td><input type="hidden" name="businessPartnerName[]" value="${businessPartner}">${businessPartner}</td>
                <td><input type="hidden" name="taxDebitYesNo[]" value="${taxDebit}">${taxDebit}</td>
                <td><input type="hidden" name="transactionAccountId[]" value="${transactionAccountId}">${transactionAccountId}</td>
                <td><input type="hidden" name="transactionAccountName[]" value="${transactionAccountName}">${transactionAccountName}</td>
                <td><input type="hidden" name="vDescription[]" value="${description}">${description}</td>
                <td class="text-center"><input type="hidden" name="voucherStatus[]" value="${voucherStatusValue}">${voucherStatusValue == 1 ? 'Active' : 'Inactive'}</td>
                <td><input type="hidden" name="voucherDate[]" value="${voucherDate}">${voucherDate}</td>
                <td class="text-center">
                    <button type="button" class="btn btn-danger btn-sm delete-row">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            </tr>
        `);

                $('#voucherForm').trigger('reset');
            });

            $(document).ready(function() {
                let deletedVoucherIds = [];

                $(document).on('click', '.delete-row', function() {
                    let row = $(this).closest('tr');
                    let voucherId = row.attr(
                        'data-voucher-id');

                    if (voucherId) {
                        deletedVoucherIds.push(voucherId);
                        $('#deletedVouchers').val(deletedVoucherIds.join(
                            ','));
                    }

                    row.remove();
                });
            });


            function showErrorNotification(errors) {
                let errorMessage = errors.join(', ');
                $('#errorMessage').text(errorMessage);
                $('#errorNotification').fadeIn().delay(3000).fadeOut();
            }
        });
    </script>
    </script>
@endpush
