<div class="d-grid gap-2 col-6 mx-auto">
    <button type="submit" class="btn btn-block btn-info" id="btn_info">
        เพิ่มภาพอินโฟกราฟิก <i class="fas fa-plus-circle"></i>
    </button>
</div>
<br>
<div class="table-responsive">
    <table id="table-info" class="table">
        <thead>
            <tr class="bg-green">
                <th>ลำดับ</th>
                <th>ชื่อไฟล์</th>
                <th>จำนวนดาวน์โหลด</th>
                <th>วันที่</th>
                <th>id</th>
                <th>จัดการ</th>
            </tr>
        </thead>
        <tbody>
            <?php if($article['status'] == true): ?>
            <?php if(count($article['data']['file']) > 0): ?>
            <?php $__currentLoopData = $article['data']['file']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $info): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            <?php if($info['type'] == 1): ?>
            <tr>
                <td width="5%"></td>
                <td width="40%"><?php echo e($info['name']); ?></td>
                <td width="20%"><?php echo e($info['download_count']); ?></td>
                <td width="20%"><?php echo e(formatDateThaiFull($info['created_at'])); ?></td>
                <td width="5%"><?php echo e($info['id']); ?></td>
                <td width="10%"></td>
            </tr>
            <?php endif; ?>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            <?php endif; ?>
            <?php endif; ?>
        </tbody>
    </table>
</div>
<br>

<!-- ADD Modal -->
<div class="modal" id="AddModalInfo" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">เพิ่มภาพอินโฟกราฟิก</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="formAddInfo" name="formAddInfo" class="needs-validation" novalidate>
                    <div class="row justify-content-md-center">
                        <div class="col">
                            <div class="mb-3">
                                <div class="mb-3">
                                    <img id="info_pic" name="info_pic" class="img-thumbnail"
                                        src="<?php echo e(asset('../storage/km/cover/default.jpg')); ?>">
                                    <p style="font-size: 12px;color:Gray;text-align: center;">(ภาพขนาด 2480x3508 px และไม่เกิน 3 MB)</p>
                                </div>
                                <div class="mb-3">
                                    <input id="info_img" name="info_img" class="form-control" type="file"
                                        accept="image/png, image/jpeg">
                                </div>
                            </div>
                            <div class="mb-3">
                                <div class="col-md-10"></div>
                                <div class="d-grid gap-2 col-md-2 mx-auto">
                                    <button class="btn btn-warning" type="submit">
                                        บันทึก <i class="fas fa-save"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>

            </div>
        </div>
    </div>
</div>

<script>
$("#btn_info").click(function() {
    $("#AddModalInfo").modal('show');
});

function readURLinfo(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('#info_pic').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

var _URL = window.URL || window.webkitURL;
$("#info_img").change(function() {
    var file, img, fileType, fsize;
    file = this.files[0];
    fileType = file['type'];
    validImageTypes = ['image/jpeg', 'image/png'];
    fsize = file.size;
    size = Math.round((fsize / 1024));
    console.log(validImageTypes.includes(fileType));
    if (validImageTypes.includes(fileType)) {
        img = new Image();
        img.onload = function() {
            // alert((this.width == 2500) && (this.height == 730));
            if (!((this.width == 2480) && (this.height == 3508))) {
                Swal.fire({
                    icon: 'warning',
                    title: 'คำเตือน',
                    text: 'กรุณาใช้ภาพขนาด 2480 x 3508 px',
                });
                $("#info_img").val("");
                $('#info_pic').attr("src", "<?php echo e(asset('../storage/km/cover/default.jpg')); ?>");
                return false;
            } else {
                if (size > 3072) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'คำเตือน',
                        text: 'กรุณาใช้ภาพขนาดไม่เกิน 3 MB',
                    });
                    $("#info_img").val("");
                    $('#info_pic').attr("src", "<?php echo e(asset('../storage/km/cover/default.jpg')); ?>");
                    return false;
                }
            }
        };
        img.onerror = function() {
            $("#info_img").val("");
            Swal.fire({
                icon: 'warning',
                title: 'คำเตือน',
                text: "กรุณาอัพโหลดไฟล์ภาพ (jpg, png) เนื่องจากเป็นไฟล์ประเภท" + file.type,
            });
        };
        img.src = _URL.createObjectURL(file);
        readURLinfo(this);
    } else {
        $("#info_img").val("");
        Swal.fire({
            icon: 'warning',
            title: 'คำเตือน',
            text: "กรุณาอัพโหลดไฟล์ภาพ (jpg, png)",
        });
    }

});

var tableInfo = $('#table-info').DataTable({
    "columnDefs": [{
            "targets": 0,
            "searchable": false,
            "orderable": false,
            "width": "5%",
            "className": "text-center",
        },
        {
            "targets": 4,
            "visible": false,
            "searchable": false
        },
        {
            "targets": -1,
            "data": null,
            "className": "text-center",
            "defaultContent": "<a class='on-default btn-delete' id='btn-delete' data-toggle='tooltip' title='ลบ'><i class='fa fa-trash-alt'></i></a>"
        }
    ],
    "order": [
        [0, 'asc']
    ],
    "autoWidth": false,
    "searching": false,
    "destroy": false,
    "paging": true,
    "info": true,
    "responsive": true,
    "orderable": false
});

