@extends('admin.layout.template')
@section('title', 'Products')
@section('content')

<div class="page-content">
    <div class="container-xxl">

        <!-- Add Product Card -->
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title d-flex align-items-center gap-1">
                            <iconify-icon icon="solar:box-bold-duotone" class="text-primary fs-20"></iconify-icon>
                            Add Product
                        </h4>
                    </div>
                    <div class="card-body">
                        <form id="addProductForm" enctype="multipart/form-data">
                            @csrf
                            <div class="row g-3">
                                <div class="col-lg-4">
                                    <label class="form-label">Category</label>
                                    <select name="category_id" id="categorySelect" class="form-control" required>
                                        <option value="">Select Category</option>
                                        @foreach(App\Models\Category::all() as $cat)
                                            <option value="{{ $cat->id }}">{{ $cat->name }}</option>
                                        @endforeach
                                    </select>
                                </div>

                                <div class="col-lg-4">
                                    <label class="form-label">Subcategory</label>
                                    <select name="sub_category_id" id="subcategorySelect" class="form-control">
                                        <option value="">Select Subcategory</option>
                                    </select>
                                </div>

                                <div class="col-lg-4">
                                    <label class="form-label">Product Name</label>
                                    <input type="text" name="name" class="form-control" placeholder="Enter product name" required>
                                </div>

                                <div class="col-lg-4">
                                    <label class="form-label">Price</label>
                                    <input type="number" name="price" class="form-control" placeholder="Enter price" required>
                                </div>

                                <div class="col-lg-4">
                                    <label class="form-label">Discount Price</label>
                                    <input type="number" name="discount_price" class="form-control" placeholder="Enter discount price">
                                </div>

                                <div class="col-lg-4">
                                    <label class="form-label">Stock</label>
                                    <input type="number" name="stock" class="form-control" placeholder="Enter stock" value="1">
                                </div>

                                <div class="col-lg-12">
                                    <label class="form-label">Description</label>
                                    <textarea name="description" class="form-control" rows="3" placeholder="Enter product description"></textarea>
                                </div>

                                <div class="col-lg-6">
                                    <label class="form-label">Images (Multiple)</label>
                                    <input type="file" name="images[]" class="form-control" multiple required>
                                </div>

                                <div class="col-lg-6">
                                    <label class="form-label">Status</label>
                                    <select name="status" class="form-control">
                                        <option value="1" selected>Active</option>
                                        <option value="0">Inactive</option>
                                    </select>
                                </div>
                            </div>

                            <div class="text-end mt-3">
                                <button type="submit" class="btn btn-success">Save Product</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
<!-- Edit Product Modal -->
<div class="modal fade" id="editProductModal" tabindex="-1" aria-labelledby="editProductModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title" id="editProductModalLabel">Edit Product</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="editProductForm" enctype="multipart/form-data">
          @csrf
          <input type="hidden" name="id" id="edit_id">

          <div class="row g-3">
            <div class="col-lg-4">
              <label class="form-label">Category</label>
              <select name="category_id" id="edit_category" class="form-control" required>
                <option value="">Select Category</option>
                @foreach(App\Models\Category::all() as $cat)
                  <option value="{{ $cat->id }}">{{ $cat->name }}</option>
                @endforeach
              </select>
            </div>

            <div class="col-lg-4">
              <label class="form-label">Subcategory</label>
              <select name="sub_category_id" id="edit_subcategory" class="form-control">
                <option value="">Select Subcategory</option>
              </select>
            </div>

            <div class="col-lg-4">
              <label class="form-label">Product Name</label>
              <input type="text" name="name" id="edit_name" class="form-control" required>
            </div>

            <div class="col-lg-4">
              <label class="form-label">Price</label>
              <input type="number" name="price" id="edit_price" class="form-control" required>
            </div>

            <div class="col-lg-4">
              <label class="form-label">Discount Price</label>
              <input type="number" name="discount_price" id="edit_discount_price" class="form-control">
            </div>

            <div class="col-lg-4">
              <label class="form-label">Stock</label>
              <input type="number" name="stock" id="edit_stock" class="form-control">
            </div>

            <div class="col-lg-12">
              <label class="form-label">Description</label>
              <textarea name="description" id="edit_description" class="form-control" rows="3"></textarea>
            </div>

            <div class="col-lg-6">
              <label class="form-label">Images (Optional)</label>
              <input type="file" name="images[]" class="form-control" multiple>
              <div id="existingImages" class="mt-2 d-flex flex-wrap gap-2"></div>
            </div>

            <div class="col-lg-6">
              <label class="form-label">Status</label>
              <select name="status" id="edit_status" class="form-control">
                <option value="1">Active</option>
                <option value="0">Inactive</option>
              </select>
            </div>
          </div>

          <div class="text-end mt-3">
            <button type="submit" class="btn btn-primary">Update Product</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>
        <!-- Product Table -->
        <div class="row mt-3">
            <div class="col-xl-12">
                <div class="card">
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table align-middle mb-0 table-hover table-centered">
                                <thead class="bg-light-subtle">
                                    <tr>
                                        <th>SL.NO</th>
                                        <th>Product</th>
                                        <th>Category</th>
                                        <th>Subcategory</th>
                                        <th>Images</th>
                                        <th>Price</th>
                                        <th>Stock</th>
                                        <th>Status</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>



