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

    .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
    }

    .urdu-font {
        font-size: 17px;
    }

    .disabled {
        opacity: 0.5;
        pointer-events: none;
    }
</style>

@section('content')
    <!-- Breadcrumb and Page Title -->
    <div class="az-content-breadcrumb">
        <span>Home</span>
        <span>Sales Rate Application</span>
    </div>
    <h2 class="az-content-title" style="display: inline">
        Apply Rates
    </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">Sales Rate Application</h5>
                <form action="{{ route('sale_rate.apply') }}" 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-6">
                            <div class="form-group">
                                <label class="az-content-label" for="sale_rate_date">Date</label>
                                <input type="text" class="form-control" name="sale_rate_date" id="sale_rate_date"
                                    readonly required>
                            </div>
                        </div>

                        {{-- Truck Entries End --}}
                        <div class="col-md-12 mt-3">
                            <div class="form-group">
                                <label class="az-content-label urdu-font" for="truck" style="float: right;">
                                    <span style="color:red;">*</span> ٹرک نمبر
                                </label>

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

                                <!-- Visible custom dropdown -->
                                <div class="custom-dropdown">
                                    <div class="selected-trucks mt-2" id="selected-trucks"></div>
                                    <div class="dropdown-toggle form-control" id="truck-toggle">- Select -</div>
                                    <!-- Display selected truck here -->
                                    <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>Select</th>
                                                    <th>Truck No</th>
                                                    <th>Supplier</th>
                                                    <th>Main Category</th>
                                                    <th>Parent Category</th>
                                                    <th>Child Category</th>
                                                    <th>Marka</th>
                                                    <th>Bori</th>
                                                    <th>Weight</th>
                                                    <th>Price</th>
                                                    <th>Total Amount</th>
                                                </tr>
                                            </thead>
                                            <tbody id="truck-table-body">
                                                @foreach ($sales as $sale)
                                                    @if (!is_null($sale->goodReceiptTruck))
                                                        @foreach ($sale->salesItemsDetails as $saleDetails)
                                                            <tr class="truck-details"
                                                                data-truck-id="{{ $sale->goodReceiptTruck->id_truck }}"
                                                                data-truck-no="{{ $sale->goodReceiptTruck->truck_no }}"
                                                                data-salesdetails-id="{{ $saleDetails->id_sid }}"
                                                                data-supplier-id="{{ $sale->goodReceiptTruck->goodReceiptDetails->first()->goodReceipt->supplier->id_supplier }}"
                                                                data-rent-received="{{ $sale->goodReceiptTruck->goodReceiptDetails->first()->goodReceipt->rent_recieve }}">
                                                                <td>
                                                                    <input type="checkbox" class="truck-checkbox" hidden
                                                                        data-truck-id="{{ $sale->goodReceiptTruck->id_truck }}">
                                                                    <span class="checkbox-icons">
                                                                        <i
                                                                            class="fa-solid fa-circle-check text-success d-none"></i>
                                                                        <i class="fa-regular fa-circle-xmark text-dark"></i>
                                                                    </span>
                                                                </td>

                                                                <td>{{ $sale->goodReceiptTruck->truck_no }}</td>
                                                                <td>{{ $sale->goodReceiptTruck->goodReceiptDetails->first()->goodReceipt->supplier->supplier_name ?? 'N/A' }}
                                                                </td>
                                                                <td>{{ $saleDetails->items_main_cate }}</td>
                                                                <td>{{ $saleDetails->items_parent_cate }}</td>
                                                                <td>{{ $saleDetails->items_child_cate }}</td>
                                                                <td>{{ $saleDetails->marka }}</td>
                                                                <td>{{ $saleDetails->bori }}</td>
                                                                <td>{{ $saleDetails->weight }}</td>
                                                                <td>{{ $saleDetails->rate }}</td>
                                                                <td>{{ $saleDetails->amount }}</td>
                                                            </tr>
                                                        @endforeach
                                                    @endif
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {{-- Truck Entries End --}}

                        <!-- 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: 13px; color: black; text-align: left;">
                                                Main Cate
                                            </th>
                                            <th style="font-size: 13px; color: black; text-align: left;">
                                                Parent Cate
                                            </th>
                                            <th style="font-size: 13px; color: black; text-align: left;">
                                                Child Cate
                                            </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 id="item-details">
                                        <!-- Dynamic rows will be added here -->
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <th colspan="5" style="text-align: right;">Grand Total</th>
                                            <th style="font-family: 'Jameel Noori Nastaleeq', serif;">
                                                <span>Total Bori </span>
                                                <span id="total-bori">0</span>
                                            </th>
                                            <th style="font-family: 'Jameel Noori Nastaleeq', serif;">
                                                <span>Total Weight </span>
                                                <span id="total-weight">0</span>
                                            </th>
                                            {{-- <th></th> --}}
                                            <th style="font-family: 'Jameel Noori Nastaleeq', serif;">
                                                <span>Total Amount </span>
                                                <span id="total-amount">0</span>
                                            </th>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>

                        <div class="col-md-3 mt-5">
                            <div class="form-group">
                                <label class="az-content-label" for="custom_price">Price</label>
                                <input type="text" class="form-control" name="custom_price" id="custom_price"
                                    value="{{ old('custom_price') }}" required disabled onkeyup="formatWithCommas(this)">
                            </div>
                            <button type="button" class="btn btn-az-primary pd-x-20 mt-3" id="apply_price_btn"
                                onclick="calculateAmount()" disabled>
                                Apply
                            </button>
                        </div>

                        <div class="mt-5">
                            <button type="submit" class="btn btn-az-primary pd-x-20 float-end">Save</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script type="text/javascript">
        function calculateAmount() {
            // Get the new rate (after removing commas) and ensure it's treated as a number
            var newRate = parseFloat($('#custom_price').val().replace(/,/g, ''));

            // Iterate through each row in the item-details table to apply the rate and calculate the amount
            $('#item-details tr').each(function() {
                // Get the weight and rate inputs from each row
                var weight = parseFloat($(this).find('.weight-input').val());
                var oldRate = parseFloat($(this).find('.rate-input').val());

                // Calculate the new amount using the formula (newRate * weight) / 40
                let newAmount = (newRate * weight) / 40;

                // Update the rate and amount in both the input fields and their corresponding span elements
                $(this).find('.rate-input').val(newRate);
                $(this).find('.amount-input').val(newAmount);

                $(this).find('.rateSet').text(newRate);
                $(this).find('.amountSet').text(newAmount);
            });
        }

        function calculateTotals() {
            var totalBori = 0;
            var totalWeight = 0;
            var totalAmount = 0;

            // Loop through all rows in the table
            $('#item-details tr').each(function() {
                var bori = parseFloat($(this).find('.bori-input').val()) || 0;
                var weight = parseFloat($(this).find('.weight-input').val()) || 0;
                var amount = parseFloat($(this).find('.amount-input').val()) || 0;

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

            // Update the totals in the footer
            $('#total-bori').text(totalBori.toFixed());
            $('#total-weight').text(totalWeight.toFixed());
            $('#total-amount').text(totalAmount.toFixed());
        }

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

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

            $("#sale_rate_date").datepicker({
                dateFormat: "yy-mm-dd"
            });
        });

        // For truck drop-down
        $(document).ready(function() {
            let selectedTruckNumbers = [];
            let selectedTruckIds = [];
            let selectedSuppliers = new Set();

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

            $('#truck-search').on('input', function() {
                showOnlyThisTruckDetails(this.value);
            });

            // Handle checkbox selection and icon toggle
            $('.truck-checkbox').on('change', function() {
                $('#custom_price').prop('disabled', false);
                $('#apply_price_btn').prop('disabled', false);
                const truckId = $(this).data('truck-id');
                const truckNo = $(this).closest('tr').data('truck-no');
                const salesDetailsId = $(this).closest('tr').data('salesdetails-id');
                const supplierName = $(this).closest('tr').find('td:nth-child(3)').text().trim();
                const supplierId = $(this).closest('tr').data('supplier-id');
                const icons = $(this).siblings('.checkbox-icons');

                if (this.checked) {
                    selectedTruckNumbers.push(truckNo);
                    selectedTruckIds.push(truckId);
                    selectedSuppliers.add(supplierName);

                    // Show the checked icon, hide the unchecked icon
                    icons.find('.fa-circle-check').removeClass('d-none');
                    icons.find('.fa-circle-xmark').addClass('d-none');

                    // Reflect the selected truck's details in the Item Details table
                    appendSelectedTruckDetails($(this).closest('tr'));
                } else {
                    const index = selectedTruckNumbers.indexOf(truckNo);
                    if (index > -1) {
                        selectedTruckNumbers.splice(index, 1);
                        selectedTruckIds.splice(index, 1);
                    }

                    // Hide the checked icon, show the unchecked icon
                    icons.find('.fa-circle-check').addClass('d-none');
                    icons.find('.fa-circle-xmark').removeClass('d-none');

                    // Remove the unselected truck's details from the Item Details table
                    removeTruckDetails(salesDetailsId, $(this).closest('tr'));

                    // Update suppliers dropdown and check if supplier still exists
                    let supplierStillExists = false;
                    $('.truck-details').each(function() {
                        const otherSupplier = $(this).find('td:nth-child(3)').text().trim();
                        const otherTruckNo = $(this).data('truck-no');
                        if (selectedTruckNumbers.includes(otherTruckNo) && otherSupplier ===
                            supplierName) {
                            supplierStillExists = true;
                        }
                    });
                    if (!supplierStillExists) {
                        selectedSuppliers.delete(supplierName);
                    }
                }

                updateSelectedTrucks(truckNo);
                updateSuppliersDropdown(supplierId);
                filterTruckDetails();
            });

            // Function to append the selected truck's data in the Item Details table
            function appendSelectedTruckDetails(truckRow) {
                const truckNo = truckRow.data('truck-no');
                const salesDeId = truckRow.data('salesdetails-id');

                const mainCate = truckRow.find('td:nth-child(4)').text();
                const parentCate = truckRow.find('td:nth-child(5)').text();
                const childCate = truckRow.find('td:nth-child(6)').text();
                const marka = truckRow.find('td:nth-child(7)').text();
                const bori = parseFloat(truckRow.find('td:nth-child(8)').text());
                const weight = parseFloat(truckRow.find('td:nth-child(9)').text());
                const rate = parseFloat(truckRow.find('td:nth-child(10)').text());
                const amount = parseFloat(truckRow.find('td:nth-child(11)').text());

                // Append the selected truck's details as a new row
                $('#item-details').append(`
                    <tr data-truck-no="${truckNo}" data-salesdetails-id="${salesDeId}">
                        <input type="hidden" name="salesDeId[]" value="${salesDeId}">
                        <td><input type="text" name="mainCate[]" hidden value="${mainCate}">${mainCate}</td>
                        <td><input type="text" name="parentCate[]" hidden value="${parentCate}">${parentCate}</td>
                        <td><input type="text" name="childCate[]" hidden value="${childCate}">${childCate}</td>
                        <td><input type="text" name="marka[]" hidden value="${marka}">${marka}</td>
                        <td><input type="text" class="form-control bori-input" name="bori[]" hidden value="${bori}"><span class="boriSet">${bori}</span></td>
                        <td><input type="text" class="form-control weight-input" name="weight[]" hidden value="${weight}"><span class="weightSet">${weight}</span></td>
                        <td><input type="text" class="form-control rate-input" name="rate[]" hidden value="${rate}"><span class="rateSet">${rate}</span></td>
                        <td><input type="text" class="form-control amount-input" name="amount[]" hidden value="${amount}"><span class="amountSet">${amount}</span></td>
                    </tr>
                `);

                calculateTotals();
            }

            // Function to remove a truck's details from the Item Details table when unchecked
            function removeTruckDetails(salesDetailsId, truckRow) {
                const truckNo = truckRow.data('truck-no');
                const salesDeId = truckRow.data('salesdetails-id');

                $(`#item-details tr[data-salesdetails-id="${salesDetailsId}"]`).remove();

                calculateTotals();
            }


            $(document).click(function(event) {
                if (!$(event.target).closest('.custom-dropdown').length) {
                    $('.dropdown-content').hide();
                }
            });

            function updateSelectedTrucks(truckNo) {
                $('#selected-trucks').text('Selected Truck: ' + truckNo);
                selectedTruckIds.forEach(function(truckId) {
                    $('#truck').append('<option value="' + truckId + '" selected>' + truckNo + '</option>');
                });
                $('#truck-toggle').html(truckNo);
            }

            function updateSuppliersDropdown(supplierId) {
                const $supplierDropdown = $('#suppliers');
                $supplierDropdown.html('');

                if (selectedSuppliers.size > 0) {
                    selectedSuppliers.forEach(function(supplier) {
                        $supplierDropdown.append('<option value="' + supplierId + '" selected>' + supplier +
                            '</option>');
                    });
                } else {
                    $supplierDropdown.append('<option value="">- Select -</option>');
                    @foreach ($suppliers as $key => $supplier)
                        $supplierDropdown.append(
                            '<option value="{{ $supplier->id_supplier }}">{{ $supplier->supplier_name }} - {{ $supplier->supplier_name_urdu }}</option>'
                        );
                    @endforeach
                }
            }

            $('#truck-table-body').on('click', '.truck-details', function() {
                const checkbox = $(this).find('.truck-checkbox')[0];
                checkbox.checked = !checkbox.checked;
                $(checkbox).trigger('change');
            });

            function filterTruckDetails() {
                const allTrucks = {};

                $('.truck-details').each(function() {
                    const truckNo = $(this).data('truck-no');
                    const truckId = $(this).data('truck-id');
                    const isSelected = selectedTruckNumbers.includes(truckNo);

                    // Track all trucks with their selection status
                    if (!allTrucks[truckNo]) {
                        allTrucks[truckNo] = {
                            count: 0,
                            checked: 0
                        };
                    }
                    allTrucks[truckNo].count++;
                    if (isSelected) {
                        allTrucks[truckNo].checked++;
                    }
                });

                // Enable or disable rows based on the selection count for each truck number
                $('.truck-details').each(function() {
                    const truckNo = $(this).data('truck-no');
                    const allSelected = allTrucks[truckNo].checked === allTrucks[truckNo].count;

                    if (allSelected) {
                        $(this).find('.truck-checkbox').prop('disabled', false); // Enable checkbox
                        $(this).removeClass('disabled');
                    } else {
                        if (selectedTruckNumbers.length > 0 && !selectedTruckNumbers.includes(truckNo)) {
                            $(this).find('.truck-checkbox').prop('disabled', true); // Disable checkbox
                            $(this).addClass('disabled');
                        } else if ($('.truck-checkbox:checked').length == 0) {
                            $('#selected-trucks').text('Selected Truck: ' + '');
                            $('#custom_price').prop('disabled', true);
                            $('#apply_price_btn').prop('disabled', true);
                            $('#truck').html('');
                            $('#truck-toggle').html('- Select -');
                            $(this).find('.truck-checkbox').prop('disabled', false); // Enable checkbox
                            $(this).removeClass('disabled');
                        }
                    }
                });
            }

            function showOnlyThisTruckDetails(searchValue) {
                searchValue = searchValue.toLowerCase();
                document.querySelectorAll('#truck-table-body .truck-details').forEach(function(row) {
                    const cells = row.querySelectorAll('td');
                    let matchFound = false;

                    cells.forEach(function(cell) {
                        if (cell.textContent.toLowerCase().includes(searchValue)) {
                            matchFound = true;
                        }
                    });

                    row.style.display = matchFound ? '' : 'none';
                });
            }
        });
    </script>
@endpush
