@extends('layouts.master')

@section('content')
    <div class="az-content-breadcrumb">
        <span>Products</span>
    </div>
    <h2 class="az-content-title" style="display: inline">
        Products List
        @if (isset($brand_id))
            <span>
                @can('Products add')
                    <a href="{{ route('products.create', ['id' => Crypt::encrypt($brand_id)]) }}" class="btn btn-az-primary"
                        style="float: right"><i class="fa-solid fa-plus"></i> Add New Product</a>
                @endcan
                @can('Products list')
                    <a href="{{ route('brands.list', ['id' => Crypt::encrypt($brand_id)]) }}" class="btn border" style="float: right"><i
                            class="fa-solid fa-bars-staggered"></i>
                        Back to Brands
                    </a>
                @endcan
            </span>
        @endif
    </h2>
    <div class="row">
        <div class="col-md-12 col-lg-12 col-xl-12">
            <div class="card card-body pd-20">
                @php
                    if(isset($brand_id)) {
                        $grnID = $brand_id;
                    } else {
                        $grnID = '';
                    }
                @endphp
                <div>
                    <table id="example2{{ $grnID }}" class="table table-responsive">
                        <thead>
                            <tr>
                                <th class="wd-5-f">S.No</th>
                                <th class="wd-10p">Brand Name</th>
                                <th class="wd-10p">Product Name</th>
                                <th class="wd-10p">Category</th>
                                <th class="wd-10p">Sale Price</th>
                                <th class="wd-10p">In Stock</th>
                                <th class="wd-10p">Threshold</th>
                                <th class="wd-10p">Measurement Unit</th>
                                <th class="wd-10p">Qty Per Unit</th>
                                <th class="wd-10p">Purchase Price</th>
                                <th class="wd-10p">Retail Price</th>
                                <th class="wd-10p">Images</th>
                                {{-- <th class="wd-10p none">Status</th> --}}
                                @if (isset($brand_id))
                                    <th class="none">Action</th>
                                @endif
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($products as $key => $product)
                                @php
                                    $color = '';
                                    if ($product->products_status == 0) {
                                        $color = '#f5c5c5';
                                    }
                                    $units = App\Measurement_unit::where(
                                        'id_measurement_unit', $product->measurement_unit_id)->first();
                                @endphp
                                <tr style="background-color: {{ $color }};">
                                    <td>{{ $key + 1 }}</td>
                                    <td>{{ $product->brand->brands_name }}</td>
                                    <td>{{ $product->products_name }}</td>
                                    <td>{{ $product->category ? $product->category->products_category_name : 'No Category' }}
                                    </td>
                                    <td>{{ $product->products_sale_price }}</td>
                                    <td>{{ $product->in_stock != null ? $product->in_stock : '0' }}</td>
                                    <td>{{ $product->products_threshold }}</td>
                                    <td>{{ $units ? $units->measurement_unit_name : 'null' }}</td>
                                    <td>{{ $product->products_qt_per_unit }}</td>
                                    <td>{{ $product->products_purchase_price }}</td>
                                    <td>{{ $product->products_retail_price }}</td>
                                    <td>
                                        <a class="btn btn-rounded view-images-btn" href="#" title="Peoduct Images"
                                            data-product-id="{{ $product->id_products }}">
                                            <i class="text-success fa-regular fa-images"></i>
                                        </a>
                                    </td>
                                    {{-- <td>
                                        @if ($product->products_status == 1)
                                            <button class="btn btn-rounded btn-success" style="color:#fff;">
                                                <strong>Active</strong> <span class="badge badge-primary"></span>
                                            </button>
                                        @else
                                            <button class="btn btn-rounded btn-danger" style="color:#fff;">
                                                <i class="fa-solid fa-ban"></i> <strong>Deactivated</strong> <span
                                                    class="badge badge-primary"></span>
                                            </button>
                                        @endif
                                    </td> --}}
                                    <td>
                                        @if (isset($brand_id))
                                            @can('Stocks list')
                                                @if ($product->products_status == 1)
                                                    <a class="btn rounded shadow-base" title="Product Stock"
                                                        href="{{ route('products.stock.list', ['brand_id' => Crypt::encrypt($product->Products_id), 'product_id' => Crypt::encrypt($product->id_products)]) }}">
                                                        <i class="text-success fa-solid fa-boxes-stacked"></i> <span
                                                            class="text-success">Stock</span>
                                                    </a>
                                                @endif
                                            @endcan
                                            @can('Products edit')
                                                <a class="btn rounded shadow-base" title="Edit Product"
                                                    href="{{ route('products.edit', Crypt::encrypt($product->id_products)) }}">
                                                    <i class="text-primary fa-regular fa-pen-to-square"></i> <span
                                                        class="text-primary">Edit</span>
                                                </a>
                                            @endcan
                                            @can('Products delete')
                                                <a class="btn rounded shadow-base" title="Delete Product"
                                                    href="{{ route('products.destroy', ['id' => Crypt::encrypt($product->id_products)]) }}">
                                                    <i class="text-danger fa-solid fa-trash-can"></i> <span
                                                        class="text-danger">Remove</span>
                                                </a>
                                            @endcan
                                        @endif
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                        <tfoot>
                            <tr>
                                <th class="wd-5-f">S.No</th>
                                <th class="wd-10p">Brand Name</th>
                                <th class="wd-10p">Product Name</th>
                                <th class="wd-10p">Category</th>
                                <th class="wd-10p">Sale Price</th>
                                <th class="wd-10p">In Stock</th>
                                <th class="wd-10p">Threshold</th>
                                <th class="wd-10p">Measurement Unit</th>
                                <th class="wd-10p">Qty Per Unit</th>
                                <th class="wd-10p">Purchase Price</th>
                                <th class="wd-10p">Retail Price</th>
                                <th class="wd-10p">Images</th>
                                {{-- <th class="wd-10p none">Status</th> --}}
                                @if (isset($brand_id))
                                    <th class="none">Action</th>
                                @endif
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
            <!-- card -->
        </div>
        <!-- col -->
    </div>
