@extends('backend.layouts.master')

@section('title')
    {{ __('Inventory') . ' - ' . $title }}
@endsection

@section('styles')
    <style>
        .bootstrap-switch-large {
            width: 200px;
        }
    </style>
@endsection

@section('navbar-content')
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">{{ __('Inventory') }} </h1>
                </div><!-- /.col -->
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item">
                            <a
                                href="{{ !Auth::guard('web')->user() ? route('buyer.dashboard') : route('home') }}">{{ __('Dashboard') }}</a>
                        </li>
                        @if (helper::roleAccess('inventorySetup.product.index'))
                            <li class="breadcrumb-item">
                                <a href="{{ route('inventorySetup.product.index') }}">{{ __('Product') }}</a>
                            </li>
                        @endif
                        <li class="breadcrumb-item active">
                            <span>{{ __('Product List') }}</span>
                        </li>
                    </ol>
                </div><!-- /.col -->
            </div><!-- /.row -->
        </div><!-- /.container-fluid -->
    </div>
@endsection

@section('admin-content')
    @if ($buyer->status == 'Approved')
        <section class="row">
            <div class="col-md-12">
                <div class="card card-default h-100">
                    <div class="card-header">
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                @foreach ($categories as $index => $category)
                                    <a href="javascript:void(0)"
                                        class="btn btn-sm btn-secondary rounded-pill mb-1 category-btn"
                                        style="{{ $index > 10 ? 'display: none;' : '' }}"
                                        data-category-id="{{ $category->id }}">
                                        <span style="font-size: 0.8rem !important;">{{ $category->name }}</span>
                                    </a>
                                @endforeach
                                <button id="toggle-categories" class="btn btn-sm btn-light rounded-pill mb-1">
                                    <i class="fas fa-chevron-down"></i>


                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            @foreach ($products as $product)
                                <div class="col-md-2">
                                    {{-- <a href="javascript:void(0)" title="{{ $product->name }}" class="product" product-name="{{ $product->name }}" product-thumbnail="{{ asset('uploads/goods/'.$product->thumbnail) }}" product-price="{{ $product->sale_price }}" data-category-id="{{ $product->category_id }}" product-colors="{{ $colors }}" > --}}
                                    <a href="javascript:void(0)" title="{{ $product->name }}" class="product"
                                        product-name="{{ $product->name }}" product-category="{{ $product->genre->name }}"
                                        product-thumbnail="{{ '/uploads/goods/' . $product->thumbnail }}"
                                        product-price="{{ $product->sale_price }}"
                                        data-category-id="{{ $product->genre_id }}">
                                        <div class="card card-outline card-primary">
                                            <img src="{{ $product->thumbnail ? asset('uploads/goods/' . $product->thumbnail) : 'https://via.placeholder.com/150x150' }}"
                                                class="card-img-top" height="120px" alt="..." />
                                            <div class="card-body px-3 py-1">
                                                <h5 class="card-title">
                                                    {{ strlen($product->name) > 20 ? substr($product->name, 0, 20) . '...' : $product->name }}
                                                </h5>
                                            </div>
                                        </div>
                                    </a>
                                </div>
                            @endforeach
                        </div>
                        <div class="pagination justify-content-center">
                            {{ $products->links() }}
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-12 mt-5">
                <form action="{{ route('buyer.order.store') }}" method="POST" enctype="multipart/form-data" />
                @csrf
                <div class="card card-default h-100">
                    <div class="card-header pb-0 mb-0">
                        <!-- Button trigger modal -->
                        <button type="button" class="btn btn-sm btn-secondary mb-2" data-toggle="modal"
                            data-target="#staticBackdrop">
                            {{ __('Custom Order') }}
                        </button>
                        {{-- <span class="badge bg-warning ml-3">{{ $orderCode }}</span> --}}
                    </div>
                    <div class="card-body">
                        <input type="hidden" name="order_code" value="{{ $orderCode }}" />
                        <input type="hidden" name="amount" id="amount" value="0">
                        <div class="form-row">
                            <div class="col-md-4">
                                <label for="styleNo">{{ __('Style No. *') }}</label>
                                <input type="text" name="style_no" class="form-control form-control-sm" id="styleNo"
                                    required />
                            </div>
                            <div class="col-md-4">
                                <label for="poNumber">{{ __('PO Number *') }}</label>
                                <input type="text" name="po_number" class="form-control form-control-sm" id="poNumber"
                                    required />

                            </div>
                            <div class="col-md-4">
                                <label for="poNumber">{{ __('Custom Mail*') }}</label>
                                <button type="button" class="btn btn-sm btn-secondary d-block" data-toggle="modal"
                                    data-target="#customEmailModal">
                                    {{ __('Add Custom Email') }}
                                </button>

                            </div>

                            <!-- Modal -->
                            <div class="modal fade" id="customEmailModal" tabindex="-1" role="dialog"
                                aria-labelledby="customEmailModalLabel" aria-hidden="true">
                                <div class="modal-dialog modal-dialog-centered" role="document">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title" id="customEmailModalLabel">Add Custom Email</h5>
                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                <span aria-hidden="true">&times;</span>
                                            </button>
                                        </div>
                                        <div class="modal-body">
                                            <label for="customEmail">Email Address:</label>
                                            <input type="email" name="cc_email" class="form-control" id="customEmail">
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-success" data-dismiss="modal">Save</button>
                                          </div>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </div>
                    <div class="table-responsive mt-3">
                        <table class="table table-bordered table-striped table-hover">
                            <thead class="table-secondary">
                                <tr>
                                    <th>{{ __('Product') }}</th>
                                    <th width="120px">{{ __('Size') }}</th>
                                    <th width="100px">{{ __('Color') }}</th>
                                    <th width="100px">{{ __('Unit') }}</th>
                                    <th width="150px">{{ __('Quantity') }}</th>
                                    <th width="120px">{{ __('Price') }}</th>
                                    <th width="120px">{{ __('Subtotal') }}</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                            <tfoot class="">
                                <tr>
                                    <td class="text-right" colspan="4">
                                        <strong>{{ __('Total =') }}</strong>
                                    </td>
                                    <td class="text-center">
                                        <span id="qty"></span>
                                    </td>
                                    <td class="text-right" colspan="2"></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <label for="note">{{ __('Order Note :') }}</label>
                            <textarea name="note" class="form-control textarea form-control-sm" id="note" cols="30"
                                rows="6"></textarea>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label for="exampleInputFile">{{ __('Attachments :') }}</label>
                            <div class="input-group input-group-sm">
                                <div class="custom-file">
                                    {{-- <input type="file" name="attachments[]" class="custom-file-input" id="attachments" accept=".jpg, .jpeg, .png, .gif, .webp" multiple /> --}}
                                    <input type="file" name="attachments[]" class="custom-file-input"
                                        id="attachments"
                                        accept=".jpg, .jpeg, .png, .gif, .webp, .pdf, .doc, .docx, .rtf, .xls, .xlsx, .csv, .txt"
                                        multiple />
                                    <label class="custom-file-label" for="attachments">{{ __('Choose file') }}</label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <div id="selected-files-container" class="row"></div>
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">
                        <span>{{ __('Place Your Order') }}</span>
                    </button>
                </div>
            </div>
            </form>
            </div>
        </section>

        <!-- Modal -->
        <section class="modal fade" id="staticBackdrop" data-backdrop="static" data-keyboard="false" tabindex="-1"
            aria-labelledby="staticBackdropLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header py-1">
                        <h5 class="modal-title" id="staticBackdropLabel">{{ __('Custom Order') }}</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div id="customOrder" class="modal-body">
                        <div class="form-row">
                            <div class="col-md-12 mb-3">
                                <label for="goodsName">{{ __('Product Name') }}</label>
                                <input type="text" name="product_name" class="form-control form-control-sm"
                                    id="goodsName" placeholder="Enter Product Name" value="TTL/Custom-" />
                            </div>
                            <div class="col-md-5 mb-3">
                                <label for="goodsCategory">{{ __('Product Category') }}</label>
                                <input type="text" name="product_category" class="form-control form-control-sm"
                                    id="goodsCategory" placeholder="Enter Product Category" />
                            </div>
                            <div class="col-md-3 mb-3">
                                <label for="goodsSize">{{ __('Product Size') }}</label>
                                <input type="text" name="product_size" class="form-control form-control-sm"
                                    id="goodsSize" placeholder="Enter Product Size" value="2mm" />
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="goodsQty">{{ __('Product Quantity') }}</label>
                                <div class="input-group input-group-sm">
                                    <button type="button" class="btn btn-sm btn-secondary rounded-0" id="increase">
                                        <i class="fas fa-plus"></i>
                                    </button>
                                    <input type="text" name="product_qty"
                                        class="form-control quantity text-center rounded-0" id="goodsQty"
                                        value="1" />
                                    <button type="button" class="btn btn-sm btn-secondary rounded-0" id="decrease">
                                        <i class="fas fa-minus"></i>
                                    </button>
                                </div>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label for="goodsImg">{{ __('Product Thumbnail') }}</label>
                                <div class="input-group input-group-sm">
                                        <input type="file"  name="product_thumbnail" class="form-control"
                                            id="goodsImg" upload-url="{{ route('buyer.upload.thumbnail') }}"
                                            accept=".jpg, .jpeg, .png, .gif, .webp" />
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer py-1">
                        <button type="button" class="btn btn-primary">{{ __('Submit') }}</button>
                    </div>
                </div>
            </div>
        </section>
    @endif
