@extends('layouts.master')

@section('content')
    <div>
        <div class="card shadow">
            <div class="card-header  text-Dark">
                <h3 class="mb-0">Stock At Hand Report</h3>
            </div>
            <div class="card-body">
                <!-- Stock Report Form -->
                <form id="stock-report-form" action="{{ route('stock_report.generate') }}" method="POST">
                    @csrf
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="truck-select">Truck</label>
                                <select id="truck-select" class="form-control select2">
                                    <option value="">-- Select Truck --</option>
                                    @foreach ($trucks as $truck)
                                        <option value="{{ $truck->id_truck }}">{{ $truck->truck_no }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="supplier-select">Supplier</label>
                                <select id="supplier-select" class="form-control select2" disabled>
                                    <option value="">-- Select Supplier --</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 Stock Report</button>

                    </div>
                </div>

                <div class="my-5">
                    <h1>Stock Report</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>

                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">Group By:</h5>
                        <div class="row">
                            <div class="col-6 ">
                                <div class="form-check form-check-inline">
                                    <input type="radio" class="form-check-input" name="group_by" value="client">
                                    <label class="form-check-label">Client</label>
                                </div>
                            </div>
                            <div class="col-6 ">
                                <div class="form-check form-check-inline">
                                    <input type="radio" class="form-check-input" name="group_by" value="product">
                                    <label class="form-check-label">Product</label>
                                </div>
                            </div>
                            <div class="col-6 ">
                                <div class="form-check form-check-inline">
                                    <input type="radio" class="form-check-input" name="group_by" value="vehicle_no">
                                    <label class="form-check-label">Vehicle No</label>
                                </div>
                            </div>
                            <div class="col-6 ">
                                <div class="form-check form-check-inline">
                                    <input type="radio" class="form-check-input" name="group_by" value="category">
                                    <label class="form-check-label">Category</label>
                                </div>
                            </div>
                            <div class="col-6 ">
                                <div class="form-check form-check-inline">
                                    <input type="radio" class="form-check-input" name="group_by" value="none">
                                    <label class="form-check-label">None</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <br>

                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">View:</h5>
                        <div class="row">
                            <div class="col-6 ">
                                <div class="form-check form-check-inline">
                                    <input type="radio" class="form-check-input" name="view" value="balance">
                                    <label class="form-check-label">Balance</label>
                                </div>
                            </div>
                            <div class="col-6 ">
                                <div class="form-check form-check-inline">
                                    <input type="radio" class="form-check-input" name="view" value="negative">
                                    <label class="form-check-label">Negative</label>
                                </div>
                            </div>
                            <div class="col-6 ">
                                <div class="form-check form-check-inline">
                                    <input type="radio" class="form-check-input" name="view" value="complete_sold">
                                    <label class="form-check-label">Complete Sold</label>
                                </div>
                            </div>
                            <div class="col-6 ">
                                <div class="form-check form-check-inline">
                                    <input type="radio" class="form-check-input" name="view" value="all">
                                    <label class="form-check-label">All</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <br>
                <div class="form-check mb-3">
                    <input type="checkbox" class="form-check-input" id="show_summary_only" name="show_summary_only">
                    <label class="form-check-label" for="show_summary_only">Show Summary Only</label>
                </div>

                <div class="d-flex justify-content-between">
                    <button type="submit" class="btn btn-primary">OK</button>
                    <button type="reset" class="btn btn-secondary">Cancel</button>
                </div>
                </form>
            </div>
        </div>
    </div>
@endsection
@push('scripts')
    <script>
        $(document).ready(function() {
            // Initialize Select2
            $('#supplier-select, #truck-select, #main-category-select, #parent-category-select, #child-category-select')
                .select2({
                    theme: 'default'
                });

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

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

                if (truckId) {
                    $.ajax({
                        url: '{{ route('get-truck-details', ':truck') }}'.replace(':truck',
                            truckId),
                        type: 'GET',
                        success: function(response) {
                            // Populate suppliers
                            let supplierOptions =
                                '<option value="">-- Select Supplier --</option>';
                            response.suppliers.forEach(supplier => {
                                supplierOptions +=
                                    `<option value="${supplier.id_supplier}">${supplier.supplier_name}</option>`;
                            });
                            supplierSelect.html(supplierOptions).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 {
                    supplierSelect.html('<option value="">-- Select Supplier --</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 truckId = $('#truck-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 (!truckId) {
                    alert('Please select a truck.');
                    return;
                }

                // AJAX request to generate report
                $.ajax({
                    url: '{{ route('stock_report.generate') }}',
                    type: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}',
                        truck_id: truckId,
                        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
