@extends('layouts.master')
@section('content')
    <div class="az-content-breadcrumb">
        <span> Service Purchase Voucher</span>
        <span>Add Service Purchase Voucher </span>
        {{-- <span>Forms</span> --}}
        {{-- <span>Form Layouts</span> --}}
    </div>
    <h2 class="az-content-title" style="display: inline">Add New Service Purchase Voucher <span>
            <a href="{{ route('service_voucher.list') }}" class="btn border" style="float: right"><i
                    class="fa-solid fa-bars-staggered"></i>
                Back to Service Purchase Voucher
            </a>
        </span></h2>
    {{-- <h2 style="float: right" class="az-content-title"></h2> --}}


    {{-- <div class="az-content-body pd-lg-l-40 d-flex flex-column"> --}}
    <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 Purchase Voucher</h5>
                <hr>
                <form id="myForm" method="post" action="{{ route('service_voucher.store') }}">
                    @csrf
                    @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-4">
                            <div class="mb-3">
                                <label for="voucher_date" class="form-label">Service Voucher Date <span
                                        style="color:red;">*</span></label>
                                <input type="text" id="voucher_date" name="voucher_date" class="form-control"
                                    placeholder="Enter Service Voucher Date" readonly />
                            </div>

                            <div class="mb-4 text-center">
                                <label class="form-label d-block mb-2">Payment Method <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_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 class="mb-3">
                                <label for="description" class="form-label">Description </label>
                                <textarea id="description" name="description" class="form-control" placeholder="Enter Description"
                                    value="{{ old('description') }}"></textarea>
                            </div> --}}
                        </div>

                        <!-- Right Column -->
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="business_partner" class="form-label">Business Partner <span
                                        style="color:red;">*</span></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="suppliers">Supplier</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>
                            <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" hidden>
                                <label for="transaction_type" class="form-label">Transaction Type <span
                                        style="color:red;">*</span></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" id="addVendorButtonContainer" style="display: none;">
                                <button type="button" class="btn btn-primary" data-bs-toggle="modal"
                                    data-bs-target="#addVendorModal">
                                    Add Vendor
                                </button>
                            </div> --}}
                        </div>

                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="partner_name" class="form-label">Partner Name <span
                                        style="color:red;">*</span></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">
                                <label for="transaction_account" class="form-label">Transaction Account <span
                                        style="color:red;">*</span></label>
                                <select name="transaction_account" name="account" class="form-control select2"
                                    id="transaction_account" required>
                                    <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 class="mb-3">
                                <label for="tax_debit" class="form-label">Tax Debit <span
                                        style="color:red;">*</span></label>
                                <select name="tax_debit" class="form-control" id="tax_debit">
                                    <option value="No">No</option>
                                    <option value="Yes">Yes</option>
                                </select>
                            </div> --}}
                        </div>
                    </div>

                    <!-- Bottom Row -->
                    <div class="row  ">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="amount" class="form-label">Amount <span style="color:red;">*</span></label>
                                <input type="text" id="amount" name="amount" class="form-control"
                                    placeholder="Enter Amount" required />
                            </div>
                        </div>
                        <div class="col-md-6">
                            <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" />
                            </div>
                        </div>
                        {{-- <div class="col-md-3">
                            <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> --}}
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <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>


                    <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>Partner Name</th>
                                        <th>Instrument</th>
                                        <th>Amount</th>
                                        <th>Created</th>
                                        <th>Credit</th>
                                        <th>Debit</th>
                                        <th class="text-center">Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="voucherTableBody">
                                    <!-- Rows will be added dynamically here -->
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <td colspan="8" class="text-end"><strong>Total:</strong></td>
                                        <td><strong><span id="totalCredit">0.00</span></strong></td>
                                        <td><strong><span id="totalDebit">0.00</span></strong></td>
                                        <td></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-az-primary btn-block mt-2" style="float: right">
                        <i class="fa fa-save"></i> Save
                    </button>
                </form>
                <!-- col -->
            </div>
        </div>
    </div>
    <!-- Add 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">Add 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.addEventListener('keydown', function(event) {
            if ((event.ctrlKey || event.metaKey) && event.key === 's') {
                event.preventDefault();

                document.getElementById('myForm').submit();
            }

            if (event.key === 'Enter') {
                event.preventDefault();
            }
        });
        $(document).ready(function() {
            $('#transaction_account').select2();
        });

        $(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' || selectedPartnerType ===
                'suppliers') {
                $.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="' + value + '">' + 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') }}', // Use Laravel's route helper to generate the correct URL
                type: 'POST',
                data: {
                    name: vendorName,
                    _token: $('meta[name="csrf-token"]').attr('content') // Add CSRF token
                },
                success: function(response) {
                    if (response.success) {
                        // alert("Vendor added successfully!");
                        $('#addVendorModal').modal('hide');

                        // Optionally, update the partner_name dropdown to include the new vendor
                        $('#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'
        });
        var today = new Date();
        var formattedDate = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today
            .getDate()).slice(-2);

        $("#voucher_date").val(formattedDate);

        // Initialize datepicker with custom format
        $("#voucher_date").datepicker({
            dateFormat: "yy-mm-dd" // Customize the date format here
        });

        $(document).ready(function() {
            let counter = 1; // Counter for serial numbers
            let totalCredit = 0;
            let totalDebit = 0;
            let hasAddedRows = false; // Flag to track if rows have been added
            let debitRow; // Variable to store the debit row

            $('#addButton').click(function() {
                // Get form data
                let voucherDate = $('#voucher_date').val().trim();
                let PartnerName = $('select[name="partner_name"] option:selected').text();
                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 = parseFloat($('#amount').val().trim());
                // let remarks = $('#remarks').val().trim();
                let transactionType = $('select[name="transaction_type"] option:selected').val().trim();
                let taxDebit = $('select[name="tax_debit"] option:selected').text().trim();

                // Validation and error messages
                let errorMessages = [];
                if (!voucherDate) errorMessages.push('Service Voucher Date');
                if (!accountid) errorMessages.push('Account');
                if (!paymentMode) errorMessages.push('Payment Mode');
                if (!amount || isNaN(amount)) errorMessages.push('Amount');
                if (!transactionType) errorMessages.push('Transaction Type');

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

                if (!hasAddedRows) {
                    // Add the first Credit row and Debit row
                    addRow(transactionAccountId, transactionAccountName, PartnerName, paymentMode,
                        instrument, amount,
                        voucherDate, 'Credit');
                    debitRow = addRow(accountid, accountname, PartnerName, paymentMode, instrument, amount,
                        voucherDate, 'Debit');
                    hasAddedRows = true;
                } else {
                    // Add new Credit row
                    let newCreditRow = addRow(transactionAccountId, transactionAccountName, PartnerName,
                        paymentMode,
                        instrument, amount, voucherDate, 'Credit');
                    $(newCreditRow).insertBefore(debitRow); // Insert new credit row above debit row
                }

                // Update the debit row amount
                totalDebit = totalCredit;
                updateDebitRow();

                $('#voucherForm').trigger('reset'); // Reset form after adding row
            });

            function addRow(accountNo, accountTitle, PartnerName, paymentMode, instrument, amount,
                created,
                transactionType) {
                let debitAmount = transactionType === 'Debit' ? amount.toFixed(2) : '';
                let creditAmount = transactionType === 'Credit' ? amount.toFixed(2) : '';

                if (transactionType === 'Credit') {
                    totalCredit += parseFloat(creditAmount); // Add to total credit
                }

                let rowHtml = `
                <tr>
                    <td class="text-center">${counter++}</td>
                    <td><input type="hidden" name="accountNo[]" value="${accountNo}">${accountNo}</td>
                    <td><input type="hidden" name="accountName[]" value="${accountTitle}">${accountTitle}</td>
                    <td><input type="hidden" name="paymentMode[]" value="${paymentMode}">${paymentMode}</td>
                    <td><input type="hidden" name="PartnerName[]" value="${PartnerName}">${PartnerName}</td>
                    <td><input type="hidden" name="instrumentAmount[]" value="${instrument}">${instrument}</td>
                    <td><input type="hidden" name="netAmount[]" value="${amount}">${amount.toFixed(2)}</td>
                    <td><input type="hidden" name="voucherDate[]" value="${created}">${created}</td>
                    <td><input type="hidden" name="creditAmount[]" value="${creditAmount}">${creditAmount}</td>
                    <td><input type="hidden" name="debitAmount[]" value="${debitAmount}">${debitAmount}</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>
                `;

                let $row = $(rowHtml);

                // Append the row initially if rows haven't been added yet
                if (!hasAddedRows) {
                    $('#voucherTableBody').append($row);
                } else {
                    $('#voucherTableBody').prepend($row); // Append above the debit row
                }

                return $row; // Return row so it can be inserted or manipulated
            }

            // Function to update the debit row amount
            function updateDebitRow() {
                $(debitRow).find('input[name="debitAmount[]"]').val(totalDebit.toFixed(2));
                $(debitRow).find('td').eq(9).text(totalDebit.toFixed(2)); // Update the displayed debit amount
                let debitAmountTd = $(debitRow).find('td').eq(9);
                debitAmountTd.html(
                    `<input type="hidden" name="debitAmount[]" value="${totalDebit.toFixed(2)}">${totalDebit.toFixed(2)}`
                );

                updateTotals();
            }

            // Function to update total displays
            function updateTotals() {
                $('#totalDebit').text(totalDebit.toFixed(2)); // Update total debit
                $('#totalCredit').text(totalCredit.toFixed(2)); // Update total credit
                if (totalDebit > totalCredit) {
                    $('#totalDebit').css('color', 'red');
                } else {
                    $('#totalDebit').css('color', ''); // Reset to default
                }
            }

            // Delete row functionality
            $(document).on('click', '.delete-row', function() {
                // Get the row to be deleted
                let row = $(this).closest('tr');

                // Get debit and credit amounts from the row
                let debitAmount = parseFloat(row.find('input[name="debitAmount[]"]').val());
                let creditAmount = parseFloat(row.find('input[name="creditAmount[]"]').val());

                // Update total amounts
                totalDebit -= debitAmount || 0;
                totalCredit -= creditAmount || 0;

                // Update totals
                updateTotals();

                // Remove the row
                row.remove();

                // Check if debitRow is removed, reset hasAddedRows if no more rows left
                if ($('#voucherTableBody tr').length === 0) {
                    hasAddedRows = false;
                    totalDebit = 0; // Reset totalDebit
                    totalCredit = 0; // Reset totalCredit
                    $('#totalDebit').text('0.00'); // Reset display
                    $('#totalCredit').text('0.00'); // Reset display
                } else if (debitRow.is(row)) {
                    // If the deleted row was the debit row, reset debitRow
                    debitRow = $('#voucherTableBody tr:last-child'); // Update debitRow to the last row
                    totalDebit = parseFloat(debitRow.find('input[name="debitAmount[]"]').val()) ||
                        0; // Get new totalDebit from the last row
                    updateDebitRow(); // Update the new debit row
                }
            });

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