@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;
        color: black !important;
    }

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

@section('content')
    <!-- Breadcrumb and Page Title -->
    <div class="az-content-breadcrumb">
        <span>Goods Receipts Billing / B-Cheque</span>
        <span>Create Goods Receipts Billing / B-Cheque</span>
    </div>
    <h2 class="az-content-title" style="display: inline">
        Create B-Cheque
        <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">Create B-Cheque</h5>
                <form action="{{ route('b_cheque.update', ['id' => Crypt::encrypt($b_cheque->id_b_cheque)]) }}"
                    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="{{ old('sales_date', $b_cheque->sales_date) }}" autocomplete="off" required>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label class="az-content-label" for="pb_no">PBNo</label>
                                <input type="text" class="form-control" name="pb_no" id="pb_no"
                                    value="{{ old('pb_no', $b_cheque->pb_no) }}" required>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="az-content-label az-content-label-urdu" for="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 }}"
                                            {{ $b_cheque->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">
                                        {{ $b_cheque->truck->truck_no ?? '- 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-4 mt-3">
                            <div class="form-group">
                                <label class="az-content-label az-content-label-urdu">سپلائرز</label>
                                <select class="form-control select2" name="suppliers" id="suppliers" required>
                                    <option value="">- Select -</option>
                                    @foreach ($suppliers as $key => $supplier)
                                        <option value="{{ $supplier->id_supplier }}"
                                            {{ $b_cheque->supplier_id == $supplier->id_supplier ? 'selected' : '' }}>
                                            {{ $supplier->supplier_name }} - {{ $supplier->supplier_name_urdu }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            @error('suppliers')
                                <span class="form-text text-danger">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>

                        <div class="col-md-4 mt-3">
                            <div class="form-group">
                                <label class="az-content-label az-content-label-urdu" for="bilty_no">بلٹی نمبر</label>
                                <input type="text" class="form-control" name="bilty_no" id="bilty_no"
                                    value="{{ old('bilty_no', $b_cheque->bilty_no) }}" required>
                            </div>
                        </div>
                        <div class="col-md-4 mt-3">
                            <div class="form-group">
                                <label class="az-content-label az-content-label-urdu" for="detail">تفصیل</label>
                                <input type="text" class="form-control" name="detail" id="detail"
                                    value="{{ old('detail', $b_cheque->detail) }}" 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"
                                    {{ old('sales_status', $b_cheque->sales_status) == '1' ? 'selected' : '' }}>Active
                                </option>
                                <option value="0"
                                    {{ old('sales_status', $b_cheque->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 table-bordered" id="item-table">
                                    <thead>
                                        <tr>
                                            <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>
                                            <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>
                                        @foreach ($b_cheque->items as $item)
                                            <tr>
                                                <td>
                                                    <select class="form-control marka-select" name="marka[]">
                                                        <option value="">- Select -</option>
                                                        <!-- Populate marka options -->
                                                    </select>
                                                </td>
                                                <td>
                                                    <select class="form-control item-select" name="items_name[]">
                                                        <option value="">- Select -</option>
                                                        <!-- Populate item options -->
                                                    </select>
                                                </td>
                                                <td><input type="text" class="form-control" name="bori[]"
                                                        value="{{ $item->bori }}"></td>
                                                <td><input type="text" class="form-control" name="weight[]"
                                                        value="{{ $item->weight }}"></td>
                                                <td><input type="text" class="form-control" name="rate[]"
                                                        value="{{ $item->rate }}"></td>
                                                <td><input type="text" class="form-control" name="amount[]"
                                                        value="{{ $item->amount }}"></td>
                                                <td>
                                                    <button type="button" class="btn btn-danger btn-sm remove-item-row">
                                                        <i class="fa fa-minus-circle" aria-hidden="true"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>

                                <button type="button" class="btn btn-primary btn-sm add-item-row">
                                    <i class="fa fa-plus-circle" aria-hidden="true"></i> Add Row
                                </button>
                            </div>
                        </div>

                        <!-- Form Submission -->
                        <div class="col-md-12 mt-5">
                            <div class="form-group">
                                <button type="submit" class="btn btn-primary">Update</button>
                                <a href="{{ route('b_cheque.list') }}" class="btn btn-secondary">Cancel</a>
                            </div>
                        </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="text" class="form-control" name="bori[]"></td>
                <td><input type="text" class="form-control" name="weight[]"></td>
                <td><input type="text" class="form-control" name="rate[]"></td>
                <td><input type="text" 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(row);
        }

        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="text" 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) {
            var truckId = $('#truck').val();
            if (truckId) {
                $.ajax({
                    url: '{{ route('get.truck.items', '__TRUCK_ID__') }}'.replace('__TRUCK_ID__', truckId),
                    type: 'GET',
                    success: function(data) {
                        // Populate marka select in the new row
                        newRow.find('.marka-select').empty().append('<option value="">- Select -</option>');
                        $.each(data.markas, function(_, marka) {
                            newRow.find('.marka-select').append(
                                `<option value="${marka}">${marka}</option>`);
                        });

                        // Populate item select in the new row
                        newRow.find('.item-select').empty().append('<option value="">- Select -</option>');
                    },
                    error: function() {
                        alert('Failed to fetch marka and item data. Please try again.');
                    }
                });
            }
        }

        $('#truck').on('change', function() {
            var truckId = $(this).val();
            if (truckId) {
                $('#item-table tbody tr').each(function() {
                    populateMarkaAndItems($(this));
                });
            } else {
                // Reset the marka and item selects if no truck is selected
                $('#item-table tbody tr').find('.marka-select, .item-select').empty().append(
                    '<option value="">- Select -</option>');
            }
        });

        $('#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),
                    error: function() {
                        alert('Failed to fetch items. Please try again.');
                    }
                });
            }
        });

        function validateCommissionRate() {
            let commissionRateInput = $('#commission_rate');
            let commissionRateValue = parseFloat(commissionRateInput.val()) || 0;
            let maxCommissionRate = 100;

            if (commissionRateValue > maxCommissionRate) {
                commissionRateInput.val(maxCommissionRate);
            }
        }

        $('#commission_rate').on('input', validateCommissionRate);

        function updateTotals() {
            let totalBori = 0;
            let totalWeight = 0;
            let totalAmount = 0;
            let initialCashReceived = 0;

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

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

            let labour = parseFloat($('input[name="labour"]').val()) || 0;
            let marketfee = parseFloat($('input[name="market_fees"]').val()) || 0;
            let postexp = parseFloat($('input[name="post_expense"]').val()) || 0;
            let miscellaneousExp = parseFloat($('input[name="miscellaneous_expense"]').val()) || 0;
            let commissionp = parseFloat($('input[name="commission_rate"]').val()) || 0;
            let commission = parseFloat($('input[name="commission"]').val()) || 0;
            let more = parseFloat($('input[name="more"]').val()) || 0;

            let cashReceived = initialCashReceived + labour + marketfee + postexp + miscellaneousExp + commission + more;

            let commissionVal = ((totalAmount * commissionp) / 100).toFixed(2);

            $('#total_bori').val(totalBori.toFixed(2));
            $('#weight').val(totalWeight.toFixed(2));
            $('#total_amount').val(totalAmount.toFixed(2));
            $('#cash_received').val(cashReceived.toFixed(2));
            $('#commission').val(commissionVal);

            $('#remaining_amount').val((totalAmount - cashReceived).toFixed(2));
        }

        function handleInputChange() {
            $('#item-table').on('input', 'input[name="bori[]"], input[name="amount[]"], input[name="weight[]"]',
                updateTotals);

            $('input[name="more"], input[name="commission"], input[name="miscellaneous_expense"], input[name="post_expense"], input[name="market_fees"], input[name="labour"], #cash_received, input[name="commission_rate"]')
                .on('input', updateTotals);
        }

        $(document).ready(function() {
            handleInputChange();
            updateTotals();

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

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

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

            $('#item-table').on('DOMSubtreeModified', 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();
                }
            });
        });

        let debounceTimeout;

        function showOnlyThisTruckDetails(searchKeys) {
            clearTimeout(debounceTimeout);
            debounceTimeout = setTimeout(function() {
                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();
                    }
                });
            }, 300);
        }
    </script>
@endpush
