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

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

    .az-content-label {
        margin-top: 10px
    }
</style>

@section('content')
    <!-- Breadcrumb and Page Title -->
    <div class="az-content-breadcrumb">
        <span>Sale Rate Application</span>
        <span>Apply Sales Rate</span>
    </div>
    <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">Sale Rate Application</h5>
                <form action="{{ route('sales.rate.apply') }}" method="POST" enctype="multipart/form-data">
                    @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="sales_rate_date">Date</label>
                                <input type="text" class="form-control" name="sales_rate_date" id="sales_rate_date"
                                    required autocomplete="off">
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="az-content-label" for="truck">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-3">
                            <label class="az-content-label" for="sales_status">Products</label>
                            <select id="sales_status" name="sales_status" class="form-control">
                                <option value="">Select</option>
                                <option value="1" selected>Active</option>
                                <option value="0" {{ old('sales_status') == '0' ? 'selected' : '' }}>
                                    In-Active
                                </option>
                            </select>
                            @error('sales_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" id="item-table">
                                    <thead>
                                        <tr>
                                            <th
                                                style="font-size: 1.3vh; color: black; text-align: left;  font-family: 'Jameel Noori Nastaleeq', serif;">
                                                Sno
                                            </th>
                                            <th
                                                style="font-size: 1.3vh; color: black; text-align: left;  font-family: 'Jameel Noori Nastaleeq', serif;">
                                                Client
                                            </th>
                                            <th
                                                style="font-size: 1.3vh; color: black; text-align: left;  font-family: 'Jameel Noori Nastaleeq', serif;">
                                                Vehicle No
                                            </th>
                                            <th
                                                style="font-size: 1.3vh; color: black; text-align: left;  font-family: 'Jameel Noori Nastaleeq', serif;">
                                                Product
                                            </th>
                                            <th
                                                style="font-size: 1.3vh; color: black; text-align: left;  font-family: 'Jameel Noori Nastaleeq', serif;">
                                                Marks
                                            </th>
                                            <th
                                                style="font-size: 1.3vh; color: black; text-align: left;  font-family: 'Jameel Noori Nastaleeq', serif;">
                                                Qty
                                            </th>
                                            <th
                                                style="font-size: 1.3vh; color: black; text-align: left;  font-family: 'Jameel Noori Nastaleeq', serif;">
                                                Weight
                                            </th>
                                            <th
                                                style="font-size: 1.3vh; color: black; text-align: left;  font-family: 'Jameel Noori Nastaleeq', serif;">
                                                Price
                                            </th>
                                            <th
                                                style="font-size: 1.3vh; color: black; text-align: left;  font-family: 'Jameel Noori Nastaleeq', serif;">
                                                Basic Amount
                                            </th>
                                            <th
                                                style="font-size: 1.3vh; color: black; text-align: left;  font-family: 'Jameel Noori Nastaleeq', serif;">
                                                Remarks
                                            </th>
                                            {{-- <th
                                                style="font-size: 2vh; color: black; font-family: 'Jameel Noori Nastaleeq', serif; ">
                                                Action
                                            </th> --}}
                                        </tr>
                                    </thead>
                                    <tbody></tbody>
                                </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" required
                                    disabled>
                            </div>
                            <button type="button" class="btn btn-az-primary pd-x-20 mt-3" id="apply_price_btn"
                                disabled>Apply</button>
                        </div>


                        <div class="mt-5">
                            <a href="{{ url('admin') }}" class="btn btn-danger pd-x-20">Cancel</a>
                            <button type="submit" class="btn btn-az-primary pd-x-20">Save</button>
                        </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script type="text/javascript">
        $(document).ready(function() {
            // Enable the price input and apply button when a truck is selected
            $('.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);

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

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

                // Enable the price input and apply button
                $('#custom_price').prop('disabled', false);
                $('#apply_price_btn').prop('disabled', false);

                // Make an AJAX request to fetch sale and item details
                $.ajax({
                    url: '{{ route('sales.getTruckDetails') }}',
                    type: 'GET',
                    data: {
                        truck_id: truckId
                    },
                    success: function(data) {
                        // Clear the item details table
                        $('#item-table tbody').empty();
                        $.each(data.sales_items, function(index, item) {
                            var row = '<tr>' +
                                '<td><input type="text" class="form-control" name="sno[]" value="' +
                                (index + 1) + '" readonly></td>' +
                                '<td><input type="text" class="form-control" name="client_name[]" value="' +
                                data.client_name + '" readonly></td>' +
                                '<td><input type="text" class="form-control" name="vehicle_no[]" value="' +
                                data.vehicle_no + '" readonly></td>' +
                                '<td><input type="text" class="form-control" name="items_name[]" value="' +
                                item.items_name + '" readonly></td>' +
                                '<td><input type="text" class="form-control" name="marka[]" value="' +
                                item.marka + '" readonly></td>' +
                                '<td><input type="text" class="form-control" name="bori[]" value="' +
                                item.bori + '" readonly></td>' +
                                '<td><input type="text" class="form-control" name="weight[]" value="' +
                                item.weight + '" readonly></td>' +
                                '<td><input type="text" class="form-control amount-input" name="amount[]" value="' +
                                item.amount + '"></td>' +
                                '<td><input type="text" class="form-control" name="rate[]" value="' +
                                item.rate + '" readonly></td>' +
                                '<td><input type="text" class="form-control" name="notes[]" value="' +
                                item.notes + '"></td>' +
                                // Hidden field for SalesItemDetail ID
                                '<td><input type="hidden" name="sales_item_detail_ids[]" value="' +
                                item.id_sid + '"></td>' +
                                '</tr>';
                            $('#item-table tbody').append(row);
                        });
                    },
                    error: function(xhr, status, error) {
                        console.error("An error occurred while fetching the details: ", error);
                    }
                });
            });

            // Apply the custom price to all item amounts
            $('#apply_price_btn').click(function() {
                var customPrice = $('#custom_price').val();
                if (customPrice) {
                    $('.amount-input').val(customPrice);
                }
            });

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

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

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

            // 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);

                // 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
