<br>
<div class="form-group">

    <!----------------- TAB ----------------->
    <ul class="nav navtab-pills" id="pills-tab" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="navtab-link active" id="pills-personal-tab" data-bs-toggle="pill"
                data-bs-target="#pills-personal" type="button" role="tab" aria-controls="pills-personal"
                aria-selected="true"><i class="fas fa-user-alt"></i>
                ข้อมูลหมวดหมู่
            </button>
        </li>
    </ul>
    <!----------------- Content Tab ----------------->
    <div class="tab-content" id="pills-tabContent">
        <div class="tab-pane fade show active" id="pills-personal" role="tabpanel" aria-labelledby="pills-personal-tab">
            <div class="borders-green">
                <div class="container" style="padding-top: 1rem">
                    <!----------------- data ----------------->
                    <form id="formAddCat" name="formAddCat">
                        <div class="row justify-content-md-center">
                            <div class="col-8">
                                <?php if($type['status'] == true): ?>
                                <input type="hidden" id="type_id" value="<?php echo e($type['data']['id']); ?>">
                                <input type="hidden" id="type_idstatus" value="<?php echo e($type['data']['status']); ?>">
                                <input type="hidden" id="sub_level" value="<?php echo e($type['data']['sub_level']); ?>">
                                <input type="hidden" id="old_cover" value="<?php echo e($type['data']['cover']); ?>">

                                <?php
                                $arr = array();
                                foreach ($type['data']['sub'] as $item) {
                                    if($item['id'] != ''){
                                        array_push($arr, $item['id']);
                                    }                                    
                                }
                                $json_arr = json_encode($arr);
                                ?>
                                <input type="hidden" id="type_idsub" value="<?php echo e($json_arr); ?>">

                                <?php else: ?>
                                <input type="hidden" id="type_id" value="">
                                <?php endif; ?>

                                <div class="mb-3">
                                    <label class="form-label">ชื่อหมวดหมู่</label>
                                    <?php if($type['status'] == true): ?>
                                    <input id="type_name" name="type_name" type="text" class="form-control"
                                        value="<?php echo e($type['data']['name']); ?>">
                                    <?php else: ?>
                                    <input id="type_name" name="type_name" type="text" class="form-control">
                                    <?php endif; ?>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">หมวดหมู่ระดับที่ 0</label>
                                    <?php if($type['status'] == true): ?>
                                    <?php if($type['data']['sub_level'] != 0): ?>
                                    <select id="type_cat0" name="type_cat0" class="form-select">
                                        <option value="" selected>เลือกหมวดหมู่</option>
                                        <?php if($mastertype['status'] == true): ?>
                                        <?php $__currentLoopData = $mastertype['data']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $master): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($master['id']); ?>"><?php echo e($master['name']); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        <?php endif; ?>
                                    </select>
                                    <?php else: ?>
                                    <select id="type_cat0" name="type_cat0" class="form-select" disabled>
                                        <option value="" selected>เลือกหมวดหมู่</option>
                                    </select>
                                    <?php endif; ?>
                                    <?php else: ?>
                                    <select id="type_cat0" name="type_cat0" class="form-select">
                                        <option value="" selected>เลือกหมวดหมู่</option>
                                        <?php if($mastertype['status'] == true): ?>
                                        <?php $__currentLoopData = $mastertype['data']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $master): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($master['id']); ?>"><?php echo e($master['name']); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        <?php endif; ?>
                                    </select>
                                    <?php endif; ?>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">หมวดหมู่ระดับที่ 1</label>
                                    <select id="type_cat1" name="type_cat1" class="form-select" disabled>
                                        <option value="" selected>เลือกหมวดหมู่</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">หมวดหมู่ระดับที่ 2</label>
                                    <select id="type_cat2" name="type_cat2" class="form-select" disabled>
                                        <option value="" selected>เลือกหมวดหมู่</option>
                                    </select>
                                </div>
                                <div class="mb-3 text-center">
                                    <?php if($type['status'] == true): ?>

                                    <?php if($type['data']['sub_level'] != 0): ?>

                                    <?php if($type['data']['cover'] != ''): ?>
                                    <img id="type_pic" name="type_pic" class="img-thumbnail" width="250px" hight="250px"
                                        src="<?php echo e(asset('../storage/km/icon/'.$type['data']['cover'])); ?>">
                                    <?php else: ?>
                                    <img id="type_pic" name="type_pic" class="img-thumbnail" width="250px" hight="250px"
                                        src="<?php echo e(asset('../storage/km/icon/default.png')); ?>">
                                    <?php endif; ?>
                                    <p style="font-size: 14px;color:Gray;">(ภาพขนาด 422 x 423 px)</p>

                                    <?php else: ?>

                                    <?php if($type['data']['cover'] != ''): ?>
                                    <img id="type_pic" name="type_pic" class="img-thumbnail" hight="250px"
                                        src="<?php echo e(asset('../storage/km/banner/'.$type['data']['cover'])); ?>">
                                    <?php else: ?>
                                    <img id="type_pic" name="type_pic" class="img-thumbnail" hight="300px"
                                        src="<?php echo e(asset('../storage/km/banner/default.jpg')); ?>">
                                    <?php endif; ?>
                                    <p style="font-size: 14px;color:Gray;">(ภาพขนาด 2500 x 375 px)</p>

                                    <?php endif; ?>

                                    <?php else: ?>
                                    <img id="type_pic" name="type_pic" class="img-thumbnail" width="250px" hight="250px"
                                        src="<?php echo e(asset('../storage/km/icon/default.png')); ?>">
                                    <p style="font-size: 14px;color:Gray;">(ภาพขนาด 422 x 423 px)</p>

                                    <?php endif; ?>
                                </div>
                                <div class="mb-3">
                                    <input id="type_img" name="type_img" class="form-control" type="file">
                                </div>
                                <?php if($type['status'] == true): ?>
                                <?php if($type['data']['sub_level'] == 0): ?>
                                <div class="mb-3">
                                    <label class="form-label">ไอคอน
                                        <a target="_blank" href="fontawesome">
                                            รายการไอคอน Font Awesome 5 ทั้งหมด
                                        </a>
                                    </label>
                                    <input id="type_icon" name="type_icon" type="text" class="form-control"
                                        value="<?php echo e($type['data']['icon']); ?>">
                                </div>
                                <?php endif; ?>
                                <?php endif; ?>
                                <div class="mb-3">
                                    <label class="form-label">สถานะการใช้งาน</label>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="type_status" value="1">
                                        <label class="form-check-label">ยังใช้งาน</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="type_status" value="2">
                                        <label class="form-check-label">เลิกใช้งาน</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row justify-content-md-center">
                            <div class="col-8">
                                <div class="mb-3">
                                    <div class="row justify-content-md-center">
                                        <div class="col-lg-10"></div>
                                        <div class="d-grid gap-2 col-lg-2 mx-auto">
                                            <button class="btn btn-warning" type="submit">
                                                บันทึก <i class="fas fa-save"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    $("select").select2({
        theme: "bootstrap-5",
    }).change(function() {
        $(this).valid();
    });

    var type_id = $("#type_id").val();
    if (type_id != "") {
        var type_idsub = $("#type_idsub").val();
        var arr_sub = jQuery.parseJSON(type_idsub);
        var len = arr_sub.length;
        // alert(len);

        for (let i = 0; i < arr_sub.length; i++) {
            // debugger;
            len = len - 1;
            // alert(i + '/' + arr_sub[len]);
            $("#type_cat" + i).val(arr_sub[len]).change();

            $("#type_cat" + i).prop('disabled', false);
            $("#type_cat" + i).change();
        }
        // $.each(arr_sub, function(index, value) {
        //     $("#type_cat" + len).val(value).change();

        //     len = len - 1;
        // });
        var type_idstatus = $("#type_idstatus").val();
        $('input:radio[name="type_status"]').filter('[value=' + type_idstatus + ']').attr('checked', true);
    }
});