@endsection

@section('scripts')
    <script>

        
        $(document).ready(function() {

            $('body').on('keydown', 'input, select', function(e) {
            if (e.key === "Enter") {
                    var self = $(this), form = self.parents('form:eq(0)'), focusable, next;
                    focusable = form.find('input,a,select,button,textarea').filter(':visible');
                    next = focusable.eq(focusable.index(this)+1);
                    if (next.length) {
                        next.focus();
                    } else {
                        form.submit();
                    }
                    return false;
                }
            });

            var goodsQty = $('#goodsQty').val();

            $(document).on('click', '#increase', function() {
                var goodsQty = parseInt($('#goodsQty').val());
                var increase = goodsQty + 1;
                $('#goodsQty').val(increase);
            });

            $(document).on('click', '#decrease', function() {
                var goodsQty = parseInt($('#goodsQty').val());
                if (goodsQty > 1) {
                    var decrease = goodsQty - 1;
                    $('#goodsQty').val(decrease);
                }
            });

            $('#staticBackdrop .btn-primary').click(function() {
                var productName = $('#goodsName').val();
                var category = $('#goodsCategory').val();
                var size = $('#goodsSize').val();
                var qty = $('#goodsQty').val();
                var thumbnailInput = document.getElementById('goodsImg');
                var thumbnailFile = thumbnailInput.files[0];
                if (!thumbnailFile) {
                    alert("Please select a file.");
                    return;
                }
                var formData = new FormData();
                formData.append('product_thumbnail', thumbnailFile);
                console.log(formData);
                var uploadURL = $('#goodsImg').attr('upload-url');
                $.ajax({
                    url: uploadURL,
                    method: 'POST',
                    data: formData,
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    contentType: false,
                    processData: false,
                    success: function(response) {
                        var thumbnail = response.thumbnail_url;
                        addProductRow(productName, category, thumbnail, size, qty, 0, 0);
                    },
                    error: function(xhr, status, error) {
                        console.error(error);
                    }
                });
                $('#staticBackdrop').modal('hide');
                $('#goodsName').val('');
                thumbnailInput.value = '';
                $('#goodsSize').val('');
                $('#goodsQty').val('1');
            });

            $('.product').click(function() {
                var productName = $(this).attr('product-name');
                // var existingRow = $('tbody').find('tr[data-product-name="' + productName + '"]'); 
                // if (existingRow.length > 0) {
                //   var input = existingRow.find('.quantity');
                //   var currentValue = parseInt(input.val());
                //   input.val(currentValue + 1);
                //   updateSubtotal(existingRow);
                // } else {
                var category = $(this).attr('product-category');
                var thumbnail = $(this).attr('product-thumbnail');
                var size = "2mm";
                var qty = 1;
                var price = parseFloat($(this).attr('product-price'));
                var subtotal = parseFloat($(this).attr('product-price')) * qty;
                addProductRow(productName, category, thumbnail, size, qty, price, subtotal);
                // }
            });

            $(document).on('click', '.increment', function() {
                var row = $(this).closest('tr');
                var input = row.find('.quantity');
                var currentValue = parseInt(input.val());
                input.val(currentValue + 1);
                updateSubtotal(row);
                updateQuantity();
            });

            $('.textarea').summernote();

            $(document).on('input', '.quantity', function() {
                var row = $(this).closest('tr');
                var input = row.find('.quantity');
                var currentValue = parseInt(input.val());
                if (currentValue > 1) {
                    // input.val(currentValue - 1);
                    updateSubtotal(row);
                    updateQuantity();
                }
            });

            $(document).on('click', '.decrement', function() {
                var row = $(this).closest('tr');
                var input = row.find('.quantity');
                var currentValue = parseInt(input.val());
                if (currentValue > 1) {
                    input.val(currentValue - 1);
                    updateSubtotal(row);
                    updateQuantity();
                }
            });


            $(document).on('click', '.delete-product', function() {
                if (confirm('Are you sure you want to delete this product?')) {
                    deleteProductRow($(this).closest('tr'));
                    updateQuantity();
                }
            });

            function addProductRow(productName, category, thumbnail, size, qty, price, subtotal) {
                var newRow = '<tr data-product-name="' + productName + '">' +
                    '<td>' +
                    '<div class="row">' +
                    '<div class="col-2">' +
                    '<a href="' + thumbnail + '" class="">' +
                    '<img src="' + thumbnail + '" class="thumbnail" width="60px" height="60px" alt="" />' +
                    '</a>' +
                    '<input type="hidden" name="thumbnail[]" value="' + thumbnail + '">' +
                    '</div>' +
                    '<div class="col-10">' +
                    '<strong class="ml-3">' + productName + '</strong> <br/>' +
                    '<span class="ml-3">' + category + '</span>' +
                    '<br>' +
                    '<a href="javascript:void(0)" class="text-danger text-sm delete-product ml-3" >' +
                    '<i class="fas fa-trash-alt"></i>' +
                    '<span class="ml-1">Remove</span>' +
                    '</a>' +
                    '</div>' +
                    '</div>' +
                    '<input type="hidden" name="goods_name[]" value="' + productName + '">' +
                    '<input type="hidden" name="category[]" value="' + category + '">' +
                    '</td>' +
                    '<td>' +
                    '<input type="text" name="size[]" class="form-control form-control-sm mt-3" placeholder="Size" value="' +
                    size + '">' +
                    '</td>' +
                    '<td>' +
                    '<input type="text" name="color[]" class="form-control form-control-sm mt-3" />' +
                    '</td>' +
                    '<td>' +
                    '<select class="form-control form-control-sm select2 mt-3" name="unit[]" >' +
                    '@foreach ($units as $unit) <option value="{{ $unit->id }}">{{ $unit->name }}</option> @endforeach' +
                    '</select>' +
                    '</td>' +
                    '<td>' +
                    '<div class="input-group input-group-sm mt-3">' +
                    '<button type="button" class="btn btn-sm btn-secondary rounded-0 increment">' +
                    '<i class="fas fa-plus"></i>' +
                    '</button>' +
                    '<input type="text" name="quantity[]" class="form-control text-center  rounded-0 quantity" value="' +
                    qty + '"  />' +
                    '<button type="button" class="btn btn-sm btn-secondary rounded-0 decrement">' +
                    '<i class="fas fa-minus"></i>' +
                    '</button>' +
                    '</div>' +
                    '</td>' +
                    '<td class="text-right price pt-4"><input type="text" class="form-control text-center rounded-0 price" value="' +
                    price.toFixed(2) + '" /></td>' +
                    '<td class="text-right subtotal pt-4">' + subtotal.toFixed(2) + '/- </td>' +
                    '<input type="hidden" name="rate[]" value="' + price + '">' +
                    '<input type="hidden" name="price[]" value="' + subtotal + '">' +
                    '</tr>';
                $('tbody').append(newRow);
                updateTotals();
                updateTotalInput();
                updateQuantity();
                alertMessage.success("Product Added")
            }

            function deleteProductRow(row) {
                row.remove();
                updateTotals();
                updateTotalInput();
                updateQuantity();
            }

            $(document).on('input', '.price input', function() {
                var row = $(this).closest('tr');
                updateSubtotal(row);
            });

            // Existing functions...

            function updateSubtotal(row) {
                var quantity = parseInt(row.find('.quantity').val());
                var price = parseFloat(row.find('.price input').val()); // Retrieve price from input field
                var subtotal = quantity * price;
                row.find('.subtotal').text(subtotal.toFixed(2) + '/-');
                row.find('[name="price[]"]').val(subtotal.toFixed(2));
                updateTotals();
                updateTotalInput();
                // updateQuantity();
            }

            function updateTotals() {
                var total = 0;
                $('tbody').find('.subtotal').each(function() {
                    var subtotalText = $(this).text();
                    var subtotal = parseFloat(subtotalText.substring(0, subtotalText.length - 2));
                    total += subtotal;
                });
                $('tfoot').find('tr:first td:last').text(total.toFixed(2) + '/-');
            }

            function updateQuantity() {
                var qty = 0;
                $('tbody').find('.quantity').each(function() {
                    var qtyValue = parseInt($(this).val());
                    qty += qtyValue;
                });
                $('#qty').text(qty);
            }

            function updateTotalInput() {
                var total = 0;
                $('.subtotal').each(function() {
                    var subtotalText = $(this).text();
                    var subtotal = parseFloat(subtotalText.substring(0, subtotalText.length - 3));
                    total += subtotal;
                });
                $('#amount').val(total.toFixed(2));
            }

            $('.category-btn').slice(10).hide();

            $('#toggle-categories').click(function() {
                $('.category-btn').slice(10).toggle();
                $(this).find('i').toggleClass('fa-chevron-down fa-chevron-up');
            });

            $('.category-btn').click(function() {
                var categoryId = $(this).data('category-id');
                $('.col-md-2').each(function() {
                    var product = $(this).find('.product');
                    if (product.data('category-id') == categoryId) {
                        $(this).css('display', 'block');
                    } else {
                        $(this).css('display', 'none');
                    }
                });
            });
            updateTotals();
            updateTotalInput();
            updateQuantity();
        });
    </script>

    <script>
        $(document).ready(function() {
            $('#attachments').change(function() {
                var files = $(this)[0].files;
                var container = $('#selected-files-container');
                container.empty();
                for (var i = 0; i < files.length; i++) {
                    var file = files[i];
                    var fileName = file.name;
                    var fileSize = (file.size / 1024).toFixed(2) + ' KB';
                    var card = '<div class="col-md-2">';
                    card += '<div class="card">';
                    card += '<div class="card-body p-2">';
                    card += '<h5 class="card-title">' + fileName + '</h5>';
                    card += '<p class="card-text">(' + fileSize + ')</p>';
                    // card += '<button type="button" class="btn btn-danger btn-sm remove-file">Remove</button>';
                    card += '</div></div></div>';
                    container.append(card);
                }
            });

            $(document).on('click', '.remove-file', function() {
                var confirmation = confirm('Are you sure you want to remove this file?');
                if (confirmation) {
                    var card = $(this).closest('.col-md-2');
                    var index = card.index();
                    var files = $('#attachments')[0].files;
                    var newFiles = Array.from(files);
                    newFiles.splice(index, 1);
                    $('#attachments').val('');
                    $('#attachments')[0].files = newFiles;
                    card.remove();
                }
            });
        });
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const imgThumbnails = document.querySelectorAll('.img-thumbnail');
            imgThumbnails.forEach(function(imgThumbnail) {
                lightGallery(imgThumbnail, {
                    animateThumb: false,
                    zoomFromOrigin: false,
                    allowMediaOverlap: true,
                    toggleThumb: true,
                });
            });
        });
    </script>
@endsection
