<script>
    function notify(msg="",type="", duration = 3000){        
        $.notify(msg, {
            animate: {
                enter: 'animated bounceInDown',
                exit: 'animated bounceOutUp'
            },
            type: type
        });
	}
    function sweetalert(msg="",type="", duration = 3000){        
        Swal.fire({
            icon: type,
            text: msg,
            timer: duration
        })
	}
</script>
<?php if(!empty($forms) && count($forms) > 0){ ?>
    <?php foreach($forms as $form){ ?>
    <script>
        $(document).ready(function(){
            $("#<?=$form['id'];?>").validate({
                ignore: 'input[type=hidden]',
                errorElement: 'span',
                errorClass: 'invalid-feedback',
                successClass: 'is-valid',
                rules: <?=json_encode($form_rules[$form['id']]);?>,
                errorPlacement: function (error, e) {
                    e.closest('.form-group,.input-group').append(error);
                },
                highlight: function (e, errorClass, validClass) {
                    $(e).removeClass('is-valid').addClass('is-invalid');
                },
                unhighlight: function (e, errorClass, validClass) {
                    $(e).removeClass('is-invalid').addClass('is-valid');
                },
                submitHandler: function (form) {
                    var $btn_submit = $("#_FRM_ADMIN_LOGIN [type='submit']");
                    var before_name = $btn_submit.html();

                    var formdata = new FormData(form);
                    <?php if($form['id'] == 'frm_login'){ ?>
                    // formdata.append('timezone', Intl.DateTimeFormat().resolvedOptions().timeZone);
                    // formdata.append('timezone_offset', new Date().getTimezoneOffset() * 60); // -19800 = reset to utc
                    formdata.append('timezone', 'UTC');
                    formdata.append('timezone_offset', 0); // -19800 = reset to utc
                    <?php } ?>
                    $.ajax({
                        url: '<?=$form_ajax[$form['id']]['ajax_url'];?>',
                        data: formdata,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        dataType: 'JSON',
                        beforeSend: function(){
                            $btn_submit.attr('disabled',true);
                            $btn_submit.html('Loading...');
                            loading('show');

                        },
                        success: function ( response ) {
                            loading('hide');
                            if(response.success){
                                $('#<?=$form['id'];?>')[0].reset();
                                <?php if($form['id'] == 'frm_import'){ ?>
                                    $("#totalRequested").html(response.data.total);
                                    $("#totalInserted").html(response.data.inserted);
                                    $("#totalUpdated").html(response.data.updated);
                                    $("#totalSkipped").html(response.data.skipped);
                                    $("#totalUnchanged").html(response.data.unchanged);
                                    $("#totalErrorWhileInsert").html(response.data.insert_error);
                                    $("#totalErrorWhileUpdate").html(response.data.update_error);
                                    $("#btn-import-stat").show();
                                    $("#import-modal").modal('hide');
                                    $("#import-history-modal").modal('show');
                                    sweetalert(response.message,"success");
                                    table.ajax.reload();
                                <?php }elseif(!empty($form_ajax[$form['id']]['redirect_url'] ?? '')){ ?>
                                    window.location.href = '<?=$form_ajax[$form['id']]['redirect_url'];?>';
                                <?php } ?>
                            }else{
                                sweetalert(response.message,"error");
                                $btn_submit.attr('disabled',false);
                                $btn_submit.html(before_name);
                            }
                        },
                        fail: function(xhr, textStatus, errorThrown){
                            loading('hide');
                            sweetalert('<?=SYSTEM_ERROR;?>',"error");
                            $btn_submit.attr('disabled',false);
                            $btn_submit.html(before_name);
                        },
                        error: function (err) {
                            loading('hide');
                            sweetalert('<?=SYSTEM_ERROR;?>',"error");
                            $btn_submit.attr('disabled',false);
                            $btn_submit.html(before_name);
                        },
                        complete: function () {}
                    });
                }
            });
        });
    </script>
    <?php } ?>
<?php } ?>
<script>
    <?php if ($this->session->flashdata('success') || $this->session->flashdata('error')){ ?>
        <?php if ($this->session->flashdata('success')){ ?>
        notify('<?=$this->session->flashdata("success");?>','success');
        <?php } ?>
        <?php if ($this->session->flashdata('error')){ ?>
        notify('<?=$this->session->flashdata("error");?>','danger');
        <?php } ?>
    <?php } ?>
