<div>
    <div class="row">
        <div class="col-md-6 d-flex justify-content-between mt-2 mb-2">
            <h4 class="fw-bold "><span class="text-muted fw-light"></span> Products</h4>
        </div>

        <div class="col-md-6 d-flex justify-content-end">
            <div class="col-md-9 mb-4">
                <input type="text" wire:model.live.debounce.300ms="search" value="" name="search" placeholder="Search" class="form-control search">
            </div>
        </div>
    </div>
    <!-- Striped Rows -->
    <div class="card">
        <div class="card-body">
            <div class="d-flex justify-content-end mb-2 mt-0">
                <button 
                    type="button" 
                    class="btn btn-primary" 
                    data-bs-toggle="modal" 
                    data-bs-target="#uploadImageModal"
                    data-bs-backdrop="static" data-bs-keyboard="false"
                    style="margin-right: 10px;"
                    ><strong><i class="bx bx-up-arrow-alt"></i>
                    Upload Image</strong>
                </button>

                <a href="{{route('admin.createProduct')}}" class="btn btn-primary" 
                    ><strong><i class="bx bx-plus"></i>
                    Add Product</strong>
                </a>
                
                <button 
                    type="button" 
                    class="btn btn-primary" 
                    data-bs-toggle="modal" 
                    data-bs-target="#importModal"
                    data-bs-backdrop="static" data-bs-keyboard="false"
                    style="margin-left: 10px;"
                    ><strong><i class="bx bx-up-arrow-alt"></i>
                    Import</strong>
                </button>

                <a href="{{route('admin.reports.products')}}" class="btn btn-primary" style="margin-left: 10px;" 
                    ><strong><i class="bx bx-down-arrow-alt"></i>
                    Download</strong>
                </a>
            </div>
            <div class="table-responsive text-nowrap">
                <table class="table table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Image</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Company</th>
                        <th>Price</th>
                        <th>Type</th>
                        <th>Clicks</th>
                        <th>Views</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody class="table-border-bottom-0">
                    @forelse ($products as $product)
                        <tr  wire:key="product-row-{{ $product->id }}">
                            <td>{{$product->id}}</td>
                            <td><img src="{{$product->productImages[0]->file ?? asset('images/placeholder.png')}}" class="listing-img"/></td>
                            <td>{{$product->name}}</td>
                            <td>{{$product->category->name ?? "-"}}</td>
                            <td>{{$product->company?->name ?? "-"}}</td>
                            <td>{{$product->currency.' '.$product->price}}</td>
                            <td><span class="badge {{$product->type == 'Buying'? "bg-label-secondary": 'bg-label-info'}}">
                                {{$product->type}}</span>
                            </td>
                            <td>{{$product->clicks_count ?? 0}}</td>
                            <td>{{$product->views_count ?? 0}}</td>
                            <td><span class="badge {{$product->status == 1 ? "bg-label-success": 'bg-label-primary'}}">
                                {{$product->status == 1 ? 'Enabled' : 'Disabled'}}</span>
                            </td>
                            <td style="width: 17%;">
                                <a href="javascript:;" wire:click="updateStatus({{$product->id}})" title="Change Status">
                                    @if($product->status == 1)
                                        <i class="bx bx-check btn btn-success btn-xs"></i>
                                    @else
                                        <i class="bx bx-x btn btn-warning btn-xs"></i>
                                    @endif
                                </a>
                                <a href="{{url('admin/products/detail/' . $product->id)}}" title="View Detail">
                                    <i class="bx bx-show btn btn-primary btn-xs"></i>
                                </a>
                                <a href="{{url('admin/products/edit/' . $product->id)}}" title="Edit">
                                    <i class="bx bx-edit btn btn-warning btn-xs"></i>
                                </a>
                                <a href="javascript:void(0);" class="delete" data-id="{{$product->id}}" title="Delete">
                                    <i class="bx bx-trash btn btn-danger btn-xs"></i>
                                </a>
                            </td>
                        </tr>
                    @empty
                    <tr>
                        <td colspan="5" class="text-center">No record found</td>
                    </tr>
                    @endforelse
                </tbody>
                </table>
                <div>
                    {{ $products->links('livewire.pagination') }}
                </div>
            </div>
        </div>
    </div>

    <!-- Import Modal -->
    <div class="modal fade" id="importModal"  tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <form action="{{route('admin.importProducts')}}" method="POST" enctype="multipart/form-data">
                @csrf
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalTitle">Import Products</h5>
                        <button
                            type="button"
                            class="btn-close"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                        ></button>
                    </div>
                    <div class="modal-body">
                        @csrf
                        <div class="row">
                            <div class="col mb-2">
                                <label for="nameLarge" class="form-label">Select Company</label>
                                <select class="form-select form-control @error('company') is-invalid @enderror" name="company">
                                    <option value="">Select</option>
                                    @foreach($companies as $comp)
                                        <option value="{{$comp->id}}">{{$comp->name}}</option>
                                    @endforeach
                                </select>
                                @error('company')
                                    <span class="invalid-feedback"><strong>{{$message}}</strong></span>
                                @enderror
                            </div>
                        </div>
                        
                
                        <div class="row">
                            <div class="col mb-2">
                                <label for="description" class="form-label">File</label>
                                <input type="file" name="file" class="form-control @error('file') is-invalid @enderror" accept="csv, xlsx"/>
                                @error('file')
                                    <span class="invalid-feedback"><strong>{{$message}}</strong></span>
                                @enderror
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">Submit</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Upload Image Modal -->
    <div class="modal fade" id="uploadImageModal"  tabindex="-1" wire:ignore.self>
        <div class="modal-dialog modal-lg" role="document">
            <form wire:submit.prevent="uploadImage" enctype="multipart/form-data">
                @csrf
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalTitle">Upload Product Image</h5>
                        <button
                            type="button"
                            class="btn-close"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                        ></button>
                    </div>
                    <div class="modal-body">
                        @csrf
                        <div class="row">
                            <p class="upload-img-note">Note: Upload the image, copy its URL, and paste it into the corresponding field in the products CSV file.</p>
                        </div>
                        <div class="row">
                            <div class="col mb-2">
                                <label for="description" class="form-label">Image</label>
                                <input type="file" wire:model="image" class="form-control @error('image') is-invalid @enderror" accept="image/*"/>
                                @error('image')
                                    <span class="invalid-feedback"><strong>{{$message}}</strong></span>
                                @enderror
                            </div>
                        </div>

                        <div class="row">
                            @if($imagePath != "")
                                <label for="" class="form-label">Image URL</label>
                            @endif
                            <p>
                                <span id="imagePath">{{$imagePath}}</span>
                                @if($imagePath != "")
                                <span onclick="copyToClipboard()" style="cursor: pointer; margin-left: 10px;" title="Copy">
                                    <i class='bx bxs-copy'></i>
                                  </span>
                                @endif
                                <span id="copyStatus" class="copied"></span>
                            </p>
                            
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">Upload</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

@section('script')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    $(document).ready(function(){
        function confirmDelete(id) {
            Swal.fire({
                title: 'Are you sure?',
                text: "This may effect on product listings",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    @this.call('delete', id)
                }
            });
        }

        $(document).on('click', '.delete', function(e) {
            e.preventDefault();

            // If icon is clicked instead of <a>, this ensures we still get correct data-id
            const id = $(e.target).closest('.delete').data('id');
            confirmDelete(id);
        });
    });

    $(document).ready(function(){
        $("#importModal").modal({
            backdrop: "static",
            keyboard: false,
        });
    });

    function copyToClipboard() {
        const text = $("#imagePath").text();
        console.log(text);
        navigator.clipboard.writeText(text).then(() => {
            document.getElementById("copyStatus").textContent = "Copied!";
        }).catch(err => {
            document.getElementById("copyStatus").textContent = "Failed to copy!";
            console.error("Failed to copy: ", err);
        });
    }

</script>

@if($errors->any())
    <script type="text/javascript">
        $(document).ready(function(){ 
            $("#importModal").modal('show'); 
        });
    </script>
@endif
@endsection