@extends('Admin.layouts.master')

@section('content')
    @php
        $currentPage = 'manage-referral-codes';
    @endphp
    <style>
        .switch-btn input[switch]+label {
            width: 6.8rem !important;
        }

        .switch-btn input[switch]:checked+label:after {
            left: 5.22rem !important;
        }
    </style>
    <div class="layout-px-spacing">
        <div class="middle-content container-xxl p-0">
            <div class="row layout-top-spacing ">
                <div class="top-tabel">
                    <div class="row">
                        <div class="col-md-4">
                            <h6 class="card-title">Manage Referral Codes </h6>
                        </div>
                        <div class="col-md-8">

                        </div>
                    </div>
                </div>
                <div class="col-xl-12 col-lg-12 col-sm-12 layout-spacing">
                    <div class="widget-content widget-content-area br-8 position-btn" style="overflow: auto;">
                        <table id="zero-config" class="table dt-table-hover manage_referral_table" style="width:100%">
                            <thead class="text-center">
                                <meta name="csrf-token" content="{{ csrf_token() }}">
                                <tr>
                                    <th class="text-center">Sr no</th>
                                    <th class="text-center">Referral Code</th>
                                    <th class="no-content">Status</th>

                                    <th class="no-content">Action</th>
                                </tr>
                            </thead>
                            <tbody class="text-center">
                                @foreach ($referralCodes as $referralCodeItem)
                                    <tr>
                                        <td class="text-center">{{ $loop->iteration }}</td>
                                        <td class="text-center">{{ $referralCodeItem->referral_code }}</td>
                                        <td class="text-start">
                                            <div class="switch-btn">
                                                <input type="checkbox" data-id = "{{ $referralCodeItem->id }}"
                                                    class="active_referral_code" id="switch{{ $referralCodeItem->id }}"
                                                    value="1" {{ $referralCodeItem->is_active ? 'checked' : '' }}
                                                    switch="bool" />
                                                <label for="switch{{ $referralCodeItem->id }}" data-on-label="Active"
                                                    data-off-label="Deactivated"></label>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="dropout">
                                                <button class="more">
                                                    <span></span>
                                                    <span></span>
                                                    <span></span>
                                                </button>
                                                <ul>

                                                    <li>

                                                        <a href="#" data-toggle="modal"
                                                            data-target="#edit-referral-code"
                                                            class="edit_referral_code_value"
                                                            data-code-id="{{ $referralCodeItem->id }}"
                                                            data-code-referral_code="{{ $referralCodeItem->referral_code }}">
                                                            <img src="{{ asset('public/assets/img/edit.svg') }}" />
                                                            <span>Edit</span>
                                                        </a>
                                                    </li>
                                                    {{-- <li>
                                                        <a class="delete_location" data-id="{{ $referralCodeItem->id }}"
                                                            data-toggle="modal" data-target="#delete-location-modal">
                                                            <img
                                                                src="{{ asset('public/assets/img/delete-recycle.svg') }}" />
                                                            <span>Delete</span>
                                                        </a>
                                                    </li> --}}

                                                </ul>
                                            </div>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>

            </div>
        </div>
    </div>

    <div class="modal fade" id="add_code_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-body">
                    <div class="modal-header p-0">
                        <h5 class="modal-title">Add Referral Code</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="row">
                        <form id="store_referral_code">
                            @csrf
                            <div class="col-md-12">
                                <label for="referral_code">Referral Code</label>
                                <input id="referral_code" name="referral_code" class="form-control" type="text"
                                    placeholder="Enter Referral Code"
                                    oninput="this.value = this.value.toUpperCase().replace(/\s/g, '')" maxlength="15">


                            </div>
                            <button type="submit" id="submit_referral_code" class="download-btn-custom mt-4 mx-auto w-25">
                                <span>Save</span>
                            </button>
                        </form>
                    </div>



                </div>
            </div>
        </div>
    </div>



    <div class="modal fade" id="edit-referral-code" tabindex="-1" role="dialog" aria-labelledby="editLocationModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <form id="edit_referral_code" enctype="multipart/form-data">
                    @csrf
                    <input class="form-control" name="id" type="hidden" id="referral_id" value="">
                    <input class="form-control" name="referral_code" type="hidden" id="referral_code" value="">
                    <div class="modal-header">
                        <h5 class="modal-title" id="editLocationModalLabel" style="text-align:center;">Edit Referral Code
                        </h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="referral_code">Referral Code</label>
                            <input type="text" class="form-control" id="referral_code" name="referral_code"
                                placeholder="Enter Referral Code"
                                oninput="this.value = this.value.toUpperCase().replace(/\s/g, '')" maxlength="15">
                        </div>

                    </div>
                    <div class="modal-footer">
                        <button type="submit" id="update_referral_code" class="download-btn-custom mt-4 mx-auto w-25">
                            <span>Update</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>







    <div class="modal fade" id="delete-location-modal" tabindex="-1" role="dialog"
        aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close">
                        x
                    </button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="delete_referral_code_id" name="location_id">
                    <p class="modal-text">Are you sure you want to delete<br> this referral code </p>
                    <div class="modal-btn d-flex ">
                        <a type="button" class="extra-btn" data-dismiss="modal">No</a>
                        <a type="button" class="download-btn-custom delete_referral_code_button"
                            data-dismiss="modal">Yes</a>
                    </div>

                </div>
            </div>
        </div>
    </div>