<script>
$(document).ready(function() {

    // Load subcategories dynamically
    $('#categorySelect').on('change', function() {
        let catId = $(this).val();
        $('#subcategorySelect').html('<option value="">Loading...</option>');
        $.get("{{ url('get-subcategories') }}/" + catId, function(data) {
            let html = '<option value="">Select Subcategory</option>';
            $.each(data, function(i, subcat) {
                html += `<option value="${subcat.id}">${subcat.name}</option>`;
            });
            $('#subcategorySelect').html(html);
        });
    });

    // Initialize DataTable
  var table = $('.table').DataTable({
    processing: true,
    serverSide: true,
    ajax: "{{ route('get-products') }}",
    order: [[1, 'asc']], // order by name instead of DT_RowIndex
    columns: [
        { data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false },
        { data: 'name', name: 'name' },
        { data: 'category', name: 'category' },
        { data: 'subcategory', name: 'subcategory' },
        { data: 'images', name: 'images', orderable: false, searchable: false },
        { data: 'price', name: 'price' },
        { data: 'stock', name: 'stock' },
        { data: 'status', name: 'status', orderable: false },
        { data: 'action', name: 'action', orderable: false, searchable: false }
    ]
});


    // Add Product
    $('#addProductForm').submit(function(e) {
        e.preventDefault();
        var formData = new FormData(this);
        $.ajax({
            url: "{{ route('add-product') }}",
            type: "POST",
            data: formData,
            contentType: false,
            processData: false,
            success: function(response){
                Swal.fire({ icon: 'success', title: 'Added!', text: response.success, timer: 1500, showConfirmButton: false });
                $('#addProductForm')[0].reset();
                table.ajax.reload();
            },
            error: function(xhr){
                let errors = xhr.responseJSON.errors;
                let errMsg = '';
                $.each(errors, function(k,v){ errMsg+=v+'\n'; });
                Swal.fire({ icon: 'error', title: 'Error', text: errMsg });
            }
        });
    });

    // Delete Product
    $(document).on('click', '.deleteproduct', function() {
        var id = $(this).data('id');
        Swal.fire({
            title: 'Delete Product?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, delete',
            cancelButtonText: 'Cancel'
        }).then(result => {
            if(result.isConfirmed){
                $.ajax({
                    url: "{{ url('delete-product') }}/"+id,
                    type: 'DELETE',
                    data: { _token: '{{ csrf_token() }}' },
                    success: function(res){
                        Swal.fire({ icon: 'success', title: 'Deleted!', text: res.success, timer: 1500, showConfirmButton: false });
                        table.ajax.reload();
                    }
                });
            }
        });
    });

});

// Open Edit Modal
$(document).on('click', '.editproduct', function () {
    var id = $(this).data('id');
    $.get("{{ url('get-product') }}/" + id, function (data) {
        // Fill modal fields
        $('#edit_id').val(data.id);
        $('#edit_name').val(data.name);
        $('#edit_price').val(data.price);
        $('#edit_discount_price').val(data.discount_price);
        $('#edit_stock').val(data.stock);
        $('#edit_description').val(data.description);
        $('#edit_status').val(data.status);
        $('#edit_category').val(data.category_id).trigger('change');

        // Load subcategories
        $.get("{{ url('get-subcategories') }}/" + data.category_id, function (subs) {
            let html = '<option value="">Select Subcategory</option>';
            $.each(subs, function (i, sub) {
                html += `<option value="${sub.id}" ${sub.id == data.sub_category_id ? 'selected' : ''}>${sub.name}</option>`;
            });
            $('#edit_subcategory').html(html);
        });

        // Show existing images
        let imgsHtml = '';
        $.each(data.images, function (i, img) {
            imgsHtml += `<img src="{{ asset('uploads/products') }}/${img.image}" class="img-thumbnail" width="60">`;
        });
        $('#existingImages').html(imgsHtml);

        $('#editProductModal').modal('show');
    });
});


// Submit Edit Form
$('#editProductForm').submit(function (e) {
    e.preventDefault();
    let id = $('#edit_id').val();
    let formData = new FormData(this);

    $.ajax({
        url: "{{ url('update-product') }}/" + id,
        type: "POST",
        data: formData,
        contentType: false,
        processData: false,
        success: function (res) {
            Swal.fire({ icon: 'success', title: 'Updated!', text: res.success, timer: 1500, showConfirmButton: false });
            $('#editProductModal').modal('hide');
            $('#editProductForm')[0].reset();
            $('.table').DataTable().ajax.reload();
        },
        error: function (xhr) {
            let errMsg = '';
            $.each(xhr.responseJSON.errors, function (k, v) { errMsg += v + '\n'; });
            Swal.fire({ icon: 'error', title: 'Error', text: errMsg });
        }
    });
});

</script>

@endsection
