@extends('layouts.master')

@section('content')
    <div>
        <div class="card shadow">
            <div class="card-header  text-Dark">
                <h3 class="mb-0">Sale Bill</h3>
            </div>
            <div class="card-body">
                <!-- Sale Bill Form -->
                <form id="stock-report-form" action="{{ route('saleBill.generate') }}" method="POST">
                    @csrf
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="customer-select">Customer</label>
                                <select id="customer-select" class="form-control select2">
                                    <option value="">-- Select Customer --</option>
                                    @foreach ($customers as $customer)
                                        <option value="{{ $customer->id_customers }}">{{ $customer->customer_name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="supplier-select">Customer</label>
                                <select id="supplier-select" class="form-control select2" disabled>
                                    <option value="">-- Select Customer --</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="main-category-select">Main Category</label>
                                <select id="main-category-select" class="form-control select2" disabled>
                                    <option value="">-- Select Main Category --</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="parent-category-select">Parent Category</label>
                                <select id="parent-category-select" class="form-control select2" disabled>
                                    <option value="">-- Select Parent Category --</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="child-category-select">Child Category</label>
                                <select id="child-category-select" class="form-control select2" disabled>
                                    <option value="">-- Select Child Category --</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </form>

                <div class="row mt-3">
                    <div class="col-md-12 text-right">
                        <button id="generate-report-btn" class="btn btn-primary">Generate Sale Bill</button>

                    </div>
                </div>

                <div class="my-5">
                    <h1>Sale Bill</h1>
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Builty Number</th>
                                <th>Truck Number</th>
                                <th>Supplier</th>
                                <th>Main Product</th>
                                <th>Parent Product</th>
                                <th>Child Product</th>
                                <th>Marka</th>
                                <th>Total Recieved Bori</th>
                                <th>Sell Bori</th>
                                <th>Remaining Bori</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>

                </form>
            </div>
        </div>
    </div>
@endsection
@push('scripts')
    <script>
        $(document).ready(function() {
            // Initialize Select2
            $('#supplier-select, #customer-select, #main-category-select, #parent-category-select, #child-category-select')
                .select2({
                    theme: 'default'
                });

            // For get the data
            $('#customer-select').on('change', function() {
                const customerId = $(this).val();
                const customerSelect = $('#supplier-select');
                const mainCategorySelect = $('#main-category-select');
                const parentCategorySelect = $('#parent-category-select');
                const childCategorySelect = $('#child-category-select');

                // Disable dropdowns while fetching
                customerSelect.attr('disabled', true);
                mainCategorySelect.attr('disabled', true);
                parentCategorySelect.attr('disabled', true);
                childCategorySelect.attr('disabled', true);

                if (customerId) {
                    $.ajax({
                        url: '{{ route('get-customer-details', ':truck') }}'.replace(':truck',
                            customerId),
                        type: 'GET',
                        success: function(response) {
                            // Populate customers
                            let truckOptions =
                                '<option value="">-- Select truck --</option>';
                            response.trucks.forEach(truck => {
                                truckOptions +=
                                    `<option value="${truck.id_truck}">${truck.truck_no}</option>`;
                            });
                            truckSelect.html(truckOptions).attr('disabled', false);

                            // Populate main categories
                            let mainCategoryOptions =
                                '<option value="">-- Select Main Category --</option>';
                            response.mainCategories.forEach(category => {
                                mainCategoryOptions +=
                                    `<option value="${category.id_pro_cate_main}">${category.products_category_name}</option>`;
                            });
                            mainCategorySelect.html(mainCategoryOptions).attr('disabled',
                                false);

                            // Populate parent categories
                            let parentCategoryOptions =
                                '<option value="">-- Select Parent Category --</option>';
                            response.parentCategories.forEach(category => {
                                parentCategoryOptions +=
                                    `<option value="${category.id_pro_sub_cat_parent}">${category.name}</option>`;
                            });
                            parentCategorySelect.html(parentCategoryOptions).attr('disabled',
                                false);

                            // Populate child categories
                            let childCategoryOptions =
                                '<option value="">-- Select Child Category --</option>';
                            response.childCategories.forEach(category => {
                                childCategoryOptions +=
                                    `<option value="${category.id_pro_sub_cat_child}">${category.name}</option>`;
                            });
                            childCategorySelect.html(childCategoryOptions).attr('disabled',
                                false);
                        },
                        error: function() {
                            alert('An error occurred while fetching data.');
                        }
                    });
                } else {
                    customerSelect.html('<option value="">-- Select Customer --</option>').attr('disabled',
                        true);
                    mainCategorySelect.html('<option value="">-- Select Main Category --</option>').attr(
                        'disabled', true);
                    parentCategorySelect.html('<option value="">-- Select Parent Category --</option>')
                        .attr('disabled', true);
                    childCategorySelect.html('<option value="">-- Select Child Category --</option>').attr(
                        'disabled', true);
                }
            });

            // For generate the report
            $('#generate-report-btn').click(function(e) {
                e.preventDefault();

                // Collect selected values
                const customerId = $('#customer-select').val();
                const supplierId = $('#supplier-select').val();
                const mainCategoryId = $('#main-category-select').val();
                const parentCategoryId = $('#parent-category-select').val();
                const childCategoryId = $('#child-category-select').val();

                // Validate inputs
                if (!customerId) {
                    alert('Please select a truck.');
                    return;
                }

                // AJAX request to generate report
                $.ajax({
                    url: '{{ route('saleBill.generate') }}',
                    type: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}',
                        truck_id: customerId,
                        supplier_id: supplierId,
                        main_category_id: mainCategoryId,
                        parent_category_id: parentCategoryId,
                        child_category_id: childCategoryId,
                    },
                    success: function(response) {
                        console.log(response);
                        // Clear the table body
                        const tableBody = $('table tbody');
                        tableBody.empty();

                        // Populate table with response data
                        response.data.forEach(item => {
                            tableBody.append(`
                        <tr>
                            <td>${item.date}</td>
                            <td>${item.builty_number}</td>
                            <td>${item.truck_number}</td>
                            <td>${item.supplier_name}</td>
                            <td>${item.main_product}</td>
                            <td>${item.parent_product}</td>
                            <td>${item.child_product}</td>
                            <td>${item.marka}</td>
                            <td>${item.total_received_bori}</td>
                            <td>${item.sold_bori}</td>
                            <td>${item.remaining_bori}</td>
                        </tr>
                    `);
                        });
                    },
                    error: function(xhr) {
                        console.error('Error generating report:', xhr.responseText);
                        alert('Unable to generate report. Please try again.');
                    }
                });
            });
        });
    </script>
@endpush
