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

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

        <!-- Add Coupon -->
        <div class="card mb-4">
            <div class="card-header">
                <h4>Add Coupon</h4>
            </div>
            <div class="card-body">
                <form id="addCouponForm">
                    @csrf
                    <div class="row">
                        <div class="col-lg-3 mb-3">
                            <label>Coupon Code</label>
                            <input type="text" name="code" class="form-control" placeholder="e.g. SAVE10">
                        </div>
                        <div class="col-lg-3 mb-3">
                            <label>Type</label>
                            <select name="type" class="form-control">
                                <option value="percentage">Percentage</option>
                                <option value="fixed">Fixed</option>
                            </select>
                        </div>
                        <div class="col-lg-3 mb-3">
                            <label>Value</label>
                            <input type="number" name="value" class="form-control" placeholder="10 or 100">
                        </div>
                        <div class="col-lg-3 mb-3">
                            <label>Country</label>
                            <select id="country_id" name="country_id" class="form-control">
                                <option value="">-- Select Country --</option>
                                @foreach(App\Models\Country::all() as $country)
                                <option value="{{ $country->id }}">{{ $country->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-lg-3 mb-3">
                            <label>Category</label>
                            <select id="category_id" name="category_id" class="form-control">
                                <option value="">-- Select Category --</option>
                            </select>
                        </div>
                        <div class="col-lg-3 mb-3">
                            <label>Product</label>
                            <select id="product_id" name="product_id" class="form-control">
                                <option value="">-- Select Product --</option>
                            </select>
                        </div>
                        <div class="col-lg-3 mb-3">
                            <label>Min Purchase</label>
                            <input type="number" name="min_purchase" class="form-control">
                        </div>
                        <div class="col-lg-3 mb-3">
                            <label>Max Uses</label>
                            <input type="number" name="max_uses" class="form-control">
                        </div>
                        <div class="col-lg-3 mb-3">
                            <label>Per User Limit</label>
                            <input type="number" name="per_user_limit" class="form-control">
                        </div>
                        <div class="col-lg-3 mb-3">
                            <label>Start Date</label>
                            <input type="date" name="start_date" class="form-control">
                        </div>
                        <div class="col-lg-3 mb-3">
                            <label>End Date</label>
                            <input type="date" name="end_date" class="form-control">
                        </div>
                        <div class="col-lg-3 mb-3">
                            <label>Description</label>
                            <input type="text" name="description" class="form-control">
                        </div>
                    </div>
                    <div class="text-end mt-3">
                        <button type="submit" class="btn btn-success">Save Coupon</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Coupon Table -->
        <div class="card">
            <div class="card-body">
                <table class="table align-middle table-hover">
                    <thead class="bg-light">
                        <tr>
                            <th>#</th>
                            <th>Code</th>
                            <th>Type/Value</th>
                            <th>Country</th>
                            <th>Category</th>
                            <th>Product</th>
                            <th>Date Range</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>

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

                            <div class="mb-2">
                                <label>Code</label>
                                <input type="text" id="edit_code" name="code" class="form-control">
                            </div>
                            <div class="mb-2">
                                <label>Type</label>
                                <select id="edit_type" name="type" class="form-select">
                                    <option value="percentage">Percentage</option>
                                    <option value="fixed">Fixed</option>
                                </select>
                            </div>
                            <div class="mb-2">
                                <label>Value</label>
                                <input type="number" id="edit_value" name="value" class="form-control">
                            </div>
                            <div class="mb-2">
                                <label>Country</label>
                                <select id="edit_country_id" name="country_id" class="form-select"></select>
                            </div>
                            <div class="mb-2">
                                <label>Category</label>
                                <select id="edit_category_id" name="category_id" class="form-select"></select>
                            </div>
                            <div class="mb-2">
                                <label>Product</label>
                                <select id="edit_product_id" name="product_id" class="form-select"></select>
                            </div>
                            <div class="mb-2">
                                <label>Start Date</label>
                                <input type="date" id="edit_start_date" name="start_date" class="form-control">
                            </div>
                            <div class="mb-2">
                                <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 type="hidden" name="is_active" value="0">
                                <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 Coupon</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>


<script>
    $(function() {
        var table = $('.table').DataTable({
            processing: true,
            serverSide: true,
            ajax: "{{ route('get-coupons') }}",
            columns: [{
                    data: 'DT_RowIndex',
                    name: 'DT_RowIndex',
                    orderable: false,
                    searchable: false
                },
                {
                    data: 'code',
                    name: 'code'
                },
                {
                    data: 'type_value',
                    name: 'type_value'
                },
                {
                    data: 'country',
                    name: 'country'
                },
                {
                    data: 'category',
                    name: 'category'
                },
                {
                    data: 'product',
                    name: 'product'
                },
                {
                    data: 'date_range',
                    name: 'date_range'
                },
                {
                    data: 'status',
                    name: 'status',
                    orderable: false,
                    searchable: false
                },
                {
                    data: 'action',
                    name: 'action',
                    orderable: false,
                    searchable: false
                },
            ]
        });

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

        // Delete coupon
        $(document).on('click', '.deleteCoupon', function() {
            var id = $(this).data('id');
            Swal.fire({
                    title: 'Delete?',
                    text: 'Remove this coupon?',
                    icon: 'warning',
                    showCancelButton: true
                })
                .then(result => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: '/delete-coupon/' + id,
                            type: 'DELETE',
                            data: {
                                _token: '{{csrf_token()}}'
                            },
                            success: 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);
            $.post('/coupon/status/' + id, {
                _token: '{{csrf_token()}}'
            }, function(res) {
                if (res.status) {
                    btn.text('Active').removeClass('btn-danger').addClass('btn-success');
                } else {
                    btn.text('Inactive').removeClass('btn-success').addClass('btn-danger');
                }
            });
        });

        // Edit coupon modal
        // $(document).on('click', '.editCouponBtn', function() {
        //     let id = $(this).data('id');
        //     $.get('/coupon/edit/' + id, function(res) {
        //         let c = res.coupon;
        //         $('#edit_coupon_id').val(c.id);
        //         $('#edit_code').val(c.code);
        //         $('#edit_type').val(c.type);
        //         $('#edit_value').val(c.value);
        //         $('#edit_start_date').val(c.start_date);
        //         $('#edit_end_date').val(c.end_date);
        //         $('#edit_is_active').prop('checked', c.is_active);

        //         $('#edit_country_id').empty().append('<option value="">All</option>');
        //         res.countries.forEach(r => {
        //             $('#edit_country_id').append(`<option value="${r.id}" ${r.id==c.country_id?'selected':''}>${r.name}</option>`);
        //         });
        //         $('#edit_category_id').empty().append('<option value="">All</option>');
        //         res.categories.forEach(r => {
        //             $('#edit_category_id').append(`<option value="${r.id}" ${r.id==c.category_id?'selected':''}>${r.name}</option>`);
        //         });
        //         $('#edit_product_id').empty().append('<option value="">All</option>');
        //         res.products.forEach(r => {
        //             $('#edit_product_id').append(`<option value="${r.id}" ${r.id==c.product_id?'selected':''}>${r.name}</option>`);
        //         });

        //         $('#editCouponModal').modal('show');
        //     });
        // });

        // Update coupon
        $('#editCouponForm').submit(function(e) {
            e.preventDefault();
            let id = $('#edit_coupon_id').val();
            $.post('/coupon/update/' + id, $(this).serialize(), function(res) {
                Swal.fire('Updated', res.message, 'success');
                $('#editCouponModal').modal('hide');
                table.ajax.reload();
            }).fail(function(xhr) {
                Swal.fire('Error', xhr.responseJSON?.message || 'Error updating coupon', 'error');
            });
        });
    });

    $(document).ready(function() {

        // When Country Changes
        $('#country_id').on('change', function() {
            var countryId = $(this).val();
            $('#category_id').html('<option value="">Loading...</option>');
            $('#product_id').html('<option value="">-- Select Product --</option>');

            if (countryId) {
                $.ajax({
                    url: '/get-categories/' + countryId,
                    type: 'GET',
                    success: function(data) {
                        $('#category_id').html('<option value="">-- Select Category --</option>');
                        $.each(data, function(key, category) {
                            $('#category_id').append('<option value="' + category.id + '">' + category.name + '</option>');
                        });
                    }
                });
            } else {
                $('#category_id').html('<option value="">-- Select Category --</option>');
            }
        });

        // When Category Changes
        $('#category_id').on('change', function() {
            var categoryId = $(this).val();
            $('#product_id').html('<option value="">Loading...</option>');

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


            // 🟢 1️⃣ When clicking "Edit" button — open modal & load data
    $(document).on('click', '.editCouponBtn', function() {
        let id = $(this).data('id');

        $.ajax({
            url: '/coupons/' + id + '/edit',
            type: 'GET',
            success: function(res) {
                let c = res.data;

                $('#edit_coupon_id').val(c.id);
                $('#edit_code').val(c.code);
                $('#edit_type').val(c.type);
                $('#edit_value').val(c.value);
                $('#edit_start_date').val(c.start_date);
                $('#edit_end_date').val(c.end_date);
                $('#edit_is_active').prop('checked', c.is_active == 1);

                // --- Load countries dropdown first ---
                loadCountries(c.country_id, c.category_id, c.product_id);

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

    // 🟢 2️⃣ When country changes inside edit modal
    $('#edit_country_id').on('change', function() {
        let countryId = $(this).val();
        $('#edit_category_id').html('<option>Loading...</option>');
        $('#edit_product_id').html('<option>-- Select Product --</option>');

        if (countryId) {
            $.get('/get-categories/' + countryId, function(data) {
                $('#edit_category_id').html('<option value="">-- Select Category --</option>');
                $.each(data, function(i, cat) {
                    $('#edit_category_id').append('<option value="' + cat.id + '">' + cat.name + '</option>');
                });
            });
        }
    });

    // 🟢 3️⃣ When category changes inside edit modal
    $('#edit_category_id').on('change', function() {
        let categoryId = $(this).val();
        $('#edit_product_id').html('<option>Loading...</option>');

        if (categoryId) {
            $.get('/get-products/' + categoryId, function(data) {
                $('#edit_product_id').html('<option value="">-- Select Product --</option>');
                $.each(data, function(i, prod) {
                    $('#edit_product_id').append('<option value="' + prod.id + '">' + prod.name + '</option>');
                });
            });
        }
    });

    // 🟢 Helper function to load dropdowns and preselect existing values
    function loadCountries(selectedCountryId, selectedCategoryId = null, selectedProductId = null) {
        $.get('/get-countries-list', function(countries) {
            $('#edit_country_id').html('<option value="">-- Select Country --</option>');
            $.each(countries, function(i, country) {
                let selected = country.id == selectedCountryId ? 'selected' : '';
                $('#edit_country_id').append('<option value="' + country.id + '" ' + selected + '>' + country.name + '</option>');
            });

            // Load categories for selected country
            if (selectedCountryId) {
                $.get('/get-categories/' + selectedCountryId, function(cats) {
                    $('#edit_category_id').html('<option value="">-- Select Category --</option>');
                    $.each(cats, function(i, cat) {
                        let selected = cat.id == selectedCategoryId ? 'selected' : '';
                        $('#edit_category_id').append('<option value="' + cat.id + '" ' + selected + '>' + cat.name + '</option>');
                    });

                    // Load products for selected category
                    if (selectedCategoryId) {
                        $.get('/get-products/' + selectedCategoryId, function(prods) {
                            $('#edit_product_id').html('<option value="">-- Select Product --</option>');
                            $.each(prods, function(i, prod) {
                                let selected = prod.id == selectedProductId ? 'selected' : '';
                                $('#edit_product_id').append('<option value="' + prod.id + '" ' + selected + '>' + prod.name + '</option>');
                            });
                        });
                    }
                });
            }
        });
    }
    });
</script>
@endsection