$('#type_cat0').on('change', function() {
    var sub_level = this.value;
    if (sub_level == '') {
        clearCON('1');
        clearCON('2');
    }else{
        $(".loader").show();
        var form_data = new FormData();
        form_data.append('sub_level', sub_level);
        $.ajax({
            type: "post",
            url: 'categoryManagement/masterGroup',
            data: form_data,
            async: false,
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            processData: false,
            contentType: false,
            cache: false,
            success: function(result) {
                $(".loader").hide();
                if (result.status == true) {
                    $('#type_cat1')
                        .empty()
                        .append(
                            '<option value="" selected>เลือกหมวดหมู่</option>');

                    var arr = result.data['data'];
                    $.each(arr, function(index) {
                        var id = arr[index]['id'];
                        var name = arr[index]['name'];

                        $('#type_cat1').append('<option value="' + id + '">' + name +
                            '</option>');
                    });
                    $('#type_cat1').prop('disabled', false);
                    clearCON('2');
                } else {
                    clearCON('1');
                    clearCON('2');
                }
            }
        });
    }
    
});

$('#type_cat1').on('change', function() {
    var sub_level = this.value;
    if (sub_level == '') {
        clearCON('2');
    }else{
        $(".loader").show();
        var form_data = new FormData();
        form_data.append('sub_level', sub_level);
        $.ajax({
            type: "post",
            url: 'categoryManagement/masterGroup',
            data: form_data,
            async: false,
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            processData: false,
            contentType: false,
            cache: false,
            success: function(result) {
                $(".loader").hide();
                if (result.status == true) {
                    $('#type_cat2')
                        .empty()
                        .append(
                            '<option value="" selected>เลือกหมวดหมู่</option>');
                    var arr = result.data['data'];
                    $.each(arr, function(index) {
                        var id = arr[index]['id'];
                        var name = arr[index]['name'];

                        $('#type_cat2').append('<option value="' + id + '">' + name +
                            '</option>');                        
                    });
                    $('#type_cat2').prop('disabled', false);
                } else {
                    clearCON('2');
                }
            }
        });
    }
    
});

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function(e) {
            $('#type_pic').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

var _URL = window.URL || window.webkitURL;
$("#type_img").change(function() {
    var file, img;
    var sub = $("#sub_level").val();

    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function() {
            // alert((this.width == 2500) && (this.height == 730));
            if (sub == 0) {
                if (!((this.width == 2500) && (this.height == 375))) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'คำเตือน',
                        text: 'กรุณาใช้ภาพขนาด 2500 x 375 px',
                    });
                    $("#type_img").val("");
                    $('#type_pic').attr("src", "<?php echo e(asset('../storage/km/banner/default.jpg')); ?>");
                    return false;
                }
            } else {
                if (!((this.width == 422) && (this.height == 423))) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'คำเตือน',
                        text: 'กรุณาใช้ภาพขนาด 422 x 423 px',
                    });
                    $("#type_img").val("");
                    $('#type_pic').attr("src", "<?php echo e(asset('../storage/km/icon/default.png')); ?>");
                    return false;
                }
            }
        };
        img.onerror = function() {
            Swal.fire({
                icon: 'warning',
                title: 'คำเตือน',
                text: "กรุณาอัพโหลดไฟล์ภาพ (jpg, png) เนื่องจากเป็นไฟล์ประเภท" + file.type,
            });
        };
        img.src = _URL.createObjectURL(file);
        readURL(this);
    }
});

