@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;
        }

        .card-body.pd-40 {
            padding: 30px;
        }

        .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>Add Payment Voucher </span>
    </div>
    <h2 class="az-content-title" style="display: inline">Add New 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">Create Payment Voucher</h5>
                <hr>
                <form id="myForm" method="post" action="{{ route('payment_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">
                        <div class="row">
                            <div class="col-lg-6 mt-3 p-3 border-end">
                                <h5 class="card-title">Voucher Information</h5>
                                <div class="mb-2">
                                    <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"
                                        placeholder="Enter Payment Voucher Date" readonly />
                                </div>
                                <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" 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" 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="my-2">
                                    <label for="voucher_details" class="form-label"> تفصیلات </label>
                                    <input type="text" id="voucher_details" name="voucher_details"
                                        class="form-control" />
                                </div>
                            </div>


                            <div class="col-lg-6 mt-3 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" />
                                </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" 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" 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" />
                                </div>
                            </div>
                        </div>
                        <div class="row my-5 card p-3">
                            <h5 class="card-title">Voucher Details</h5>
                            <div class="col-12">
                                <table id="example2" class="table table-hover table-bordered align-middle">
                                    <thead class="table-light">
                                        <tr>
                                            <th>جمع کھاتہ</th>
                                            <th>Description(تفصیل)</th>
                                            <th>رقم Debit</th>
                                            <th>رقم Credit</th>
                                            <th>Employee</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody id="itemsTableBody">
                                        <tr>
                                            <td>
                                                <select name="items[0][adaegi_khata]" class="form-control vendor-select"
                                                    style="width: 100%;"></select>
                                            </td>
                                              <td>
                                                <input type="text" name="items[0][description]" class="form-control">
                                            </td>
                                            <td>
                                                <input type="text" name="items[0][debit_amount]"
                                                    class="form-control debit-amount" placeholder="رقم Debit">
                                            </td>
                                             <td>
                                                <input type="text" name="items[0][credit_amount]"
                                                    class="form-control credit-amount" placeholder="رقم Credit">
                                            </td>
                                            <td>
                                                <input type="text" name="items[0][employee]" class="form-control">
                                            </td>
                                            <td>
                                                {{-- <button type="button" class="btn btn-danger btn-sm remove-row">
                                                Remove
                                            </button> --}}
                                            </td>
                                        </tr>
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <th class="text-end">Grand Total</th>
                                             <th colspan="1"></th>
                                            <th>
                                                <input type="text" id="grandTotalDebit" class="form-control text-end"
                                                    readonly>
                                            </th>
                                            <th>
                                                <input type="text" id="grandTotalCredit" 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-az-primary btn-block mt-2" style="float: right">
                            <i class="fa fa-save"></i> Save
                        </button>
                </form>
            </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>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
@endsection

@push('scripts')
    <script>
        document.addEventListener('keydown', function(e) {
            // Check for Ctrl + S or Cmd + S (Mac)
            if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {
                e.preventDefault();

                const form = document.getElementById('myForm');
                if (form) form.submit();
            }
        });
    </script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('myForm');

            form.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' && e.target.tagName !== 'TEXTAREA') {
                    e.preventDefault();
                    return false;
                }
            });
        });
    </script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const chequeFields = document.querySelectorAll('.cheque-field');
            const paymentModeInputs = document.querySelectorAll('input[name="payment_mode"]');

            function toggleChequeFields() {
                const selectedMode = document.querySelector('input[name="payment_mode"]:checked')?.value;

                chequeFields.forEach(field => {
                    field.disabled = (selectedMode !== 'bank');
                });
            }

            // Initially disable on page load
            toggleChequeFields();

            // Add change listeners to radio buttons
            paymentModeInputs.forEach(input => {
                input.addEventListener('change', toggleChequeFields);
            });
        });
    </script>
    <script>
        function initCustomerSelect(selector) {
            $(selector).select2({
                placeholder: 'Search Supplier',
                minimumInputLength: 0,
                ajax: {
                    url: '{{ url('get-supplier-data') }}',
                    dataType: 'json',
                    delay: 250,
                    data: function(params) {
                        return {
                            query: params.term || ''
                        };
                    },
                    processResults: function(data) {
                        return {
                            results: data
                        };
                    }
                }
            }).on('select2:open', function() {
                $('.select2-search__field').trigger('input');
            });
        }

        $(document).ready(function() {
            initCustomerSelect('.vendor-select');
        });
    </script>
    {{-- New --}}
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Add row functionality
            document.getElementById('addRowBtn').addEventListener('click', function() {
                const tableBody = document.getElementById('itemsTableBody');
                const rowCount = tableBody.children.length;

                const newRow = document.createElement('tr');
                newRow.innerHTML = `
                <td>
                    <select name="items[${rowCount}][adaegi_khata]" class="form-control vendor-select" style="width: 100%;"></select>
                </td>
                <td>
                    <input type="text" name="items[${rowCount}][description]" class="form-control">
                </td>
                <td>
                    <input type="text" name="items[${rowCount}][debit_amount]" class="form-control debit-amount" placeholder="رقم Debit">
                </td>
                <td>
                    <input type="text" name="items[${rowCount}][credit_amount]" class="form-control credit-amount" placeholder="رقم Credit ">
                </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>
            `;

                tableBody.appendChild(newRow);
                initCustomerSelect(newRow.querySelector('.vendor-select')); // re-apply select2
            });

            // Remove row functionality
            document.addEventListener('click', function(e) {
                if (e.target && e.target.classList.contains('remove-row')) {
                    const row = e.target.closest('tr');
                    const tableBody = document.getElementById('itemsTableBody');

                    // Don't allow removing the last row
                    if (tableBody.children.length > 1) {
                        row.remove();

                        // Reindex the remaining rows
                        const rows = tableBody.querySelectorAll('tr');
                        rows.forEach((row, index) => {
                            row.querySelector('select').name = `items[${index}][option]`;
                            row.querySelector('input[type="number"]').name =
                                `items[${index}][amount]`;
                            row.querySelector('input[type="text"]').name =
                                `items[${index}][employee]`;
                        });
                    }
                }
            });
        });
    </script>
    {{-- New End --}}

    <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();
            }
        });

        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_mode"]').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();
        });

        var today = new Date();
        var formattedDate = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today
            .getDate()).slice(-2);

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

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

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

        $("#voucher_depdate").datepicker({
            dateFormat: "yy-mm-dd" // Customize the date format here
        });
    </script>
    <script>
        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 bindCreditFieldFormatter() {
            $('.credit-amount').off('input').on('input', function() {
                const cursorPos = this.selectionStart;
                const numeric = stripCommas(this.value);
                if (!/^\d*\.?\d*$/.test(numeric)) return;

                this.value = formatNumberWithCommas(numeric);
                this.setSelectionRange(cursorPos, cursorPos);
            });

            // Optional: cleanup commas before submitting
            $('#myForm').on('submit', function() {
                $('.credit-amount').each(function() {
                    const raw = stripCommas($(this).val());
                    $(this).val(raw);
                });
            });
        }

        $(document).ready(function() {
            bindCreditFieldFormatter();

            // Re-apply formatting on dynamically added rows
            $('#addRowBtn').on('click', function() {
                setTimeout(() => bindCreditFieldFormatter(), 50);
            });
        });
    </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 calculateCreditGrandTotal() {
        let total = 0;


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

        $('#grandTotalCredit').val(formatNumber(total));
    }
    function calculateDebitGrandTotal() {
        let total = 0;


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

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

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

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

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

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