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

@section('content')
    <!-- Breadcrumb and Page Title -->
    <div class="az-content-breadcrumb">
        <span>Sales</span>
        <span>Edit Sale</span>
    </div>
    <h2 class="az-content-title" style="display: inline">
        Edit Sale
        <span>
            <a href="{{ route('sales.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">Edit Sale</h5>
                <form action="{{ route('sales.update', Crypt::encrypt($sale->id_sales)) }}" method="POST">
                    @csrf
                    @method('PUT')

                    <!-- 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_date">Date</label>
                                <input type="text" class="form-control" name="sales_date" id="sales_date"
                                    value="{{ $sale->date }}" required>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label class="az-content-label" for="s_no">SNo</label>
                                <input type="text" class="form-control" name="s_no" id="s_no"
                                    value="{{ $sale->s_no }}" required>
                            </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 }}"
                                            {{ $sale->good_receipts_truck_id == $truck->id_truck ? 'selected' : '' }}>
                                            {{ $truck->truck_no }}
                                        </option>
                                    @endforeach
                                </select>

                                <!-- Visible custom dropdown -->
                                <div class="custom-dropdown">
                                    <div class="dropdown-toggle form-control" id="truck-toggle">{{ $truck->truck_no }}</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" for="customers">Customer</label>
                                <select class="form-control select2" name="customer_id" id="customers" required>
                                    <option value="">- Select -</option>
                                    @foreach ($customers as $customer)
                                        <option value="{{ $customer->id_customers }}"
                                            {{ $sale->customer_id == $customer->id_customers ? 'selected' : '' }}>
                                            {{ $customer->customer_name }} - {{ $customer->customer_name_urdu }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4 mt-3">
                            <div class="form-group">
                                <label class="az-content-label" for="bill_no">Bill Number</label>
                                <input type="text" class="form-control" name="bill_no" id="bill_no"
                                    value="{{ $sale->bill_no }}" required>
                            </div>
                        </div>
                        <div class="col-md-4 mt-3">
                            <label class="az-content-label" for="sales_status">Status</label>
                            <select id="sales_status" name="sales_status" class="form-control">
                                <option value="">- Select -</option>
                                <option value="1" {{ $sale->status == '1' ? 'selected' : '' }}>Active</option>
                                <option value="0" {{ $sale->status == '0' ? 'selected' : '' }}>In-Active</option>
                            </select>
                            @error('sales_status')
                                <span class="form-text text-danger">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                        <div class="row">
                            <div class="col-md-4 mt-3">
                                <div class="form-group">
                                    <label class="az-content-label" for="details">Details</label>
                                    <textarea class="form-control" name="details" id="details" cols="5" rows="5">{{ $sale->details }}</textarea>
                                </div>
                            </div>
                            <div class="col-md-4 mt-3">
                                <div class="form-group">
                                    <label class="az-content-label" for="bori_details">Bori Details</label>
                                    <textarea class="form-control" name="bori_details" id="bori_details" cols="5" rows="5">{{ $sale->bori_details }}</textarea>
                                </div>
                            </div>
                        </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>Marka</th>
                                            <th>Item</th>
                                            <th>Bori</th>
                                            <th>Weight</th>
                                            <th>Rate</th>
                                            <th>Amount</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach ($sale->salesItemsDetails as $itemDetail)
                                            <tr data-id="{{ $itemDetail->id_sid }}">
                                                <td>
                                                    <select class="form-control marka-select" name="marka[]"
                                                        id="marka">
                                                        <option value="{{ $itemDetail->marka }}">
                                                            {{ $itemDetail->marka }}
                                                        </option>
                                                    </select>
                                                </td>
                                                <td>
                                                    <select class="form-control item-select" name="items_name[]">
                                                        <option value="{{ $itemDetail->items_name }}">
                                                            {{ $itemDetail->items_name }}
                                                        </option>
                                                    </select>
                                                </td>
                                                <td><input type="number" class="form-control" name="bori[]"
                                                        value="{{ $itemDetail->bori }}"></td>
                                                <td><input type="number" class="form-control" name="weight[]"
                                                        value="{{ $itemDetail->weight }}"></td>
                                                <td><input type="number" class="form-control" name="rate[]"
                                                        value="{{ $itemDetail->rate }}"></td>
                                                <td><input type="number" class="form-control" name="amount[]"
                                                        value="{{ $itemDetail->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>
                                                    <input type="hidden" name="item_detail_ids[]"
                                                        value="{{ $itemDetail->id_sid }}">
                                                </td>
                                            </tr>
                                        @endforeach
                                    </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>

                        <!-- Additional Bori Details Section -->
                        <div class="col-md-12 mt-4">
                            <h4>Additional Bori Details</h4>
                            <div class="shadow p-3 bg-light rounded">
                                <table class="table table-bordered" id="bori-table">
                                    <thead>
                                        <tr>
                                            <th>Bori Number</th>
                                            <th>Weight</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach ($sale->salesPerBoriWeight as $boriDetail)
                                            <tr data-id="{{ $boriDetail->id_sales_per_bw }}">
                                                <td><input type="text" class="form-control" name="bori_number[]"
                                                        value="{{ $boriDetail->bori_number }}"></td>
                                                <td><input type="number" class="form-control" name="per_bori_weight[]"
                                                        value="{{ $boriDetail->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>
                                                    <input type="hidden" name="bori_detail_ids[]"
                                                        value="{{ $boriDetail->id_sales_per_bw }}">
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                                <button type="button" class="btn btn-az-primary btn-block mt-2" onclick="addBoriRow()">
                                    <span class="mdi mdi-arrow-expand-up"></span> Add More
                                </button>
                            </div>
                        </div>

                        <!-- Totals Section -->
                        <div class="row mt-4">
                            <div class="col-md-12">
                                <h4>Totals</h4>
                                <div class="form-group row">
                                    <label for="total_bori" class="col-sm-2 col-form-label">Total Bori:</label>
                                    <div class="col-sm-10">
                                        <input type="number" class="form-control" id="total_bori" name="total_bori"
                                            value="{{ $sale->salesItemsDetails->sum('bori') }}" readonly>
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="remaining_amount" class="col-sm-2 col-form-label">Remaining
                                        Amount:</label>
                                    <div class="col-sm-10">
                                        <input type="number" class="form-control" id="remaining_amount"
                                            name="remaining_amount" value="{{ $sale->balance }}" readonly>
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="cash_received" class="col-sm-2 col-form-label">Cash Received:</label>
                                    <div class="col-sm-10">
                                        <input type="number" class="form-control" id="cash_received"
                                            name="cash_received" value="{{ $sale->paid }}">
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="total_amount" class="col-sm-2 col-form-label">Total Amount:</label>
                                    <div class="col-sm-10">
                                        <input type="number" class="form-control" id="total_amount" name="total_amount"
                                            value="{{ $sale->total_amount }}" readonly>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="mt-5">
                            <a href="{{ route('sales.list') }}" class="btn btn-danger pd-x-20">Cancel</a>
                            <button type="submit" class="btn btn-az-primary pd-x-20">Save</button>
                        </div>
                    </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="number" class="form-control" name="bori[]"></td>
            <td><input type="number" class="form-control" name="weight[]"></td>
            <td><input type="number" class="form-control" name="rate[]"></td>
            <td><input type="number" 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);
            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="number" 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, selectedMarka = null, selectedItem = null) {
            var truckId = $('#truck').val();
            if (truckId) {
                $.ajax({
                    url: '{{ route('get.truck.items', '__TRUCK_ID__') }}'.replace('__TRUCK_ID__', truckId),
                    type: 'GET',
                    success: function(data) {
                        var markaSelect = newRow.find('.marka-select');
                        markaSelect.empty().append('<option value="">- Select -</option>');
                        $.each(data.markas, function(_, marka) {
                            markaSelect.append(
                                `<option value="${marka}" ${marka == selectedMarka ? 'selected' : ''}>${marka}</option>`
                            );
                        });

                        var itemSelect = newRow.find('.item-select');
                        if (selectedItem == null) {
                            itemSelect.empty().append('<option value="">- Select -</option>');
                        }
                        if (selectedMarka && data.items[selectedMarka]) {
                            $.each(data.items[selectedMarka], function(id, name) {
                                itemSelect.append(
                                    `<option value="${name}" ${name == selectedItem ? 'selected' : ''}>${name}</option>`
                                );
                            });
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Error fetching truck items:', error);
                    }
                });
            }
        }

        $('#truck').on('change', function() {
            var truckId = $(this).val();
            if (truckId) {
                $('#item-table tbody tr').each(function() {
                    populateMarkaAndItems($(this));
                });
            }
        });

        $('#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 updateTotals() {
            let totalBori = 0;
            let totalAmount = 0;

            $('#item-table tbody tr').each(function() {
                let bori = parseFloat($(this).find('input[name="bori[]"]').val()) || 0;
                let amount = parseFloat($(this).find('input[name="amount[]"]').val()) || 0;

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

            $('#total_bori').val(totalBori);
            $('#total_amount').val(totalAmount);

            let cashReceived = parseFloat($('#cash_received').val()) || 0;
            $('#remaining_amount').val(totalAmount - cashReceived);
        }

        function handleInputChange() {
            $('#item-table').on('input', 'input[name="bori[]"], input[name="amount[]"]', updateTotals);
            $('#cash_received').on('input', function() {
                let cashReceived = parseFloat($(this).val()) || 0;
                let totalAmount = parseFloat($('#total_amount').val()) || 0;
                $('#remaining_amount').val(totalAmount - cashReceived);
            });
        }

        $(document).ready(function() {
            $("#sales_date").datepicker({
                dateFormat: "yy-mm-dd"
            });

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

            handleInputChange();

            var truckId = $('#truck').val();
            if (truckId) {
                $('#item-table tbody tr').each(function(index) {
                    var itemDetail = {!! json_encode($sale->salesItemsDetails) !!}[index];
                    populateMarkaAndItems($(this), itemDetail.marka, itemDetail.items_name);
                });
            }

            $('#item-table').on('DOMNodeInserted DOMNodeRemoved', updateTotals);

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

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

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

                $('#truck-toggle').text(truckNumber);
                $('.dropdown-content').hide();
            });

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

        function showOnlyThisTruckDetails(searchKeys) {
            var filter = searchKeys.toLowerCase();
            $('#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
