@extends('layouts.master')

@section('content')

    <style>
        @font-face {
            font-family: 'Jameel Noori Nastaleeq';
            src: url('path/to/JameelNooriNastaleeq.woff') format('woff'),
                url('path/to/JameelNooriNastaleeq.ttf') format('truetype');
        }

        .az-content-label-ur {
            font-family: 'Jameel Noori Nastaleeq', serif;
            font-size: 2vh;

            /* margin-bottom: 15px; */
            line-height: 2;
        }

        .urdu-font {
            font-size: 17px;
        }
    </style>
    <!-- Breadcrumb and Page Title -->
    <div class="az-content-breadcrumb">
        <span>Goods Receipts</span>
        <span>Add Goods Receipts</span>
    </div>
    <h2 class="az-content-title" style="display: inline">Add New Goods Receipts
        <span>
            <a href="{{ route('good_receipts.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">Add Goods Receipts</h5>
                <form method="post" action="{{ route('good_receipts.store') }}">
                    @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

                    <!-- Basic Details -->
                    <div class="row row-sm mg-b-20">
                        <!-- Date, PNo, Truck Number -->
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="az-content-label" for="goods_date">Date</label>
                                <input type="text" id="goods_date" name="goods_date" class="form-control"
                                    value="{{ old('goods_date') }}" placeholder="dd/mm/yyyy" readonly />
                            </div>
                            @error('goods_date')
                                <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                            @enderror
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="az-content-label urdu-font" style="float: inline-end;">
                                    <span style="color:red;">*</span>
                                    ٹرک نمبر
                                </label>
                                <input type="text" name="truck_number" class="form-control" required
                                    value="{{ old('truck_number') }}" />
                            </div>
                            @error('truck_number')
                                <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                            @enderror
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="az-content-label urdu-font" style="float: inline-end;">
                                    <span style="color:red;">*</span>
                                    سپلائرز
                                </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 }}">
                                            {{ $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>

                    <!-- Suppliers, Builty Number, Rent Received -->
                    <div class="row row-sm mg-b-20">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="az-content-label urdu-font" style="float: inline-end;">
                                    بلٹی نمبر
                                </label>
                                <input type="text" name="builty_number" class="form-control"
                                    value="{{ old('truck_number') }}" />
                            </div>
                            @error('builty_number')
                                <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                            @enderror
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="az-content-label urdu-font" style="float: inline-end;">
                                    کرایہ وصول
                                </label>
                                <input type="text" name="rent_received" id="rent_received" class="form-control"
                                    value="{{ old('rent_received') }}" />
                            </div>
                            @error('rent_received')
                                <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                            @enderror
                        </div>
                        <div class="col-md-4">
                            <label class="az-content-label" for="goods_status">Status</label>
                            <select id="goods_status" name="goods_status" class="form-control">
                                <option value="">Select</option>
                                <option value="1" {{ old('goods_status') == '1' ? 'selected' : 'selected' }}>
                                    Active
                                </option>
                                <option value="0" {{ old('goods_status') == '0' ? 'selected' : '' }}>
                                    In-Active
                                </option>
                            </select>
                            @error('goods_status')
                                <span class="form-text text-danger">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                    </div>

                    <!-- Details -->
                    <div class="row row-sm mg-b-20">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label class="az-content-label urdu-font" style="float: inline-end;">تفصیلات</label>
                                <textarea class="form-control" name="details" id="details">{{ old('details') }}</textarea>
                            </div>
                            @error('details')
                                <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                            @enderror
                        </div>
                    </div>

                    <!-- Items Section -->
                    <hr class="my-5">
                    <div id="items-wrapper">
                        <div class="row delete_row row-sm mg-b-20 shadow p-3 bg-light rounded" id="item-row-0">
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label class="az-content-label" for="items">Items (مال)</label>
                                    <select name="items[]"id="items" class="form-control">
                                        <option value="">Select Item</option>
                                        @foreach ($products as $key => $product)
                                            <option value="{{ $product->id_products }}">
                                                {{ $product->products_name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                                @error('items')
                                    <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                                @enderror
                            </div>
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label class="az-content-label">Marka (مارکہ)</label>
                                    <input type="text" name="marka[]" class="form-control" />
                                </div>
                                @error('marka')
                                    <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                                @enderror
                            </div>
                            <div class="col-md-1">
                                <div class="form-group">
                                    <label class="az-content-label">Bori (بوری)</label>
                                    <input type="text" name="bori[]" class="form-control" />
                                </div>
                                @error('bori')
                                    <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                                @enderror
                            </div>
                            <div class="col-md-1">
                                <div class="form-group">
                                    <label class="az-content-label">Weight (وزن)</label>
                                    <input type="text" name="weight[]" oninput="calculateAmount(this)"
                                        class="form-control weight-input" />
                                </div>
                                @error('weight')
                                    <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                                @enderror
                            </div>
                            <div class="col-md-1">
                                <div class="form-group">
                                    <label class="az-content-label">Rate (ریٹ)</label>
                                    <input type="text" name="rate[]" oninput="calculateAmount(this)"
                                        class="form-control rate-input" />
                                </div>
                                @error('rate')
                                    <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                                @enderror
                            </div>
                            <div class="col-md-1">
                                <div class="form-group">
                                    <label class="az-content-label">Amount (رقم)</label>
                                    <input type="text" name="amount[]" oninput="calculateAmount(this)"
                                        class="form-control amount-input" readonly />
                                </div>
                                @error('amount')
                                    <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                                @enderror
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label class="az-content-label">Remarks (ریمارکس)</label>
                                    <textarea class="form-control remarks-input" name="remarks[]"></textarea>
                                </div>
                                @error('remarks')
                                    <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                                @enderror
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-12">
                        <button type="button" class="btn btn-az-primary btn-block mt-2" id="add-more">
                            <span class="mdi mdi-arrow-expand-up"></span> Add More
                        </button>
                    </div>

                    <!-- Show Total -->
                    <div class="row row-sm mg-b-20 mt-5" style="float: right;">
                        <div class="col-12">
                            <h3 style="line-height: 2.5rem;">
                                <span>
                                    Total Bori: <span id="total-bori">0</span>
                                </span>
                                <br>
                                <span>
                                    Total Weight: <span id="total-weight">0</span>
                                </span>
                            </h3>
                        </div>
                    </div>

                    <!-- Submit and Cancel Buttons -->
                    <div class="mt-5">
                        <a href="{{ route('good_receipts.list') }}" 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>
    <div id="errorNotification" class="alert alert-danger position-fixed top-0 end-0 m-3" style="display: none;">
        <strong>Error!</strong> <span id="errorMessage">Please select the row you want to delete.</span>
    </div>
@endsection

@push('scripts')
    <script>
        function calculateAmount(element) {
            // Get the closest parent with class "row"
            let row = element.closest('.row');

            // Get the values for weight and rate, with default to 0 if empty
            let weight = parseFloat(row.querySelector('.weight-input').value) || 0;
            let rate = parseFloat(row.querySelector('.rate-input').value) || 0;

            // Calculate the amount (rate * weight / 40)
            let amount = (rate * weight) / 40;

            // Set the calculated amount in the "amount-input" field
            row.querySelector('.amount-input').value = amount.toFixed(2);
        }


        $(document).ready(function() {
            // $("#goods_date").datepicker({
            //     dateFormat: "yy-mm-dd"
            // });
            var today = new Date();
            var formattedDate = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' +
                today.getDate()).slice(-2);

            $("#goods_date").val(formattedDate);

            // Initialize datepicker with custom format
            $("#goods_date").datepicker({
                dateFormat: "yy-mm-dd" // Customize the date format here
            });

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

            $('#items').select2({
                // theme: 'default',
                placeholder: "Select an item",
                allowClear: true
            });
        });

        document.addEventListener("DOMContentLoaded", function() {
            let itemIndex = 1;

            // Function to calculate and update total bori and weight
            function calculateTotals() {
                let totalBori = 0;
                let totalWeight = 0;

                document.querySelectorAll('input[name="bori[]"]').forEach(function(boriInput) {
                    totalBori += parseFloat(boriInput.value) || 0;
                });

                document.querySelectorAll('input[name="weight[]"]').forEach(function(weightInput) {
                    totalWeight += parseFloat(weightInput.value) || 0;
                });

                document.getElementById('total-bori').innerText = totalBori;
                document.getElementById('total-weight').innerText = totalWeight;
            }

            // Event listener to recalculate totals when bori or weight fields are changed
            document.getElementById('items-wrapper').addEventListener('input', function(event) {
                if (event.target.name === 'bori[]' || event.target.name === 'weight[]') {
                    calculateTotals();
                }
            });


            // Function to add a new item row
            //     document.getElementById('add-more').addEventListener('click', function() {
            //         let newRow = document.getElementById('item-row-0').cloneNode(true);
            //         newRow.id = 'item-row-' + itemIndex;
            //         newRow.addClass = 'mt-5';

            //         // Reset the input fields in the cloned row
            //         newRow.querySelectorAll('input, textarea').forEach(function(input) {
            //             input.value = '';
            //         });

            //         // Create the "Remove" trash icon
            //         let removeIcon = document.createElement('i');
            //         removeIcon.className = 'fa fa-trash-alt text-light remove-item bg-danger p-2 rounded-1';
            //         removeIcon.style.cursor = 'pointer';
            //         removeIcon.style.float = 'right';
            //         removeIcon.style.marginTop = '10px';

            //         // Add event to remove the current row and recalculate totals
            //         removeIcon.addEventListener('click', function() {
            //             this.closest('.row').remove();
            //             calculateTotals();
            //         });

            //         // Append the "Remove" icon to the new row
            //         let actionCol = document.createElement('div');
            //         actionCol.className = 'col-md-12';
            //         actionCol.appendChild(removeIcon);
            //         newRow.appendChild(actionCol);

            //         document.getElementById('items-wrapper').appendChild(newRow);
            //         itemIndex++;
            //     });
        });


        let itemIndex = 1; // Start from 1 for cloned rows
        // Event listener for adding a new row when the 'Add More' button is clicked
        // document.getElementById('add-more').addEventListener('click', function() {
        //     addNewRow();
        // });

        // Event listener for detecting 'Tab' key in the last input field
        // document.addEventListener('keydown', function(event) {
        //     let focusedElement = document.activeElement;
        //     if (event.key === 'Tab' && focusedElement.classList.contains('remarks-input')) {
        //         // Prevent default tab behavior if it's the last input
        //         event.preventDefault();
        //         addNewRow();
        //         // Focus the input in the newly created row
        //         document.querySelector(`#item-row-${itemIndex - 1} .item-input`).focus();
        //     }

        //     // Detect Alt + D to delete the selected row
        //     if (event.altKey && event.key === 'd') {
        //         event.preventDefault();

        //         const focusedElement = document.activeElement;
        //         const focusedRow = focusedElement.closest('.row'); // Find the closest row

        //         if (focusedRow) {
        //             focusedRow.remove(); // Remove the focused row

        //             // If no rows remain, reset the itemIndex and add a new row
        //             if (document.querySelectorAll('.row').length === 0) {
        //                 itemIndex = 1; // Reset itemIndex
        //                 addNewRow(); // Add the first row again
        //             }
        //         } else {
        //             showErrorNotification(
        //                 'Please select the row you want to delete.\nبراہ کرم اس صف کو منتخب کریں جسے آپ حذف کرنا چاہتے ہیں۔'
        //                 );
        //         }
        //     }
        // });

        // Function to add a new row
        // function addNewRow() {
        //     let newRow = document.getElementById('item-row-0').cloneNode(true);
        //     newRow.id = 'item-row-' + itemIndex;
        //     newRow.classList.add('mt-5');

        //     // Reset the input fields in the cloned row
        //     newRow.querySelectorAll('input, textarea').forEach(function(input) {
        //         input.value = '';
        //     });

        //     // Create the "Remove" trash icon
        //     let removeIcon = document.createElement('i');
        //     removeIcon.className = 'fa fa-trash-alt text-light remove-item bg-danger p-2 rounded-1';
        //     removeIcon.style.cursor = 'pointer';
        //     removeIcon.style.float = 'right';
        //     removeIcon.style.marginTop = '10px';

        //     // Add event to remove the current row
        //     removeIcon.addEventListener('click', function() {
        //         this.closest('.row').remove();

        //         // If no rows remain, reset the itemIndex and add a new row
        //         if (document.querySelectorAll('.row').length === 0) {
        //             itemIndex = 1; // Reset itemIndex
        //             addNewRow(); // Add the first row again
        //         }
        //     });

        //     // Append the "Remove" icon to the new row
        //     let actionCol = document.createElement('div');
        //     actionCol.className = 'col-md-12';
        //     actionCol.appendChild(removeIcon);
        //     newRow.appendChild(actionCol);

        //     document.getElementById('items-wrapper').appendChild(newRow);
        //     itemIndex++;
        // }

        document.getElementById('add-more').addEventListener('click', function() {
            // Generate the new row HTML
            let newRow = `
                    <div class="row delete_row row-sm mg-b-20 shadow p-3 bg-light rounded mt-5" id="item-row-${itemIndex}">
                        <div class="col-md-2">
                            <div class="form-group">
                                <label class="az-content-label" for="items">Items (مال)</label>
                                <select name="items[]" class="form-control item-select" required>
                                    <option value="">Select Item</option>
                                    @foreach ($products as $key => $product)
                                        <option value="{{ $product->id_products }}">
                                            {{ $product->products_name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label class="az-content-label">Marka (مارکہ)</label>
                                <input type="text" name="marka[]" class="form-control" />
                            </div>
                        </div>
                        <div class="col-md-1">
                            <div class="form-group">
                                <label class="az-content-label">Bori (بوری)</label>
                                <input type="text" name="bori[]" class="form-control" />
                            </div>
                        </div>
                        <div class="col-md-1">
                            <div class="form-group">
                                <label class="az-content-label">Weight (وزن)</label>
                                <input type="text" name="weight[]" class="form-control weight-input" oninput="calculateAmount(this)" />
                            </div>
                        </div>
                        <div class="col-md-1">
                            <div class="form-group">
                                <label class="az-content-label">Rate (ریٹ)</label>
                                <input type="text" name="rate[]" class="form-control rate-input" oninput="calculateAmount(this)" />
                            </div>
                        </div>
                        <div class="col-md-1">
                            <div class="form-group">
                                <label class="az-content-label">Amount (رقم)</label>
                                <input type="text" name="amount[]" class="form-control amount-input" readonly />
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="az-content-label">Remarks (ریمارکس)</label>
                                <textarea class="form-control" name="remarks[]" cols="30" rows="2"></textarea>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <i class="fa fa-trash-alt text-light remove-item bg-danger p-2 rounded-1" style="cursor: pointer; float: right; margin-top: 10px;"></i>
                        </div>
                    </div>
                    `;
            // Append the new row
            document.getElementById('items-wrapper').insertAdjacentHTML('beforeend', newRow);

            // Re-initialize select2 for the new item-select
            $(`#item-row-${itemIndex} .item-select`).select2({
                placeholder: "Select Item",
                allowClear: true
            });

            // Add event listener for remove icon
            document.querySelector(`#item-row-${itemIndex} .remove-item`).addEventListener('click',
                function() {
                    if (document.querySelectorAll('#items-wrapper .row').length > 1) {
                        this.closest('.row').remove();
                        calculateTotals();
                    } else {
                        alert("You cannot delete the last remaining item.");
                    }
                });

            // Increment the item index for the next row
            itemIndex++;
        });
        document.addEventListener('keydown', function(event) {
            const activeElement = document.activeElement;

            // Check for Tab key press
            if (event.key === "Tab") {
                const allRemarksInputs = document.querySelectorAll('textarea[name="remarks[]"]');
                const lastRemarksInput = allRemarksInputs[allRemarksInputs.length - 1];

                // If activeElement is the last remarks input, add a new row
                if (activeElement === lastRemarksInput) {
                    event.preventDefault(); // Prevent default tab behavior

                    // Trigger the click event of the 'Add More' button
                    document.getElementById('add-more').click();

                    // Focus on the newly added row's first input field (e.g., items select)
                    setTimeout(function() {
                        const newItemsInput = document.querySelectorAll('select[name="items[]"]');
                        newItemsInput[newItemsInput.length - 1].focus(); // Focus on the last added input
                    }, 0);
                }
            }

            // Detect Alt + D to delete the selected row
            if (event.altKey && event.key === 'd') {
                event.preventDefault();

                const focusedElement = document.activeElement;
                const focusedRow = focusedElement.closest('.delete_row'); // Find the closest row (div.row)

                // If a row is focused, remove it
                if (focusedRow) {
                    focusedRow.remove(); // Remove the focused row

                    // You can add additional functionality like recalculating totals here
                    // Example: updateTotals();
                } else {
                    showErrorNotification(
                        'Please select the row you want to delete.\nبراہ کرم اس صف کو منتخب کریں جسے آپ حذف کرنا چاہتے ہیں۔'
                    );
                }
            }
        });

        // Function to show error notification
        function showErrorNotification(message) {
            const notification = document.getElementById('errorNotification');
            const errorMessage = document.getElementById('errorMessage');

            errorMessage.innerText = message;
            notification.style.display = 'block';

            setTimeout(() => {
                notification.style.display = 'none';
            }, 5000); // Hide after 5 seconds
        }

        // Optional: Define updateBoriDetails if necessary
        function updateBoriDetails() {
            // Your logic to update details after deleting a row
        }
    </script>
@endpush
