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

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

        <!-- Add Banner -->
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title">Add Banner</h4>
                    </div>
                    <div class="card-body">
                        <form id="addBannerForm" enctype="multipart/form-data">
                            @csrf
                            <div class="row">
                                <div class="col-lg-3 mb-3">
                                    <label class="form-label">Title</label>
                                    <input type="text" name="title" class="form-control" placeholder="Enter banner title">
                                </div>
                                <div class="col-lg-3">
                                    <label class="form-label">Category</label>
                                    <select name="category_id" id="category_id" class="form-control">
                                        <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-3">
                                    <label class="form-label">Product</label>
                                    <select name="product_id" id="product_id" class="form-control">
                                        <option value="">-- Select Product --</option>
                                    </select>
                                </div>
                                <div class="col-lg-3">
                                    <label class="form-label">Image</label>
                                    <input type="file" name="image" class="form-control" required>
                                </div>
                                <div class="col-lg-4">
                                    <label>Set as seasonal Banner</label>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input toggleStatus" value="1" name="seasonal_banner" type="checkbox" id="seasonal">
                                    </div>
                                </div>
                                <div class="col-lg-4">
                                    <label>Start Date</label>
                                    <input type="date" name="start_date" class="form-control" id="start_date" disabled>
                                </div>
                                <div class="col-lg-4">
                                    <label>End Date</label>
                                    <input type="date" name="end_date" class="form-control" id="end_date" disabled>
                                </div>
                            </div>
                            <div class="text-end mt-3">
                                <button type="submit" class="btn btn-success">Save</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Banner Table -->
        <div class="row mt-4">
            <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>Title</th>
                                        <th>Category</th>
                                        <th>Product</th>
                                        <th>Image</th>
                                        <th>Status</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>


<div class="modal fade" id="editBannerModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <form id="editBannerForm">
            @csrf
            <input type="hidden" id="edit_id" name="id">

            <input type="hidden" name="seasonal_banner" value="0"> <!-- default -->

            <div class="modal-content">
                <div class="modal-header">
                    <h5>Edit Banner</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body row">
                    <div class="col-6 mb-3">
                        <label>Title</label>
                        <input type="text" id="edit_title" name="title" class="form-control">
                    </div>

                    <div class="col-6 mb-3">
                        <label>Set Seasonal Banner</label>
                        <div class="form-check form-switch">
                            <input type="checkbox" id="edit_seasonal" name="seasonal_banner" value="1" class="form-check-input">
                        </div>
                    </div>

                    <div class="col-6 mb-3">
                        <label>Start Date</label>
                        <input type="date" id="edit_start_date" name="start_date" class="form-control" disabled>
                    </div>

                    <div class="col-6 mb-3">
                        <label>End Date</label>
                        <input type="date" id="edit_end_date" name="end_date" class="form-control" disabled>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="submit" class="btn btn-success">Update</button>
                </div>
            </div>
        </form>
    </div>
</div>


