<style>
    .amount-field,
    .percentage-field {
        display: none;
    }
</style>
{{>header}}
<title>Coupons</title>
<div class="row p-2" style="margin: 0px !important;">
    <div class="col-md-12">
        <div class="card mt-2">
            <div class="card-header" style="background-color:white; color:#4B0F77;">
                <h4><b>Coupons</b></h4>
            </div>
            <div class="card-body p-2">
                <div id="example1_wrapper">
                    <div class="row">
                        <div class="col-sm-12">
                            <ol class="float-sm-right">
                                <button href="" id="" data-bs-toggle="modal" data-bs-target="#addModal"
                                    style="background-color: rgb(0, 0, 0); color:white; border:none; border-radius:5px; width: 180px; height: 40px; "><i
                                        class="fa-solid fa-plus"></i> Add Coupon</button>
                            </ol>
                        </div>
                        <div class="col-sm-12 table-responsive">
                            <table id="example2" aria-describedby="example1_info">
                                <thead>
                                    <tr>
                                        <th class="sorting" tabindex="0" aria-controls="example1">S.No</th>
                                        <th class="sorting" tabindex="0" aria-controls="example1">Name</th>
                                        <th class="sorting" tabindex="0" aria-controls="example1">Type</th>
                                        <th class="sorting" tabindex="0" aria-controls="example1">Code</th>
                                        <th class="sorting" tabindex="0" aria-controls="example1">Amount</th>
                                        <th class="sorting" tabindex="0" aria-controls="example1">Percentage</th>
                                        <th class="sorting" tabindex="0" aria-controls="example1">Price Range</th>
                                        <th class="sorting" tabindex="0" aria-controls="example1">Status</th>
                                        <th class="sorting" tabindex="0" aria-controls="example1">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {{#each allCoupouns}}
                                    <tr class="odd">
                                        <td>{{inc @index}}</td>
                                        <td>{{this.name}}</td>
                                        <td>{{this.type}}</td>
                                        <td>{{this.code}}</td>
                                        <td>{{#if this.amount}}{{this.amount}}{{else}}N/A{{/if}}</td>
                                        <td>{{#if this.percentage}}{{this.percentage}}{{else}}N/A{{/if}}</td>
                                        <td>{{this.priceRange}}</td>
                                        <td>{{this.status}}</td>
                                        <td>
                                            <div class="eye d-flex justify-content-center">
                                                <a href="/admin/v1/singlecoupon/{{this._id}}"
                                                    class="btn btn-md btn-info m-1">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                                {{!-- <a href="javascript:void(0);" data-bs-toggle="modal"
                                                    data-bs-target="#updateModal" class="btn btn-md btn-warning m-1"
                                                    data-id="{{this._id}}" data-name="{{this.name}}"
                                                    data-type="{{this.type}}" data-amount="{{this.amount}}"
                                                    data-percentage="{{this.percentage}}" data-code="{{this.code}}"
                                                    data-pricerange="{{this.priceRange}}" data-status="{{this.status}}"
                                                    data-vendor='{{json this.vendor}}'>
                                                    <i class="fa-solid fa-edit"></i>
                                                </a> --}}
                                                <a href="javascript:void(0);" data-bs-toggle="modal"
                                                    data-id="{{this._id}}" data-bs-target="#deleteModal"
                                                    class="btn btn-md btn-danger m-1">
                                                    <i class="fa-solid fa-trash"></i>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                    {{/each}}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{{!-- add modal --}}
<div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="addModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 style="color: black; font-weight: bold; font-size: 40px;">Add Coupon</h5>
            </div>
            <form id="addCouponForm" action="/admin/v1/addcoupoun" method="post">
                <div class="modal-body">
                    <label for="name">Name</label>
                    <input type="text" class="form-control" name="name" placeholder="Coupoun Name"
                        pattern="^[A-Za-z]+(?: [A-Za-z]+)*$" required
                        title="Name must not have leading/trailing spaces or special characters." minlength="2"
                        maxlength="50">
                    <label for="name">Minimum purchase amount</label>
                    <input type="number" class="form-control" name="priceRange" placeholder="Minimum purchasal amount"
                        required min="1" max="99999">
                    <label for="type">Coupoun Code</label>
                    <input type="text" class="form-control" name="code" placeholder="Coupon code: ENTRYBONUS" required
                        minlength="5" maxlength="20"
                        oninput="this.value = this.value.toUpperCase().replace(/[^A-Z0-9]/g, '')"
                        style="text-transform: uppercase;" pattern="^(?=.*[A-Z])(?=.*\d)[A-Z0-9]{5,20}$"
                        title="Must be 5-20 characters and include both letters and numbers.">

                    <label for="type">Type</label>
                    <select name="type" class="form-control" id="discountTypeSelect">
                        <option value="amount">Amount</option>
                        <option value="percentage">Percentage</option>
                    </select>
                    <div id="amountSection">
                        <label for="amount">Amount</label>
                        <input type="number" class="form-control" name="amount" required
                            placeholder="Enter discount amount" min="1" max="99999">
                    </div>
                    <div id="percentageSection" style="display: none;">
                        <label for="percentage">Percentage</label>
                        <input type="number" class="form-control" name="percentage" required
                            placeholder="Enter percentage" min="0" max="100">
                    </div>
                   <div class="form-group">
                    <label for="vendors">Select Vendors</label>

                    <input type="text" id="vendorSearch" class="form-control mb-2" placeholder="Search vendor...">

                    <div id="vendors" class="checkbox-list border rounded p-2" style="max-height: 200px; overflow-y: auto;">
                        {{#each allVendors}}
                        <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="vendors" id="vendor_{{this._id}}" value="{{this._id}}">
                        <label class="form-check-label" for="vendor_{{this._id}}">
                            {{this.communityName}}
                        </label>
                        </div>
                        {{/each}}
                    </div>
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-success">Add</button>
                </div>
            </form>
        </div>
    </div>
</div>
   {{!-- Vendor search functionality --}}
{{!-- <script>
  document.getElementById("vendorSearch").addEventListener("keyup", function () {
    const searchValue = this.value.toLowerCase();
    const vendors = document.querySelectorAll("#vendors .form-check");

    vendors.forEach(vendor => {
      const label = vendor.querySelector(".form-check-label").textContent.toLowerCase();
      vendor.style.display = label.includes(searchValue) ? "block" : "none";
    });
  });
</script> --}}
<script>
  const searchInput = document.getElementById("vendorSearch");
  const vendorList = document.getElementById("vendors");
  const vendors = vendorList.querySelectorAll(".form-check");

  // Hide vendors initially
  vendors.forEach(v => v.style.display = "none");

  searchInput.addEventListener("keyup", function () {
    const searchValue = this.value.toLowerCase().trim();

    if (searchValue === "") {
      // Hide all vendors if search is empty
      vendors.forEach(v => v.style.display = "none");
      return;
    }

    vendors.forEach(vendor => {
      const text = vendor.textContent.toLowerCase();
      vendor.style.display = text.includes(searchValue) ? "block" : "none";
    });
  });
</script>
{{!-- script for add model toggle --}}
<script>
    document.addEventListener("DOMContentLoaded", function () {
        const typeSelect = document.getElementById("discountTypeSelect");
        const amountSection = document.getElementById("amountSection");
        const percentageSection = document.getElementById("percentageSection");
        const amountInput = amountSection.querySelector('input[name="amount"]');
        const priceRangeInput = document.querySelector('input[name="priceRange"]');
        const percentageInput = percentageSection.querySelector('input[name="percentage"]');
        const addCouponForm = document.getElementById("addCouponForm");

        function toggleDiscountFields() {
            if (typeSelect.value === "amount") {
                amountSection.style.display = "block";
                amountInput.required = true;

                percentageSection.style.display = "none";
                percentageInput.required = false;
                percentageInput.value = ""; // Clear value if not used
            } else {
                percentageSection.style.display = "block";
                percentageInput.required = true;

                amountSection.style.display = "none";
                amountInput.required = false;
                amountInput.value = ""; // Clear value if not used
            }
        }
        const modal = document.getElementById("addModal");
        modal.addEventListener("hidden.bs.modal", function () {
            addCouponForm.reset();
        });


        function enforceMinMax(input) {
            input.addEventListener("input", function () {
                const value = parseInt(input.value, 10);
                if (value > 99999) input.value = 99999;
                if (value < 1) input.value = 1;
            });
        }

        enforceMinMax(amountInput);
        enforceMinMax(priceRangeInput);


        // Initialize on load
        toggleDiscountFields();

        // Listen for changes
        typeSelect.addEventListener("change", toggleDiscountFields);
    });
</script>
{{!-- update --}}
<div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="updateModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h3 style="color: black; font-weight: bold;">Update Coupon</h3>
            </div>
            <form id="updateForm" action="/admin/updatecoupoun/{{this._id}}" method="post">
                <div class="modal-body">
                    <label for="name">Name</label>
                    <input type="text" class="form-control" name="name" placeholder="Coupoun Name"
                        pattern="^[A-Za-z]+(?: [A-Za-z]+)*$" required
                        title="Name must not have leading/trailing spaces or special characters." minlength="2"
                        maxlength="50">
                    <label for="name">Minimum purchase amount</label>
                    <input type="number" class="form-control" name="priceRange" placeholder="Minimum purchasal amount"
                        required min="1" max="99999">
                    <label for="code">Coupon Code</label>
                    <input type="text" class="form-control" name="code" placeholder="Coupon code: ENTRYBONUS" required
                        minlength="5" maxlength="20"
                        oninput="this.value = this.value.toUpperCase().replace(/[^A-Z0-9]/g, '')"
                        style="text-transform: uppercase;" pattern="^(?=.*[A-Z])(?=.*\d)[A-Z0-9]{5,20}$"
                        title="Must be 5-20 characters and include both letters and numbers.">

                    <label for="type">Type</label>
                    <select name="type" class="form-control type" id="discountTypeSelect2">
                        <option value="amount">Amount</option>
                        <option value="percentage">Percentage</option>
                    </select>
                    <div class="amount-field" id="amountSection2">
                        <label for="amount">Amount</label>
                        <input type="number" class="form-control" name="amount" required min="1" max="99999"
                            placeholder="Enter discount amount">
                    </div>
                    <div class="percentage-field" id="percentageSection2" style="display: none;">
                        <label for="percentage">Percentage</label>
                        <input type="number" class="form-control" name="percentage" required min="0" max="100"
                            placeholder="Enter discount percentage">
                    </div>
                    <label for="status">Status</label>
                    <select name="status" class="form-control statuses" value="1">
                        <option value="Active">Active</option>
                        <option value="Inactive">Inactive</option>
                    </select>
                    <div class="form-group">
                        <label for="vendors">Select Vendors</label>
                        <div id="vendors" class="checkbox-list border rounded p-2"
                            style="max-height: 200px; overflow-y: auto;">
                            {{#each allVendors}}
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="vendors" id="vendor_{{this._id}}"
                                    value="{{this._id}}" {{#ifIn this._id ../vendor}}checked{{/ifIn}}>
                                <label class="form-check-label" for="vendor_{{this._id}}">
                                    {{this.storeName}}
                                </label>
                            </div>
                            {{/each}}
                        </div>
                    </div>


                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-success" id="updateButton"
                        style="background-color: rgb(0, 0, 0); color:white">Update</button>
                </div>
            </form>
        </div>
    </div>
</div>
{{!-- script to show existing data in update form --}}
<script>
    $(document).ready(function () {
        $('#updateModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget);
            var modal = $(this);
            if (typeof vendor === 'string') {
                try {
                    vendor = JSON.parse(vendor);
                } catch (e) {
                    vendor = [vendor];
                }
            }
            var categoryId = button.data('id');
            var name = button.data('name');
            var type = button.data('type');
            var code = button.data('code');
            var amount = button.data('amount');
            var percentage = button.data('percentage');
            var priceRange = button.data('pricerange');
            var vendor = button.data('vendor');
            var status = button.data('status');
            modal.find('form').attr('action', '/admin/updatecoupoun/' + categoryId);
            modal.find('input[name="name"]').val(name);
            modal.find('input[name="amount"]').val(amount);
            modal.find('input[name="code"]').val(code);
            modal.find('input[name="percentage"]').val(percentage);
            modal.find('input[name="priceRange"]').val(priceRange);
            modal.find('.statuses').val(status);
            modal.find('.type').val(type);
            if (type === 'amount') {
                $('.amount-field').show();
                $('.percentage-field').hide();
            } else if (type === 'percentage') {
                $('.amount-field').hide();
                $('.percentage-field').show();
            } else {
                $('.amount-field, .percentage-field').hide();
            }
            var button = $(event.relatedTarget);

            var vendorSelect = modal.find('select[name="vendors"]');
            vendorSelect.find('option').prop('selected', false);

            // Set selected vendors
            if (vendor && vendor.length > 0) {
                vendorSelect.val(vendor);
            }

            // If using Select2 or Bootstrap Select, trigger change
            vendorSelect.trigger('change');
        });
    });
</script>
{{!-- script for update model toggle --}}
<script>
    document.addEventListener("DOMContentLoaded", function () {
        const typeSelect = document.getElementById("discountTypeSelect2");
        const amountSection = document.getElementById("amountSection2");
        const percentageSection = document.getElementById("percentageSection2");
        const amountInput = amountSection.querySelector('input[name="amount"]');
        const percentageInput = percentageSection.querySelector('input[name="percentage"]');

        function toggleDiscountFields2() {
            if (typeSelect.value === "amount") {
                amountSection.style.display = "block";
                amountInput.required = true;

                percentageSection.style.display = "none";
                percentageInput.required = false;
                percentageInput.value = ""; // Clear value if not used
            } else {
                percentageSection.style.display = "block";
                percentageInput.required = true;

                amountSection.style.display = "none";
                amountInput.required = false;
                amountInput.value = ""; // Clear value if not used
            }
        }

        // Initialize on load
        toggleDiscountFields2();

        // Listen for changes
        typeSelect.addEventListener("change", toggleDiscountFields2);
    });
</script>
{{!-- delete --}}
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModal" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 style="color: black; font-weight: 480;">Are you sure you want to delete this?</h4>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">No</button>
                <a href="/admin/v1/deletecoupoun/{{this._id}}" type="button" class="btn btn-danger"> yes </a>
            </div>
        </div>
    </div>
</div>
<script>
    $(document).ready(function () {
        $('#deleteModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget);
            var categoryId = button.data('id');
            var modal = $(this);
            modal.find('a.btn-danger').attr('href', '/admin/v1/deletecoupoun/' + categoryId);
        });
    });
</script>
{{>footer}}
<script>
    $(document).ready(function () {
        if (!$.fn.DataTable.isDataTable('#example2')) {
            $('#example2').addClass('table table-bordered table-striped').DataTable({
                "paging": true,
            });
        }
    });
</script>

</html>