@endsection

<!-- image View Modal -->
<div class="modal fade" id="imagesModal" tabindex="-1" role="dialog" aria-labelledby="imagesModalLabel"
    aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="imagesModalLabel">Product Images</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true" class="text-dark" onclick="closeModal();">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="productImages"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" id="deleteAllImagesBtn">Delete All Images</button>
                <button type="button" class="btn btn-secondary text-light" data-dismiss="modal"
                    onclick="closeModal();">Close</button>
            </div>
        </div>
    </div>
</div>

@push('scripts')
    <script type="text/javascript">
        $(function() {
        oTable = $('#example2'+{{ $grnID }}).DataTable({
            dom: 'Bfrtip',
            buttons: [{
                    extend: 'csv',
                    text: 'CSV',
                    title: 'Products List',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: 'th:not(:last-child)'
                    }
                },
                {
                    extend: 'excel',
                    text: 'Excel',
                    title: 'Products List',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: 'th:not(:last-child)'
                    }
                },
                {
                    extend: 'pdf',
                    text: 'PDF',
                    title: 'Products List',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: 'th:not(:last-child)'
                    }
                },
                {
                    extend: 'print',
                    text: 'Print',
                    title: 'Products List',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: 'th:not(:last-child)'
                    }
                }
            ],
            responsive: !0
        });
    });
        // $(document).ready(function() {
        //     $('#example2 tfoot th').each(function() {
        //         var title = $(this).text();
        //         $(this).html('<input type="text" class="form-control" placeholder="' + title + '" />');
        //     });
        //     $('#example2').DataTable({
        //         "ordering": true,
        //         "dom": 'Blfrtip',
        //         "buttons": [
        //             'excel', 'pdf', 'print'
        //         ],
        //         responsive: !0,
        //         columnDefs: [{
        //             className: 'control',
        //             orderable: false
        //         }],
        //         initComplete: function() {
        //             // Apply the search
        //             this.api()
        //                 .columns()
        //                 .every(function() {
        //                     var that = this;
        //                     $('input', this.footer()).on('keyup change clear', function() {
        //                         if (that.search() !== this.value) {
        //                             that.search(this.value).draw();
        //                         }
        //                     });
        //                 });
        //         }
        //     });
        // });

        // for image view
        $(document).ready(function() {
            function loadProductImages(productId) {
                $.ajax({
                    url: "{{ route('products.images.view', ['id' => ':id']) }}".replace(':id', productId),
                    type: 'GET',
                    success: function(response) {
                        $('#productImages').html(response);
                        $('#productImages').data('product-id',
                            productId); // Store product ID in modal for later use
                    },
                    error: function(xhr, status, error) {
                        console.error(xhr.responseText);
                    }
                });
            }

            $('.view-images-btn').click(function(e) {
                e.preventDefault();
                var productId = $(this).data('product-id');
                $('#imagesModal').modal('show');
                loadProductImages(productId);
            });

            // AJAX request to delete a single image
            $(document).on('click', '.delete-image-btn', function(e) {
                e.preventDefault();
                var imageId = $(this).data('image-id');
                var productId = $('#productImages').data('product-id');

                // Confirmation dialog
                if (confirm('Are you sure you want to delete this image?')) {
                    $.ajax({
                        url: "{{ route('products.images.delete', ['id' => ':id']) }}".replace(
                            ':id', imageId),
                        type: 'GET',
                        success: function(response) {
                            console.log(response);
                            loadProductImages(productId); // Reload images after deletion
                        },
                        error: function(xhr, status, error) {
                            console.error(xhr.responseText);
                        }
                    });
                }
            });

            // AJAX request to delete all images
            $('#deleteAllImagesBtn').click(function(e) {
                e.preventDefault();
                var productId = $('#productImages').data('product-id');

                // Confirmation dialog
                if (confirm('Are you sure you want to delete all images?')) {
                    $.ajax({
                        url: "{{ route('products.images.delete.all', ['id' => ':id']) }}".replace(
                            ':id', productId),
                        type: 'GET',
                        success: function(response) {
                            console.log(response);
                            loadProductImages(productId); // Reload images after deletion
                        },
                        error: function(xhr, status, error) {
                            console.error(xhr.responseText);
                        }
                    });
                }
            });

        });

        function closeModal() {
            $('#imagesModal').modal('hide');
        }
    </script>
@endpush
