@extends('layouts.admin')
@section('content')
<div class="row">
    <div class="col-12">
        <div class="page-title-box d-sm-flex align-items-center justify-content-between bg-galaxy-transparent">
            <h4 class="mb-sm-0">{{ (!empty($notification->id)) ? 'Update Notification' : 'Create Notification' }}</h4>

            <div class="page-title-right">
                <ol class="breadcrumb m-0">
                    <li class="breadcrumb-item"><a href="javascript: void(0);">Home</a></li>
                    <li class="breadcrumb-item"><a href="javascript: void(0);">Notification</a></li>
                    <li class="breadcrumb-item active">{{ (!empty($notification->id)) ? 'Update Notification' : 'Create Notification' }}</li>
                </ol>
            </div>
        </div>
    </div>
</div> 
<!-- end page title -->

<div class="row">
    <div class="col-lg-12">
        <div class="card" id="orderList">
            <div class="card-body">
                <form class="tablelist-form {{ !empty($notification->id) ? 'edit-form' : '' }}" autocomplete="off" name="countryForm" id="countryForm" method="post" novalidate enctype="multipart/form-data" action="{{ route('admin.notifications.submit') }}">
                    @csrf
                    <input type="hidden" name="id" id="id" value="{{ (!empty($notification->id)) ? $notification->id : '' }}" />
                    <div class="row">
                        <div class="col-lg-12 mb-3">
                            <label for="customername-field" class="form-label">Title</label>
                            <input type="text" id="title" name="title" class="form-control" placeholder="Enter Notification Title" required value="{{ (!empty($notification->title)) ? $notification->name : '' }}" />
                        </div>
                        <div class="col-lg-12 mb-3">
                            <label class="form-label">Title (Arabic)</label>
                            <input type="text" name="title_ar" style="text-align: right;" class="form-control" value="{{ (!empty($notification->title_ar)) ? $notification->title_ar : '' }}"  required  placeholder="أدخل عنوان الإشعار">
                        </div>
                        <div class="col-lg-12 mb-3">
                            <label for="customername-field" class="form-label">Content</label>
                            <textarea id="content" name="content" class="form-control" placeholder="Enter Notification Content" required>{{ (!empty($notification->content)) ? $notification->content : '' }}</textarea>
                        </div>
                        <div class="col-lg-12 mb-3">
                            <label class="form-label">Content (Arabic)</label>
                            <textarea name="content_ar" id="content_ar" style="text-align: right;" class="form-control"  placeholder="أدخل محتوى الإشعار" required  >{{ (!empty($notification->content_ar)) ? $notification->content_ar : '' }}</textarea>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="image" class="form-label">Image</label>
                            <input type="file" id="icon" name="image"  class="form-control icon-image-field" accept="image/jpeg, image/jpg, image/png" />
                        </div>
                        <div class="col-lg-4 mb-3">
                            <img src="{{ !empty($notification->image) ? $notification->image : asset('assets/images/camera_placeholder.png') }}" class="img-fluid icon-image-preview" alt="icon" style="height: 100px; width: 100px;">
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="customername-field" class="form-label">Status</label> 
                            <select class="form-select js-example-basic-single status-select"  id="status" name="status">
                                <option value=""></option>
                                <option value="1" {{ (!empty($notification->id) && $notification->status == 1) ? 'selected' : '' }}>Active</option>
                                <option value="0" {{ (!empty($notification->id) && $notification->status == 0) ? 'selected' : '' }}>Inactive</option>
                            </select>
                        </div>
                    </div>

                    <div id="NotificationModal" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
                                <div class="modal-dialog modal-lg">
                                        <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title" id="exampleModalLabel">Select users to send notification</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="col-lg-4 mb-3">
                                            <label for="customername-field" class="form-label">Name</label>
                                            <input type="text" id="selectSearch" class="form-control" placeholder="Search"  />
                                        </div>
                                            <table class="table table-striped table-hover mt-3" id = "">
                                                <thead>
                                                    <tr>
                                                    <th>
                                                        <span class="custom-checkbox">
                                                            <input type="checkbox"  id="check-all">
                                                            <label for="selectAll"></label>
                                                        </span>
                                                    </th>
                                                    <th>Name</th>
                                                    <th>Email</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="tableData">

                                                    @foreach($users as $user)
                                                        <tr>
                                                            <td>
                                                                <span class="custom-checkbox">
                                                                    <input type="checkbox"  name="options[]" value="{{ $user->id }}" class = "select-customers">
                                                                    <label for="checkbox1"></label>
                                                                </span>
                                                            </td>
                                                            <td>{{$user->name}}</td>
                                                            <td>{{$user->email}}</td>
                                                        </tr>
                                                    @endforeach
                                                </tbody>




                                                <!-- <tbody id="tableData">
                                                </tbody> -->

                                                
                                            </table>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-back" data-dismiss="modal">Close</button>
                                            <button type="submit" class="btn btn-success btn-hover" id = "assign" disabled >Push</button>
                                        </div>
                                        </div>
                                    </div>
                                </div>

                    <div class="hstack gap-2 justify-content-between">
                    <a href="{{ route('admin.notifications') }}" class="btn btn-success">Back</a>
                    <button type="button" class="btn btn-success notification-modal-btn"  data-toggle="modal" data-target="#NotificationModal">Create Notification</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div> 