@endsection
@section('section_script')
    <script src="{{ asset('public/assets/js/admin/manage_location/main.js') }}"></script>
    {{-- <script src="{{ asset('public/assets/js/admin/manage_location/add_location.js') }}"></script>
    <script src="{{ asset('public/assets/js/admin/manage_location/edit_location.js') }}"></script> --}}
    <script>
        $(document).ready(function() {
            $(' <button><a class="extra-btn width-max-content" data-toggle="modal" data-target="#add_code_modal" href="">Add</a></button>')
                .insertBefore("#zero-config_filter label");
        });
    </script>

    <script>
        //add referral code 
        $(document).on("click", "#submit_referral_code", function(e) {
            $('#store_referral_code').validate({
                rules: {
                    referral_code: {
                        required: true,
                        maxlength: 15
                    },

                },
                messages: {
                    referral_code: {
                        required: "Please enter referral code.",
                    },

                },
                errorClass: 'error-message',
                submitHandler: function(form) {
                    e.preventDefault();
                    let base_url = url_path;
                    var formData = new FormData(form);
                    $('#submit_referral_code').text('Please wait...');
                    $('#submit_referral_code').attr('disabled', true);
                    $.ajaxSetup({
                        headers: {
                            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
                        },
                    });
                    $.ajax({
                        url: base_url + '/add-referral-code',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(response) {
                            if (response.status == 200) {
                                toastr.success('Referral Code added successfully');
                                setTimeout(function() {
                                    window.location.href = base_url +
                                        "/manage-referral-codes";
                                }, 1000);
                            } else if (response.status == 422 && response.error ===
                                'Referral Code name already exists') {
                                toastr.error('Referral Code name already exists');
                            } else {
                                toastr.error("Something went wrong");
                                window.location.reload();
                            }
                            $('#submit_referral_code').attr('disabled', false);
                            $('#submit_referral_code').text('Save');
                        },
                        error: function(xhr, status, error) {
                            // Handle the case where the server returns an error
                            if (xhr.status == 422 && xhr.responseJSON.error ===
                                'Referral Code name already exists') {
                                toastr.error('Referral Code name already exists');
                            } else {
                                toastr.error("An error occurred");
                                window.location.reload();
                            }

                            $('#submit_referral_code').attr('disabled', false);
                            $('#submit_referral_code').text('Save');
                            window.location.reload();
                        }
                    });
                }
            });
        });
    </script>
    <script>
        $(document).ready(function() {
            $(document).on("click", ".edit_referral_code_value", function(e) {
                e.preventDefault(); // Prevent default action

                var referralId = $(this).data('code-id');
                var referralCode = $(this).data('code-referral_code');


                console.log('referralId ID:', referralId);


                $('#referral_id').val(referralId);
                $('#referral_code').val(referralCode);


                $('#edit-referral-code').modal('show');
            });
        });
    </script>



    <script>
        $(document).ready(function() {
            // Assuming you have a mechanism to set manage_state_xid in the modal
            $('#edit-referral-code').on('show.bs.modal', function(event) {
                var button = $(event.relatedTarget); // Button that triggered the modal
                var locationId = button.data('code-id'); // Extract info from data-* attributes
                var manageStateXid = button.data('code-referral_code');

                // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
                // Update the modal's content.
                var modal = $(this);
                modal.find('#location_id').val(locationId);
                modal.find('#manage_state_xid').val(manageStateXid);

                modal.find('#referral_id').val(locationId);
                modal.find('#referral_code').val(manageStateXid);


            });

            $('#edit_referral_code').validate({
                rules: {
                    referral_code: {
                        required: true
                    },

                },
                messages: {
                    referral_code: {
                        required: "Please enter the Referral name."
                    },

                },
                errorClass: 'error-message',
                submitHandler: function(form) {
                    var formData = new FormData(form);
                    let base_url = url_path;
                    $('#update_referral_code').text('Please wait...');
                    $('#update_referral_code').attr('disabled', true);
                    $.ajax({
                        url: base_url + '/update_referral_code',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(result) {
                            if (result.success) {
                                toastr.success('Referral Code updated successfully');
                                setTimeout(function() {
                                    window.location.href = base_url +
                                        "/manage-referral-codes";
                                }, 2000);
                            } else {
                                toastr.error(result.error || 'Something went wrong');
                                window.location.reload();
                            }
                            $('#update_referral_code').attr('disabled', false);
                            $('#update_referral_code').text('Save');
                        },
                        error: function(xhr, status, error) {
                            toastr.error('Something went wrong');
                            $('#update_referral_code').attr('disabled', false);
                            $('#update_referral_code').text('Save');
                            window.location.reload();
                        }
                    });
                }
            });
        });
    </script>

    <script>
        $(document).on("click", ".delete_location", function() {
            var delete_id = $(this).data('id');
            $('#delete_referral_code_id').val(delete_id);
        });

        $(document).on("click", ".delete_referral_code_button", function(e) {
            e.preventDefault();
            let base_url = url_path;
            var delete_id = $('#delete_referral_code_id').val();
            $.ajaxSetup({
                headers: {
                    "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
                },
            });
            $.ajax({
                type: "DELETE",
                url: base_url + "/delete_referral_code/" + delete_id,
                success: function(response) {
                    if (response.status == 200) {
                        toastr.success('Referral Code deleted successfully');
                        setTimeout(function() {
                            window.location.href = base_url + "/manage-referral-codes";
                        }, 1000);
                    } else {
                        toastr.error("Something went wrong");

                    }
                },
            });
        });


        $(".manage_referral_table").on("change", ".active_referral_code", function() {
            let base_url = url_path;
            var status = $(this).prop("checked") == true ? 1 : 0;
            var referral_id = $(this).data("id");
            $.ajax({
                type: "GET",
                dataType: "json",
                url: base_url + '/change_referral_code_status',
                data: {
                    status: status,
                    referral_id: referral_id,
                },
                success: function(data) {
                    if (status == 1) {
                        toastr.options = {
                            "timeOut": 9000
                        }

                        toastr.success("Referral Code Activated successfully.");
                        setTimeout(function() {
                            window.location.reload();
                        }, 3000);

                    } else {
                        toastr.error("Referral Code  Deactivated successfully.");
                        setTimeout(function() {
                            window.location.reload();
                        }, 3000);

                    }
                },
            });
        });
    </script>
@endsection