jQuery.validator.addMethod('update_rule', function(value, element) {
    var type_id = $("#type_id").val();
    if (type_id != "") {
        return true;
    } else {
        return false;
    };
});

jQuery.validator.addMethod('option_tag1', function(value, element) {
    var num = $('#type_cat1 option').length;
    var cat = $('#type_cat1').val();
    if (num > 1) {
        if (cat == "") {
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
});

jQuery.validator.addMethod('option_tag2', function(value, element) {
    var num = $('#type_cat2 option').length;
    var cat = $('#type_cat2').val();
    if (num > 1) {
        if (cat == "") {
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
});

var $savecat = $("#formAddCat");
$savecat.validate({
    rules: {
        type_name: {
            required: true,
        },
        type_cat0: {
            required: true,
        },
        // type_cat1: {
        //     option_tag1: true,
        // },
        // type_cat2: {
        //     option_tag2: true,
        // },
        // type_img: {
        //     update_rule: true,
        // },
        type_status: {
            required: true,
        }
    },
    messages: {
        type_name: {
            required: "กรุณากรอกชื่อหมวดหมู่",
        },
        type_cat0: {
            required: "กรุณากรอกหมวดหมู่ระดับที่ 0",
        },
        // type_cat1: {
        //     required: "กรุณากรอกหมวดหมู่ระดับที่ 1",
        // },
        // type_cat2: {
        //     required: "กรุณากรอกหมวดหมู่ระดับที่ 1",
        // },
        // type_img: {
        //     update_rule: "กรุณาเลือกไฟล์",
        // },
        type_status: {
            required: "กรุณาเลือกสถานะการใช้งาน",
        }
    },
    submitHandler: function() {
        // $(".loader").show();
        var type_id = $("#type_id").val();
        var type_name = $("#type_name").val();

        var arrType = [];
        var type_cat0 = $("#type_cat0").val();
        if (type_cat0 != '') {
            arrType.push(type_cat0);
        }
        var type_cat1 = $("#type_cat1").val();
        if (type_cat1 != '') {
            arrType.push(type_cat1);
        }
        var type_cat2 = $("#type_cat2").val();
        if (type_cat2 != '') {
            arrType.push(type_cat2);
        }
        var type_json = JSON.stringify(arrType);

        var type_img = $('#type_img').prop('files')[0];
        var type_status = $('input[name="type_status"]:checked').val();

        var old_cover = $("#old_cover").val();

        if (type_id == '') {
            // add
            var form_data = new FormData();
            form_data.append('type_name', type_name);
            form_data.append('type_json', type_json);
            form_data.append('type_img', type_img);
            form_data.append('type_status', type_status);

            $.ajax({
                type: "post",
                url: 'categoryManagement/add',
                data: form_data,
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                processData: false,
                contentType: false,
                cache: false,
                success: function(data) {
                    // $(".loader").hide();
                    // console.log(data.status);
                    if (data.status == true) {
                        Swal.fire({
                            icon: 'success',
                            title: data.message,
                            text: '',
                            allowOutsideClick: false,
                            focusConfirm: true,
                            confirmButtonText: 'ตกลง',
                        }).then((result) => {
                            if (result.value) {
                                $(".loader").show();
                                window.location = "categoryManagement";
                            }
                        })
                        return false;

                    } else {
                        Swal.fire({
                            icon: 'warning',
                            title: 'คำเตือน',
                            text: JSON.stringify(data.message),
                        });
                        return false;
                    }
                },
            });
        } else {
            // update
            var sub_level = $("#sub_level").val();

            var form_data = new FormData();
            form_data.append('type_name', type_name);
            if (arrType != "") {
                form_data.append('type_json', type_json);
            }
            if (type_img != null) {
                form_data.append('type_img', type_img);
            }
            form_data.append('type_status', type_status);
            form_data.append('sub_level', sub_level);

            if (sub_level == 0) {
                var type_icon = $("#type_icon").val();
                form_data.append('type_icon', type_icon);
            }

            form_data.append('old_cover', old_cover);

            $.ajax({
                type: "post",
                url: 'categoryManagement/update/' + type_id,
                data: form_data,
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                processData: false,
                contentType: false,
                cache: false,
                success: function(data) {
                    $(".loader").hide();
                    if (data.status == true) {
                        // location.reload();
                        Swal.fire({
                            icon: 'success',
                            title: data.message,
                            text: '',
                            allowOutsideClick: false,
                            focusConfirm: true,
                            confirmButtonText: 'ตกลง',
                        }).then((result) => {
                            if (result.value) {
                                $(".loader").show();
                                window.location = "categoryManagement";
                            }
                        })
                        return false;
                    } else {
                        Swal.fire({
                            icon: 'warning',
                            title: 'คำเตือน',
                            text: JSON.stringify(data.message),
                        });
                        return false;
                    }
                },
            });
        }
    },
    errorElement: "div",
    errorPlacement: function(error, element) {
        // console.log("errorPlacement // "+element[0].id);
        error.addClass("invalid-feedback");

        if (element.prop("type") === "checkbox") {
            error.insertAfter(element).addClass("invalid-feedback");
        } else {
            error.insertAfter(element);
        }

        var elem = $(element);
        if (elem.hasClass("select2-hidden-accessible")) {
            element = $("#select2-" + elem.attr("id") + "-container").parent();
            error.insertAfter(element).addClass("invalid-feedback");
        } else {
            error.insertAfter(element);
        }

        if (!element.next("span")[0]) {
            $("<span class='glyphicon glyphicon-remove form-control-feedback'></span>")
            .insertAfter(element);
        }

        if (element.parent().hasClass('input-group')) {
            error.insertAfter(element.parent()).addClass("invalid-feedback");
        } else {
            error.insertAfter(element).addClass("invalid-feedback");
        }
    },
    success: function(label, element) {     
        // console.log("success // "+element.id);   
        var elem = $(element);
        elem.removeClass("is-invalid");
        elem.addClass("is-valid");
    },
    highlight: function(element, errorClass, validClass) {
        var elem = $(element);
        elem.addClass("is-invalid");
        // console.log("highlight // "+element.outerHTML);
    },
    unhighlight: function(element, errorClass, validClass) {
        // console.log("unhighlight // "+element.id);
        var elem = $(element);
        elem.removeClass("is-invalid");
    }
});

function clearCON(id){
    $("#con_cat"+id).val('').change();
    $("#con_cat"+id).prop('disabled', true);
    $tex = $("#con_cat"+id).val();
    if ($tex == '') {
        $("#con_cat"+id).removeClass("is-invalid");
        $('#con_cat'+id+'-error').remove();
    }
}
</script><?php /**PATH C:\xampp\htdocs\km-web\resources\views/subpageBack/add_category.blade.php ENDPATH**/ ?>