@endsection
@section('script')
    <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/jquery.validate.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/additional-methods.min.js"></script>
    <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $(document).on('click','.notification-modal-btn',function(){
                $('#NotificationModal').modal('show');
            })
            $('.icon-image-field').change(function() {
                var file = this.files[0];
                var fileType = file.type;
                var validImageTypes = ['image/png', 'image/jpeg', 'image/png'];

                if (validImageTypes.includes(fileType)) {
                    var reader = new FileReader();

                    reader.onload = function(event) {
                        $('.icon-image-preview').attr('src',event.target.result);
                    }

                    reader.readAsDataURL(file);
                }
            });

        $("#selectSearch").keyup(function(){
            var search = $(this).val();
            var option = $('#selectOption').val();

            $.ajax({
                    method: 'get',
                    url:'{{ route("admin.getSearchUserList")}}',
                    data:{"_token": "{{ csrf_token() }}",
                    search:search , option:option},
                    success:function(data){
                        $('#tableData').html(data);
                        $('#check-all').prop('checked', false);
                        
                    }
                }); 
            });


        $(document).on('change', '.icon-image-field', function () {
                $('#submitBtn').prop('disabled', false);
            });


        $.validator.addMethod("countryCoderule", function (value, element) {
            return this.optional(element) || /^\+\d{1,5}$/.test(value);  // Modify regex as needed
        }, "Please enter a valid country code (e.g., +1, +91).");

        
            $("#countryForm").validate({
                rules: {
                    name: {
                        required: true,
                        minlength: 3,
                    },
                    status: {
                        required: true,
                    },
                },
                messages: {
                    name: {
                        required: "Please enter the Notification name.",
                        minlength: "Company name must be at least 3 characters.",
                    },

                    status: {
                        required: "Please select the status.",
                    },
                    
                },
                onkeyup: function (element) {
                    $(element).valid(); // Real-time validation on keyup
                },
                onfocusout: function (element) {
                    $(element).valid(); // Validate when focus is lost
                },
                errorPlacement: function (error, element) {
                    if (element.is("select")) {
                        error.insertAfter(element.next('.select2')); 
                    } else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: function (form) {
                    let formData = new FormData(form);

                    // AJAX submission
                    $.ajax({
                        url: form.action,
                        type: "POST",
                        data: formData,
                        processData: false,
                        contentType: false,
                        headers: {
                            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
                        },
                        success: function (response) { 

                            Swal.fire({
                                iconHtml: `<img src="{{ asset('assets/images/success-circle.svg') }}" class="img-fluid">`,
                               // title: "Success!",
                                text: response.message,
                                confirmButtonText: "OK",
                                customClass: {
                                    confirmButton: 'custom-ok-button-class w-sm' // Add your custom class here
                                }
                            }).then(() => {
                                window.location.href = "{{ route('admin.notifications') }}"; // Redirect to company list
                            });
                            // Show success message with Swal
                           
                        },
                        error: function (xhr) {
                            if (xhr.status === 422) {
                                let errors = xhr.responseJSON.errors;

                                // Display validation errors from the server
                                $.each(errors, function (key, value) {
                                    let field = $(`[name="${key}"]`);
                                    field.addClass("error"); // Add error class to the field
                                    field.after(`<label class="error">${value[0]}</label>`); // Add error message
                                });
                            } else {
                                Swal.fire({
                                    text: "Something went wrong. Please try later",
                                    iconHtml: `<img src="{{ asset('assets/images/error-circle.svg') }}" class="img-fluid">`,
                                    confirmButtonText: "OK", // Optional: Change the text of the button
                                    customClass: {
                                        confirmButton: 'custom-ok-button-class w-sm' // Add your custom class here
                                    }
                                });
                            }
                        }
                    });

                    return false; // Prevent default form submission
                },
                invalidHandler: function(event, validator) {
                    var firstInvalidField = $(validator.errorList[0].element);
                    
                    $('html, body').animate({
                        scrollTop: firstInvalidField.offset().top - 100 
                    }, 500); 
                }
            });

            $(document).on('click','#check-all',function(){
    
                let checkboxes = $('.select-customers'); 
                let totalCheckboxes = checkboxes.length; 
                
                if ($(this).is(':checked')) {
                    checkboxes.prop('checked', true);
                } else {
                checkboxes.prop('checked', false); 
                }
                
                var checkedCount = checkboxes.filter(':checked').length;

                if (checkedCount > 0) {
                $('#assign').prop('disabled', false);
                } else {
                $('#assign').prop('disabled', true);
                }
                if (checkedCount > totalCheckboxes) {
                checkboxes.filter(':checked').slice(totalCheckboxes).prop('checked', false);
                }

                console.log('total='+totalCheckboxes);
                console.log('checked='+checkedCount);

            });

            $(document).on('click', '.select-customers', function() {
                let totalCheckboxes = $('.select-customers').length;
                let numberOfChecked = $('.select-customers').filter(':checked').length;
                // Selected checkboxes ki ginti, load hone wali checkboxes ki sankhya ke barabar hai
                
                // Selected checkboxes ki ginti, load hone wali checkboxes ki sankhya se zyada hai toh additional checkboxes ko deselect karein
                if (numberOfChecked > totalCheckboxes) {
                $('.select-customers').filter(':checked').slice(totalCheckboxes).prop('checked', false);
                }

                if (numberOfChecked > 0) {
                $('#assign').prop('disabled', false);
                } else {
                $('#assign').prop('disabled', true);
                }

                if (totalCheckboxes == numberOfChecked) {
                $('#check-all').prop('checked', true);
                } else {
                $('#check-all').prop('checked', false);
                }
            });
        });
    </script>
    
@endsection
