@extends('layouts.master')

<style>
    .d-none {
        display: none;
    }

    .custom-dropdown {
        position: relative;
        display: inline-block;
        width: 100%;
    }

    .dropdown-toggle {
        background: white;
        border: 1px solid #ced4da;
        border-radius: 4px;
        padding: 5px;
        cursor: pointer;
    }

    .dropdown-content {
        display: none;
        position: absolute;
        background-color: white;
        width: 100%;
        max-height: 300px;
        overflow-y: auto;
        border: 1px solid #ced4da;
        border-radius: 4px;
        box-shadow: 0px 8px 16px rgba(0, 0, 0, 0.2);
        z-index: 1;
    }

    .table-hover tbody tr:hover {
        background-color: #f5f5f5;
    }

    .truck-details {
        cursor: pointer;
    }

    .urdu-text {
        font-family: 'Jameel Noori Nastaleeq', serif;
        font-weight: 700;


    }

    .form-label {
        text-align: right;
        color: black !important;
    }

    .form-control-urdu {
        text-align: right;
    }

    .az-content-label-urdu {
        float: right;
        font-size: 2.4vh;
        font-family: 'Jameel Noori Nastaleeq', serif;
        margin-bottom: 10px
    }
</style>

@section('content')
    <!-- Breadcrumb and Page Title -->
    <div class="az-content-breadcrumb">
        <span>Goods Receipts Billing / B-Cheque</span>
        <span>Create Goods Receipts Billing / B-Cheque</span>
    </div>
    <h2 class="az-content-title" style="display: inline">
        Create B-Cheque
        <span>
            <a href="{{ route('b_cheque.list') }}" class="btn border" style="float: right">
                <i class="fa-solid fa-bars-staggered"></i> Back to List
            </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 B-Cheque</h5>
                <form action="{{ route('b_cheque.store') }}" method="POST">
                    @csrf
                    <!-- Error Display -->
                    @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 row-sm mg-b-20">
                        <div class="col-md-3">
                            <div class="form-group">
                                <label class="az-content-label" for="bCheck_date">Date</label>
                                <input type="text" class="form-control" name="bCheck_date" id="bCheck_date" autocomplete="off" required>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label class="az-content-label" for="pb_no">PBNo</label>
                                <input type="text" class="form-control" name="pb_no" id="pb_no" required>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="az-content-label az-content-label-urdu" for="truck">ٹرک نمبر</label>

                                <!-- Hidden native select element -->
                                <select class="form-control d-none" name="good_receipts_truck_id" id="truck" required>
                                    <option value="">- Select -</option>
                                    @foreach ($trucks as $truck)
                                        <option value="{{ $truck->id_truck }}">
                                            {{ $truck->truck_no }}
                                        </option>
                                    @endforeach
                                </select>

                                <!-- Visible custom dropdown -->
                                <div class="custom-dropdown">
                                    <div class="dropdown-toggle form-control" id="truck-toggle">- Select -</div>
                                    <div class="dropdown-content">
                                        <input type="text" id="truck-search" class="form-control"
                                            placeholder="Search the truck number..."
                                            onkeyup="showOnlyThisTruckDetails(this.value)">
                                        <table class="table table-bordered table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Truck No</th>
                                                    <th>Item</th>
                                                    <th>Marka</th>
                                                    <th>Quantity</th>
                                                    <th>Weight</th>
                                                    <th>Price</th>
                                                </tr>
                                            </thead>
                                            <tbody id="truck-table-body">
                                                @foreach ($trucks as $truck)
                                                    @foreach ($truck->goodReceipts as $receipt)
                                                        @foreach ($receipt->goodReceiptDetails as $detail)
                                                            <tr class="truck-details"
                                                                data-truck-id="{{ $truck->id_truck }}">
                                                                <td>{{ $truck->truck_no }}</td>
                                                                <td>{{ $detail->goods_name }}</td>
                                                                <td>{{ $detail->marka }}</td>
                                                                <td>{{ $detail->bori }}</td>
                                                                <td>{{ $detail->weight }}</td>
                                                                <td>{{ $detail->rate }}</td>
                                                            </tr>
                                                        @endforeach
                                                    @endforeach
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4 mt-3">
                            <div class="form-group">
                                <label class="az-content-label az-content-label-urdu">سپلائرز</label>
                                <select class="form-control select2" name="suppliers" id="suppliers" required>
                                    <option value="">- Select -</option>
                                    @foreach ($suppliers as $key => $supplier)
                                        <option value="{{ $supplier->id_supplier }}">{{ $supplier->supplier_name }} -
                                            {{ $supplier->supplier_name_urdu }}</option>
                                    @endforeach
                                </select>
                            </div>
                            @error('suppliers')
                                <span class="form-text text-danger">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>

                        <div class="col-md-4 mt-3">
                            <div class="form-group">
                                <label class="az-content-label az-content-label-urdu" for="bilty_no">بلٹی نمبر</label>
                                <input type="text" class="form-control" name="bilty_no" id="bilty_no" required>
                            </div>
                        </div>
                        <div class="col-md-4 mt-3">
                            <div class="form-group">
                                <label class="az-content-label az-content-label-urdu" for="detail">تفصیل</label>
                                <input type="text" class="form-control" name="detail" id="detail" required>
                            </div>
                        </div>
                        <div class="col-md-4 mt-3">
                            <label class="az-content-label" for="bCheck_status">Status{{-- حیثیت --}}</label>
                            <select id="bCheck_status" name="bCheck_status" class="form-control">
                                <option value="">Select</option>
                                <option value="1" selected>Active</option>
                                <option value="0" {{ old('bCheck_status') == '0' ? 'selected' : '' }}>
                                    In-Active
                                </option>
                            </select>
                            @error('bCheck_status')
                                <span class="form-text text-danger">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>

                        <!-- Item Details Section -->
                        <div class="col-md-12 mt-5">
                            <h4>Item Details</h4>
                            <div class="shadow p-3 bg-light rounded">
                                <table class="table table-bordered" id="item-table">
                                    <thead>
                                        <tr>
                                            <th
                                                style="font-size: 2vh; color: black; text-align: right;  font-family: 'Jameel Noori Nastaleeq', serif;">
                                                مارکہ</th>
                                            <th
                                                style="font-size: 2vh; color: black; text-align: right;  font-family: 'Jameel Noori Nastaleeq', serif;">
                                                آئٹم</th>
                                            <th
                                                style="font-size: 2vh; color: black; text-align: right;  font-family: 'Jameel Noori Nastaleeq', serif;">
                                                بوری</th>
                                            <th
                                                style="font-size: 2vh; color: black; text-align: right;  font-family: 'Jameel Noori Nastaleeq', serif;">
                                                وزن</th>
                                            <th
                                                style="font-size: 2vh; color: black; text-align: right;  font-family: 'Jameel Noori Nastaleeq', serif;">
                                                نرخ</th>
                                            <th
                                                style="font-size: 2vh; color: black; text-align: right;  font-family: 'Jameel Noori Nastaleeq', serif;">
                                                رقم</th>
                                            <th
                                                style="font-size: 2vh; color: black; text-align: right;  font-family: 'Jameel Noori Nastaleeq', serif;">
                                                عمل</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td>
                                                <select class="form-control marka-select" name="marka[]" id="marka">
                                                    <option value="">- Select -</option>
                                                </select>
                                            </td>
                                            <td>
                                                <select class="form-control item-select" name="items_name[]">
                                                    <option value="">- Select -</option>
                                                </select>
                                            </td>
                                            <td><input type="text" class="form-control" name="bori[]"></td>
                                            <td><input type="text" class="form-control" name="weight[]"></td>
                                            <td><input type="text" class="form-control" name="rate[]"></td>
                                            <td><input type="text" class="form-control" name="amount[]"></td>
                                            <td>
                                                <button type="button" class="btn rounded shadow-base"
                                                    onclick="removeRow(this)">
                                                    <i class="text-danger fa-solid fa-trash-can"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                                <button type="button" class="btn btn-az-primary btn-block mt-2" onclick="addRow()">
                                    <span class="mdi mdi-arrow-expand-up"></span> Add More
                                </button>
                            </div>
                        </div>
                    </div>

                    <br><br>
                    <hr>
                    <br>
                    <div class="row urdu-text">

                        <div class="col-md-3">
                            <div class="form-group mb-3">
                                <label for="total_amount" class="form-label">:کل رقم</label>
                                <input type="text" class="form-control form-control-urdu" id="total_amount"
                                    name="total_amount" placeholder="کل رقم درج کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="cash_received" class="form-label">:کل خرچہ</label>
                                <input type="text" class="form-control form-control-urdu" id="cash_received"
                                    name="cash_received" placeholder="کل خرچہ درج کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="remaining_amount" class="form-label">:بچت</label>
                                <input type="text" class="form-control form-control-urdu" id="remaining_amount"
                                    name="remaining_amount" placeholder=" بچت درج کریں">
                            </div>

                        </div>

                        <div class="col-md-3">
                            <div class="form-group mb-3">
                                <label for="total_bori" class="form-label">:کل بوریاں</label>
                                <input type="text" class="form-control form-control-urdu" id="total_bori"
                                    name="total_bori" placeholder="کل بوریاں درج کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="weight" class="form-label">:وزن</label>
                                <input type="text" class="form-control form-control-urdu" id="weight"
                                    name="weight" placeholder="وزن درج کریں">
                            </div>
                        </div>


                        <div class="col-md-3">
                            <div class="form-group mb-3">
                                <label for="commission_rate" class="form-label">
                                    <span style="float: left; font-size: 1.9vh; font-weight: 100 !important;">Put The value
                                        of total in percentage <span style="color: red;">(%)</span></span>
                                    <span>:کمیشن ریٹ</span>
                                </label>
                                <input type="number" class="form-control form-control-urdu" id="commission_rate"
                                    name="commission_rate" placeholder="کمیشن ریٹ درج کریں" max="100">
                            </div>
                            <div class="form-group mb-3">
                                <label for="commission" class="form-label">:کمیشن</label>
                                <input type="text" class="form-control form-control-urdu" id="commission"
                                    name="commission" placeholder="کمیشن درج کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="more" class="form-label">:مزید</label>
                                <input type="text" class="form-control form-control-urdu" id="more"
                                    name="more" placeholder="اضافی رقم درج کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="detail" class="form-label">:تفصیلات</label>
                                <textarea class="form-control form-control-urdu" name="detail" id="detail" rows="5"
                                    placeholder="تفصیلات درج کریں"></textarea>
                            </div>
                        </div>


                        <div class="col-md-3">
                            <div class="form-group mb-3">
                                <label for="rent_received" class="form-label">:کرایہ وصول</label>
                                <input type="text" class="form-control form-control-urdu" id="rent_received"
                                    name="rent_received" placeholder="کرایہ وصول کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="labour" class="form-label">:مزدوری</label>
                                <input type="text" class="form-control form-control-urdu" id="labour"
                                    name="labour" placeholder="مزدوری درج کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="market_fees" class="form-label">:بازار کی فیس</label>
                                <input type="text" class="form-control form-control-urdu" id="market_fees"
                                    name="market_fees" placeholder="بازار کی فیس درج کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="post_expense" class="form-label">:پوسٹ خرچ</label>
                                <input type="text" class="form-control form-control-urdu" id="post_expense"
                                    name="post_expense" placeholder="پوسٹ خرچ درج کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="miscellaneous_expense" class="form-label">:متفرق خرچ</label>
                                <input type="text" class="form-control form-control-urdu" id="miscellaneous_expense"
                                    name="miscellaneous_expense" placeholder="متفرق خرچ درج کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="cash" class="form-label">:نقد</label>
                                <input type="text" class="form-control form-control-urdu" id="cash"
                                    name="cash" placeholder="نقد رقم درج کریں">
                            </div>
                        </div>
                        <div class="mt-5">
                            <a href="{{ route('b_cheque.list') }}" class="btn btn-danger pd-x-20">Cancel</a>
                            <button type="submit" class="btn btn-az-primary pd-x-20">Submit</button>
                        </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script type="text/javascript">
        function addRow() {
            var row = `<tr>
                <td>
                    <select class="form-control marka-select" name="marka[]">
                        <option value="">- Select -</option>
                    </select>
                </td>
                <td>
                    <select class="form-control item-select" name="items_name[]">
                        <option value="">- Select -</option>
                    </select>
                </td>
                <td><input type="text" class="form-control" name="bori[]"></td>
                <td><input type="text" class="form-control" name="weight[]"></td>
                <td><input type="text" class="form-control" name="rate[]"></td>
                <td><input type="text" class="form-control" name="amount[]"></td>
                <td>
                    <button type="button" class="btn rounded shadow-base" onclick="removeRow(this)">
                        <i class="text-danger fa-solid fa-trash-can"></i>
                    </button>
                </td>
            </tr>`;
            $('#item-table tbody').append(row);

            // Populate marka and item selects in the new row
            populateMarkaAndItems($('#item-table tbody tr:last'));
        }

        function removeRow(button) {
            $(button).closest('tr').remove();
            updateTotals();
        }

        function addBoriRow() {
            var row = `
            <tr>
                <td><input type="text" class="form-control" name="bori_number[]"></td>
                <td><input type="text" class="form-control" name="per_bori_weight[]"></td>
                <td>
                    <button type="button" class="btn rounded shadow-base" onclick="removeBoriRow(this)">
                        <i class="text-danger fa-solid fa-trash-can"></i>
                    </button>
                </td>
            </tr>`;
            $('#bori-table tbody').append(row);
        }

        function removeBoriRow(button) {
            $(button).closest('tr').remove();
        }

        function populateMarkaAndItems(newRow) {
            var truckId = $('#truck').val();
            if (truckId) {
                $.ajax({
                    url: '{{ route('get.truck.items', '__TRUCK_ID__') }}'.replace('__TRUCK_ID__', truckId),
                    type: 'GET',
                    success: function(data) {
                        // Populate marka select in the new row
                        newRow.find('.marka-select').empty().append('<option value="">- Select -</option>');
                        $.each(data.markas, function(_, marka) {
                            newRow.find('.marka-select').append(
                                `<option value="${marka}">${marka}</option>`);
                        });

                        // Populate item select in the new row
                        newRow.find('.item-select').empty().append('<option value="">- Select -</option>');
                    }
                });
            }
        }

        // Fetch items and markas when the truck is selected
        $('#truck').on('change', function() {
            alert('as');
            var truckId = $(this).val();
            if (truckId) {
                $('#item-table tbody tr').each(function() {
                    populateMarkaAndItems($(this));
                });
            }
        });

        // Fetch items based on selected marka
        $('#item-table').on('change', 'select[name="marka[]"]', function() {
            var marka = $(this).val();
            var truckId = $('#truck').val();
            if (marka && truckId) {
                $.ajax({
                    url: '{{ route('get.items.by.marka', ['truckId' => '__TRUCK_ID__', 'marka' => '__MARKA__']) }}'
                        .replace('__TRUCK_ID__', truckId).replace('__MARKA__', marka),
                    type: 'GET',
                    success: function(data) {
                        var itemSelect = $(this).closest('tr').find('.item-select');
                        itemSelect.empty().append('<option value="">- Select -</option>');
                        $.each(data, function(id, name) {
                            itemSelect.append(`<option value="${name}">${name}</option>`);
                        });
                    }.bind(this)
                });
            }
        });

        function validateCommissionRate() {
            let commissionRateInput = $('#commission_rate');
            let commissionRateValue = parseFloat(commissionRateInput.val()) || 0;
            let maxCommissionRate = 100;

            if (commissionRateValue > maxCommissionRate) {
                commissionRateInput.val(maxCommissionRate);
            }
        }

        // Bind the validation function to the input event
        $('#commission_rate').on('input', validateCommissionRate);

        function updateTotals() {
            let totalBori = 0;
            let totalWeight = 0;
            let totalAmount = 0;
            let initialCashReceived = 0;

            // Loop through each row to calculate totals
            $('#item-table tbody tr').each(function() {
                let bori = parseFloat($(this).find('input[name="bori[]"]').val()) || 0;
                let weight = parseFloat($(this).find('input[name="weight[]"]').val()) || 0;
                let amount = parseFloat($(this).find('input[name="amount[]"]').val()) || 0;

                totalBori += bori;
                totalWeight += weight;
                totalAmount += amount;
            });

            // Get the input values
            let labour = parseFloat($('input[name="labour"]').val()) || 0;
            let marketfee = parseFloat($('input[name="market_fees"]').val()) || 0;
            let postexp = parseFloat($('input[name="post_expense"]').val()) || 0;
            let miscellaneousExp = parseFloat($('input[name="miscellaneous_expense"]').val()) || 0;
            let commissionp = parseFloat($('input[name="commission_rate"]').val()) || 0;
            let commission = parseFloat($('input[name="commission"]').val()) || 0;
            let more = parseFloat($('input[name="more"]').val()) || 0;

            // Calculate the new cash received value
            let cashReceived = initialCashReceived + labour + marketfee + postexp + miscellaneousExp + commission + more;

            // Calculate commission value
            let commissionVal = (totalAmount * commissionp) / 100;

            // Update fields
            $('#total_bori').val(totalBori);
            $('#weight').val(totalWeight);
            $('#total_amount').val(totalAmount);
            $('#cash_received').val(cashReceived);
            $('#commission').val(commissionVal.toFixed(2)); // Ensure commission value is properly formatted

            // Update Remaining Amount based on the new Cash Received value
            $('#remaining_amount').val(totalAmount - cashReceived);
        }

        function handleInputChange() {
            // Bind input events directly without debouncing for real-time updates
            $('#item-table').on('input', 'input[name="bori[]"], input[name="amount[]"], input[name="weight[]"]',
                updateTotals);

            $('input[name="more"], input[name="commission"], input[name="miscellaneous_expense"], input[name="post_expense"], input[name="market_fees"], input[name="labour"], #cash_received, input[name="commission_rate"]')
                .on('input', updateTotals);
        }

        // Call handleInputChange to bind event listeners after the document is ready
        $(document).ready(function() {
            handleInputChange();
            updateTotals(); // Initial call to set totals on page load
        });
        // Initialize the input change handler
        $(document).ready(function() {
            $('#suppliers').select2({
                theme: 'default'
            });
            $("#sales_date").datepicker({
                dateFormat: "yy-mm-dd"
            });

            $('#customers').select2({
                theme: 'default'
            });

            handleInputChange();
            // Update totals when rows are added or removed
            $('#item-table').on('DOMSubtreeModified', updateTotals);

            // for truck custom dropdown

            // Toggle custom dropdown content
            $('#truck-toggle').click(function() {
                $('.dropdown-content').toggle();
            });

            // Handle truck selection
            $('.truck-details').click(function() {
                var truckId = $(this).data('truck-id');
                var truckNumber = $(this).find('td:first').text();

                // Update the hidden select element
                $('#truck').val(truckId);

                if (truckId) {
                    $('#item-table tbody tr').each(function() {
                        populateMarkaAndItems($(this));
                    });
                }

                // Update the custom dropdown display
                $('#truck-toggle').text(truckNumber);

                // Hide the dropdown content
                $('.dropdown-content').hide();
            });

            // Hide the custom dropdown if clicked outside
            $(document).click(function(event) {
                if (!$(event.target).closest('.custom-dropdown').length) {
                    $('.dropdown-content').hide();
                }
            });
        });
        // Filter the truck table based on search input
        function showOnlyThisTruckDetails(searchKeys) {
            // Convert searchKeys to lowercase for case-insensitive search
            var filter = searchKeys.toLowerCase();

            // Loop through all rows in the table and hide those that don't match the search query
            $('#truck-table-body tr').each(function() {
                var truckNo = $(this).find('td:first').text().toLowerCase();

                if (truckNo.includes(filter)) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        }
    </script>
@endpush