<script>
    $(document).ready(function() {
        var table = $('.table').DataTable({
            processing: true,
            serverSide: true,
            ajax: "{{ route('get-banner') }}",
            columns: [{
                    data: 'DT_RowIndex',
                    name: 'DT_RowIndex'
                },
                {
                    data: 'title',
                    name: 'title'
                },
                {
                    data: 'category',
                    name: 'category'
                },
                {
                    data: 'product',
                    name: 'product'
                },
                {
                    data: 'image',
                    name: 'image'
                },
                {
                    data: 'status',
                    name: 'status'
                },
                {
                    data: 'action',
                    name: 'action'
                }
            ]
        });

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

        // Delete Banner
        $(document).on('click', '.deletebanner', function(e) {
            e.preventDefault();
            var id = $(this).data('id');
            Swal.fire({
                title: 'Delete?',
                text: "This will permanently delete the banner!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, delete it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: "{{ url('delete-banner') }}/" + id,
                        type: 'DELETE',
                        data: {
                            _token: '{{ csrf_token() }}'
                        },
                        success: function(response) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Deleted!',
                                text: response.success,
                                timer: 1500,
                                showConfirmButton: false
                            });
                            table.ajax.reload();
                        }
                    });
                }
            });
        });

     

        $(document).on('click', '.editbanner', function () {
    let data = $(this).data();

    $('#edit_id').val(data.id);
    $('#edit_title').val(data.title);

    if (data.seasonal_banner == 1) {
        $('#edit_seasonal').prop('checked', true);
        $('#edit_start_date, #edit_end_date').prop('disabled', false).val(data.start_date);
    } else {
        $('#edit_seasonal').prop('checked', false);
        $('#edit_start_date, #edit_end_date').prop('disabled', true).val('');
    }

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


        // 🔄 Load products dynamically when category changes inside edit row
        $(document).on('change', '.edit-category', function() {
            var categoryId = $(this).val();
            var row = $(this).closest('tr');
            var productSelect = row.find('.edit-product');

            if (categoryId) {
                $.ajax({
                    url: '/get-products/' + categoryId,
                    type: 'GET',
                    success: function(data) {
                        productSelect.empty();
                        productSelect.append('<option value="">-- Select Product --</option>');
                        $.each(data, function(key, product) {
                            productSelect.append('<option value="' + product.id + '">' + product.name + '</option>');
                        });
                    }
                });
            } else {
                productSelect.empty().append('<option value="">-- Select Product --</option>');
            }
        });

        // Cancel Edit
        $(document).on('click', '.cancelEdit', function() {
            table.ajax.reload();
        });

        // Save Edited Banner
        $(document).on('click', '.savebanner', function() {
            var id = $(this).data('id');
            var row = $(this).closest('tr');
            var title = row.find('.edit-title').val();
            var category_id = row.find('.edit-category').val();
            var product_id = row.find('.edit-product').val();
            var imageFile = row.find('.edit-image')[0].files[0];

            var formData = new FormData();
            formData.append('_token', '{{ csrf_token() }}');
            formData.append('_method', 'PUT');
            formData.append('title', title);
            formData.append('category_id', category_id);
            formData.append('product_id', product_id);
            if (imageFile) formData.append('image', imageFile);

            $.ajax({
                url: "{{ url('update-banner') }}/" + 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
                    });
                    table.ajax.reload();
                },
                error: function(xhr) {
                    let msg = xhr.responseJSON?.error ?? 'Something went wrong';
                    if (xhr.responseJSON?.errors) {
                        $.each(xhr.responseJSON.errors, (k, v) => msg += '\n' + v);
                    }
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: msg
                    });
                }


            });
        });

        // 🔄 Product list update for Add form
        $(document).on('change', '#category_id', function() {
            var categoryId = $(this).val();

            if (categoryId) {
                $.ajax({
                    url: '/get-products/' + categoryId,
                    type: 'GET',
                    success: function(data) {
                        $('#product_id').empty();
                        $('#product_id').append('<option value="">-- Select Product --</option>');
                        $.each(data, function(key, product) {
                            $('#product_id').append('<option value="' + product.id + '">' + product.name + '</option>');
                        });
                    }
                });
            } else {
                $('#product_id').empty();
                $('#product_id').append('<option value="">-- Select Product --</option>');
            }
        });



        // Disable by default
        $('#start_date, #end_date').prop('disabled', true);

        $(document).on('change', '#seasonal', function() {
            if ($(this).is(':checked')) {
                $('#start_date, #end_date').prop('disabled', false)
                    .attr('required', true); // Optional
            } else {
                $('#start_date, #end_date').prop('disabled', true)
                    .removeAttr('required')
                    .val(''); // Clear dates
            }
        });

    });

    $(document).on('click', '.toggleStatusBtn', function() {
        var bannerId = $(this).data('id');
        var btn = $(this);

        $.ajax({
            url: '/banner/status/' + bannerId,
            type: 'POST',
            data: {
                _token: '{{ csrf_token() }}'
            },
            success: function(response) {
                if (response.success) {
                    if (response.status) {
                        btn.text('Active').removeClass('btn-danger').addClass('btn-success');
                    } else {
                        btn.text('Inactive').removeClass('btn-success').addClass('btn-danger');
                    }
                }
            }
        });
    });
</script>

@endsection