</script>
<script>
    $.fn.setFormData = function(data){
        let t = this;
        $.each(data, function(key, value) {  
            var ctrl = $(t).find('[name="'+key+'"]');
            if(ctrl.length > 0 && ["password"].indexOf(key) == -1){
                switch(ctrl.prop("type")) { 
                    case "radio":
                    case "checkbox":
                        ctrl.each(function() {
                            // if($(this).attr('value') == value) $(this).attr("checked",value);
                            if (value.indexOf($(this).attr('value')) >= 0) {
                                $(this).attr("checked",value);
                            } else {
                                $(this).attr("checked",false);
                            }
                        });   
                        break; 
                    case "select-one" :
                    case "select-multiple" :
                        ctrl.val(value);
                        ctrl.trigger('change.select2');
                        break;
                    case "file" :
                        let defaultImg = "<?=SITE_URL;?>"+value;
                        var drEvent = ctrl.dropify();
                        drEvent = drEvent.data('dropify');
                        drEvent.resetPreview();
                        drEvent.clearElement();
                        drEvent.settings.defaultFile = defaultImg;
                        drEvent.destroy();
                        drEvent.init();
                        ctrl.dropify({ defaultFile: defaultImg });
                        break;
                    default:
                        ctrl.val(value); 
                }  
            }
        });  
    }

    $(document).ready(function(){
        $('#edit-modal').on('show.bs.modal', function (event) {
            var source = $(event.relatedTarget)
            var primary_id = source.data("id")
            var module = source.data("module")
            $processingTemplate = `<div class="modal-body processing">
                                        <div class="form-row">
                                            <div class="col">
                                                <p><span class="spinner-border spinner-border-sm"></span> Loading... please wait!</p>
                                            </div>
                                        </div>
                                    </div>`;

            var modal = $(this);
            var formdata = new FormData();
            formdata.append("primary_id",primary_id)

            $.ajax({
                url: "<?=ADMIN_AJAX_URL . 'get-';?>" + module + "-details",
                data: formdata,
                processData: false,
                contentType: false,
                type: 'POST',
                dataType: 'JSON',
                beforeSend: function(){
                    modal.find('.modal-body').prop("hidden",true);
                    modal.find('.modal-footer').prop("hidden",true);
                    modal.find('.modal-body').before($processingTemplate);
                },
                success: function ( response ) {
                    modal.find('.modal-body.processing').remove();
                    modal.find('.modal-body').prop("hidden",false);
                    modal.find('.modal-footer').prop("hidden",false);
                    if(response.success){
                        $("#frm_edit").setFormData(response.data.row);
                    }else{
                        sweetalert(response.message,"error");
                        $btn_submit.attr('disabled',false);
                        $btn_submit.html(before_name);
                    }
                },
                fail: function(xhr, textStatus, errorThrown){
                    modal.find('.modal-body.processing').remove();
                    modal.find('.modal-body').prop("hidden",false);
                    modal.find('.modal-footer').prop("hidden",false);
                },
                error: function (err) {
                    modal.find('.modal-body.processing').remove();
                    modal.find('.modal-body').prop("hidden",false);
                    modal.find('.modal-footer').prop("hidden",false);
                },
                complete: function () {}
            });

            
        })
    })

    $(document).ready(function(){
        $('#permission-modal').on('show.bs.modal', function (event) {
            var source = $(event.relatedTarget)
            var primary_id = source.data("id")
            var module = source.data("module")
            $processingTemplate = `<div class="modal-body processing">
                                        <div class="form-row">
                                            <div class="col">
                                                <p><span class="spinner-border spinner-border-sm"></span> Loading... please wait!</p>
                                            </div>
                                        </div>
                                    </div>`;

            var modal = $(this);
            var formdata = new FormData();
            formdata.append("primary_id",primary_id)

            $.ajax({
                url: "<?=ADMIN_AJAX_URL . 'get-';?>" + module + "-permissions",
                data: formdata,
                processData: false,
                contentType: false,
                type: 'POST',
                dataType: 'JSON',
                beforeSend: function(){
                    modal.find('.modal-body').prop("hidden",true);
                    modal.find('.modal-footer').prop("hidden",true);
                    modal.find('.modal-body').before($processingTemplate);
                },
                success: function ( response ) {
                    modal.find('.modal-body.processing').remove();
                    modal.find('.modal-body').prop("hidden",false);
                    modal.find('.modal-footer').prop("hidden",false);
                    if(response.success){
                        $("#frm_permission").setFormData(response.data.row);
                        $('[name="permissions[]"]').trigger("change");
                    }else{
                        sweetalert(response.message,"error");
                        $btn_submit.attr('disabled',false);
                        $btn_submit.html(before_name);
                    }
                },
                fail: function(xhr, textStatus, errorThrown){
                    modal.find('.modal-body.processing').remove();
                    modal.find('.modal-body').prop("hidden",false);
                    modal.find('.modal-footer').prop("hidden",false);
                },
                error: function (err) {
                    modal.find('.modal-body.processing').remove();
                    modal.find('.modal-body').prop("hidden",false);
                    modal.find('.modal-footer').prop("hidden",false);
                },
                complete: function () {}
            });

            
        })
    })
</script>