tableInfo.on('order.dt search.dt', function() {
    tableInfo.column(0, {
        search: 'applied',
        order: 'applied'
    }).nodes().each(function(cell, i) {
        cell.innerHTML = i + 1;
    });
}).draw();


$('#table-info tbody').on('click', '.btn-delete', function() {
    var RowIndex = $(this).closest('tr');
    var data = tableInfo.row(RowIndex).data();
    // var data = tableInfo.row( this ).data();
    var idinfo = data[4];
    var nameold = data[1];
    var idArt = $("#con_id").val();
    Swal.fire({
        icon: 'info',
        title: 'คุณแน่ใจแล้วใช่ไหมว่าจะลบข้อมูลที่เลือก',
        text: '',
        allowOutsideClick: false,
        focusConfirm: true,
        showCancelButton: true,
        confirmButtonText: 'ตกลง',
        cancelButtonText: 'ยกเลิก',
    }).then((result) => {
        if (result.value) {
            var form_data = new FormData();
            form_data.append('art_id', idArt);
            form_data.append('type', 1);
            form_data.append('name_old', nameold);
            $.ajax({
                type: "post",
                url: 'content/deleteFile/' + idinfo,
                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) {
                        $('#blade-info').html(data.body);
                    } else {
                        Swal.fire({
                            icon: 'warning',
                            title: 'คำเตือน',
                            text: JSON.stringify(data.message),
                        });
                    }
                },
            });
        }
    })
});

var $saveinfo = $("#formAddInfo");
$saveinfo.validate({
    rules: {
        info_img: {
            required: true
        }
    },
    messages: {
        info_img: {
            required: "กรุณาเลือกภาพอินโฟกราฟิก"
        }
    },
    submitHandler: function() {
        $(".loader").show();
        var idArt = $("#con_id").val();
        var info_img = $('#info_img').prop('files')[0];

        if (idArt == "") {
            $(".loader").hide();
            Swal.fire({
                icon: 'warning',
                title: 'คำเตือน',
                text: 'กรุณาเพิ่มข้อมูลเนื้อหาความรู้ก่อน',
            });
        } else {
            var form_data = new FormData();
            form_data.append('art_id', idArt);
            form_data.append('input_file', info_img);
            form_data.append('type', '1');

            $.ajax({
                type: "post",
                url: 'content/addFile',
                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) {
                        $('#AddModalInfo').modal('hide');
                        $('#blade-info').html(data.body);
                    } else {
                        Swal.fire({
                            icon: 'warning',
                            title: 'คำเตือน',
                            text: JSON.stringify(data.message),
                        });
                    }
                },
            });
        }
    },
    errorElement: "div",
    errorPlacement: function(error, element) {
        // Add the `invalid-feedback` class to the error element
        error.addClass("invalid-feedback");

        // Add `has-feedback` class to the parent div.form-group
        // in order to add icons to inputs
        // element.parents(".col-sm-5").addClass("has-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);
        }

        // Add the span element, if doesn't exists, and apply the icon classes to it.
        if (!element.next("span")[0]) {
            $("<span class='glyphicon glyphicon-remove form-control-feedback'></span>")
                .insertAfter(element);
        }
    },
    success: function(label, element) {
        // Add the span element, if doesn't exists, and apply the icon classes to it.
        // console.log(element);
        if (!$(element).next("span")[0]) {
            $("<span class='glyphicon glyphicon-ok form-control-feedback'></span>")
                .insertAfter(
                    $(element));
        }
    },
    highlight: function(element, errorClass, validClass) {
        // $(element).parents(".col-sm-5").addClass("has-error").removeClass("has-success");
        // $(element).next("span").addClass("glyphicon-remove").removeClass("glyphicon-ok");
        var elem = $(element);
        if (elem.hasClass("select2-hidden-accessible")) {
            $("#select2-" + elem.attr("id") + "-container").parent().addClass(
                errorClass);
        } else {
            elem.addClass(errorClass);
        }
    },
    unhighlight: function(element, errorClass, validClass) {
        // $(element).parents(".col-sm-5").addClass("has-success").removeClass("has-error");
        // $(element).next("span").addClass("glyphicon-ok").removeClass("glyphicon-remove");
        var elem = $(element);
        if (elem.hasClass("select2-hidden-accessible")) {
            $("#select2-" + elem.attr("id") + "-container").parent().removeClass(
                errorClass);
        } else {
            elem.removeClass(errorClass);
        }
    }
});
</script><?php /**PATH C:\xampp\htdocs\km-web\resources\views/subpageBack/table_infographic.blade.php ENDPATH**/ ?>