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

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

        <!-- Add Offer -->
        <div class="card mb-4">
            <div class="card-header">
                <h4>Add Gift Offer</h4>
            </div>
            <div class="card-body">
                <form id="addOfferForm">
                    @csrf
                    <div class="row ">
                        <div class="col-lg-3 mb-3">
                            <label>Title</label>
                            <input type="text" name="title" class="form-control" placeholder="Offer title">
                        </div>
                        <div class="col-lg-3">
                            <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>Product (optional)</label>
                            <select name="product_id" id="product_id" class="form-control">
                                <option value="">-- Select Product --</option>
                            </select>
                        </div>
                        <div class="col-lg-2">
                            <label>Discount %</label>
                            <input type="number" name="discount_percentage" class="form-control" placeholder="%">
                        </div>
                        <div class="col-lg-2">
                            <label>Flat Amount</label>
                            <input type="number" name="discount_amount" class="form-control" placeholder="₹">
                        </div>
                        <div class="col-lg-2">
                            <label>Start Date</label>
                            <input type="date" name="start_date" class="form-control">
                        </div>
                        <div class="col-lg-2">
                            <label>End Date</label>
                            <input type="date" name="end_date" class="form-control">
                        </div>
                    </div>
                    <div class="text-end mt-3">
                        <button type="submit" class="btn btn-success">Save Offer</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Offer Table -->
        <div class="card">
            <div class="card-body">
                <table class="table align-middle table-hover">
                    <thead class="bg-light">
                        <tr>
                            <th>SL.NO</th>
                            <th>Title</th>
                            <th>Category</th>
                            <th>Product</th>
                            <th>Discount</th>
                            <th>Date Range</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>


        <!-- Edit Offer Modal -->
<div class="modal fade" id="editOfferModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Edit Gift Offer</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="editOfferForm">
                    @csrf
                    <input type="hidden" id="edit_offer_id">

                    <div class="mb-3">
                        <label>Title</label>
                        <input type="text" id="edit_title" name="title" class="form-control" required>
                    </div>

                    <div class="mb-3">
                        <label>Category</label>
                        <select id="edit_category_id" name="category_id" class="form-select" required></select>
                    </div>

                    <div class="mb-3">
                        <label>Product</label>
                        <select id="edit_product_id" name="product_id" class="form-select"></select>
                    </div>

                    <div class="mb-3">
                        <label>Discount Percentage</label>
                        <input type="number" id="edit_discount_percentage" name="discount_percentage" class="form-control">
                    </div>

                    <div class="mb-3">
                        <label>Discount Amount</label>
                        <input type="number" id="edit_discount_amount" name="discount_amount" class="form-control">
                    </div>

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

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

                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="edit_is_active" name="is_active" value="1">
                        <label class="form-check-label" for="edit_is_active">Active</label>
                    </div>

                    <button type="submit" class="btn btn-success w-100">Update Offer</button>
                </form>
            </div>
        </div>
    </div>
</div>

    </div>
</div>

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

    // Add Offer
    $('#addOfferForm').submit(function(e){
        e.preventDefault();
        var formData = new FormData(this);
        $.ajax({
            url: "{{ route('add-offer') }}",
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(res){
                Swal.fire('Success', res.success, 'success');
                $('#addOfferForm')[0].reset();
                table.ajax.reload();
            },
            error: function(xhr){
                let msg = xhr.responseJSON?.message || 'Validation error';
                Swal.fire('Error', msg, 'error');
            }
        });
    });

    // Delete Offer
    $(document).on('click', '.deleteoffer', function(){
        var id = $(this).data('id');
        Swal.fire({
            title: 'Delete?',
            text: 'This will remove the offer permanently.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, delete it!'
        }).then(result => {
            if(result.isConfirmed){
                $.ajax({
                    url: '/delete-offer/' + id,
                    type: 'DELETE',
                    data: { _token: '{{ csrf_token() }}' },
                    success: function(res){
                        Swal.fire('Deleted!', res.success, 'success');
                        table.ajax.reload();
                    }
                });
            }
        });
    });

    // Toggle Status
    $(document).on('click', '.toggleStatusBtn', function(){
        var id = $(this).data('id');
        var btn = $(this);
        $.ajax({
            url: '/offer/status/' + id,
            type: 'POST',
            data: { _token: '{{ csrf_token() }}' },
            success: function(res){
                if(res.success){
                    if(res.status){
                        btn.text('Active').removeClass('btn-danger').addClass('btn-success');
                    } else {
                        btn.text('Inactive').removeClass('btn-success').addClass('btn-danger');
                    }
                }
            }
        });
    });

    // Dynamic product load
    $(document).on('change', '#category_id', function(){
        var catId = $(this).val();
        $.get('/get-products/' + catId, function(data){
            $('#product_id').html('<option value="">-- Select Product --</option>');
            $.each(data, function(i, p){
                $('#product_id').append('<option value="'+p.id+'">'+p.name+'</option>');
            });
        });
    });
});



    $(document).on('click', '.editOfferBtn', function() {
        let id = $(this).data('id');
        $.get('/gift-offer/edit/' + id, function(res) {
            let offer = res.offer;
            $('#edit_offer_id').val(offer.id);
            $('#edit_title').val(offer.title);
            $('#edit_discount_percentage').val(offer.discount_percentage);
            $('#edit_discount_amount').val(offer.discount_amount);
            $('#edit_start_date').val(offer.start_date);
            $('#edit_end_date').val(offer.end_date);
            $('#edit_is_active').prop('checked', offer.is_active);

            // Populate categories
            $('#edit_category_id').empty();
            res.categories.forEach(cat => {
                $('#edit_category_id').append(
                    `<option value="${cat.id}" ${cat.id == offer.category_id ? 'selected' : ''}>${cat.name}</option>`
                );
            });

            // Populate products
            $('#edit_product_id').empty().append('<option value="">-- None --</option>');
            res.products.forEach(prod => {
                $('#edit_product_id').append(
                    `<option value="${prod.id}" ${prod.id == offer.product_id ? 'selected' : ''}>${prod.name}</option>`
                );
            });

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

    // Update Offer
   $('#editOfferForm').on('submit', function(e) {
    e.preventDefault();

    let id = $('#edit_offer_id').val();
    let formData = $(this).serialize();

    $.post('/gift-offer/update/' + id, formData, function(res) {
        if (res.success) {
            Swal.fire({
                title: 'Updated!',
                text: res.message,
                icon: 'success',
                confirmButtonColor: '#28a745',
                timer: 2000,
                showConfirmButton: false
            });

            $('#editOfferModal').modal('hide');

            // Optional small delay before reload for smooth UX
            setTimeout(() => {
                location.reload(); // or update table row dynamically
            }, 1500);
        }
    }).fail(function(xhr) {
        let msg = 'An error occurred.';
        if (xhr.responseJSON && xhr.responseJSON.message) {
            msg = xhr.responseJSON.message;
        }

        Swal.fire({
            title: 'Error!',
            text: msg,
            icon: 'error',
            confirmButtonColor: '#d33'
        });
    });
});


</script>
@endsection
