<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <div class="card card-primary">
                <div id="tabel_loading" class="overlay d-flex justify-content-center align-items-center">
                    <i class="fas fa-2x fa-sync fa-spin"></i>
                </div>
                <div class="card-header">
                    <h3 class="card-title">HADIAH</h3>
                </div>
                <div class="card-body">
                    <a class="btn btn-primary" onclick="aksi_tambah_modal()">Tambah</a> &nbsp;
                    <div style="margin-bottom: 10px;"></div>
                    <div id="tabel" class="table-responsive">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<div class="modal fade" id="modal_hadiah">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div id="modal_loading" class="overlay d-flex justify-content-center align-items-center">
                <i class="fas fa-2x fa-sync fa-spin"></i>
            </div>
            <form enctype="multipart/form-data" id="submit">
                <div class="modal-header">
                    <h4 id="modal_title" class="modal-title">TAMBAH DATA</h4>
                    <button type="button" class="close" onclick="aksi_tutup_modal()" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>

                <div class="modal-body">

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-row">
                                <label for="input1" class="col-lg-2 control-label">Kode</label>
                                <div class="col-lg-10">
                                    <input type="text" class="form-control" id="mst_hadiah_kode" name="mst_hadiah_kode" placeholder="Kode hadiah">
                                </div>
                            </div>
                            <br>
                            <div class="form-row">
                                <label for="input1" class="col-lg-2 control-label">Nama</label>
                                <div class="col-lg-10">
                                    <input type="text" class="form-control" id="mst_hadiah_nama" name="mst_hadiah_nama" placeholder="Nama hadiah">
                                </div>
                            </div>
                            <br>
                            <div class="form-row">
                                <label for="input1" class="col-lg-2 control-label">Jenis</label>
                                <div class="col-lg-10">
                                    <select required class="form-control select2bs4" style="width: 100%;" id="mst_hadiah_jenis" name='mst_hadiah_jenis' required>
                                        <option selected="selected"></option>
                                        <option value="Saldo">Saldo</option>
                                        <option value="Produk">Produk</option>
                                    </select>
                                </div>
                            </div>
                            <br>
                            <div class="form-row">
                                <label for="input1" class="col-lg-2 control-label">Harga</label>
                                <div class="col-lg-10">
                                    <input type="text" class="form-control" id="mst_hadiah_harga" name="remoteUrl" placeholder="Poin yang dibutuhkan untuk menukar hadiah">
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-row">
                                <label for="input1" class="col-lg-3 control-label">Stok</label>
                                <div class="col-lg-9">
                                    <input type="number" class="form-control" id="mst_hadiah_stok" name="remoteUrl" placeholder="Stok hadiah">
                                </div>
                            </div>
                            <br>
                            <div class="form-row">
                                <label for="input1" class="col-lg-3 control-label">Tgl. Awal</label>
                                <div class="col-lg-9">
                                    <input type="datetime-local" class="form-control" id="mst_hadiah_periode_awal" name="mst_hadiah_periode_awal">
                                </div>
                            </div>
                            <br>
                            <div class="form-row">
                                <label for="input1" class="col-lg-3 control-label">Tgl. Akhir</label>
                                <div class="col-lg-9">
                                    <input type="datetime-local" class="form-control" id="mst_hadiah_periode_akhir" name="mst_hadiah_periode_akhir">
                                </div>
                            </div>
                            <br>
                            <div class="form-row">
                                <label for="input1" class="col-lg-3 control-label">Foto</label>
                                <div class="col-lg-9">
                                    <input type="file" class="form-control" id="mst_hadiah_foto" name="mst_hadiah_foto">
                                </div>
                            </div>

                        </div>

                        <div style="margin-top: 20px;" class="col-md-12">
                            <div class="form-row">
                                <label for="input1" class="col-lg-1 control-label">Isi</label>
                                <div class="col-lg-11">
                                    <textarea class="form-control" id="mst_hadiah_keterangan" name="mst_hadiah_keterangan"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>

                <div class="modal-footer justify-content-between">
                    <button type="button" class="btn btn-default" onclick="aksi_tutup_modal()">TUTUP</button>
                    <button type="submit" id="btn_simpan" class="btn btn-primary">SIMPAN</button>
                </div>
            </form>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>


<script src="<?php echo base_url(); ?>assets/plugins/jquery/jquery.min.js"></script>
<script src="<?php echo base_url(); ?>assets/ckeditor/ckeditor.js"></script>
<script type="text/javascript">
    $(function() {
        CKEDITOR.replace('mst_hadiah_keterangan', {
            toolbar: [
                ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'],
                {
                    name: 'basicstyles',
                    items: ['Bold', 'Italic', 'Underline']
                },
                {
                    name: 'links',
                    items: ['Link', 'Unlink', 'Anchor']
                },
            ],
            height: '200px'
        });
    });
</script>

<script type='text/javascript'>
    var submit_status;
    $(document).ready(function() {
        aksi_data();

        //FORMAT RUPIAH
        var mst_hadiah_harga = document.getElementById('mst_hadiah_harga');
        mst_hadiah_harga.addEventListener('keyup', function(e) {
            mst_hadiah_harga.value = aksi_rupiah(this.value, '');
        });
    });

    $('#submit').submit(function(e) {
        e.preventDefault();
        var mst_hadiah_kode = $("#mst_hadiah_kode").val();
        var mst_hadiah_nama = $("#mst_hadiah_nama").val();
        var mst_hadiah_jenis = $("#mst_hadiah_jenis").val();
        var mst_hadiah_harga = $("#mst_hadiah_harga").val();
        var mst_hadiah_stok = $("#mst_hadiah_stok").val();
        var mst_hadiah_periode_awal = $("#mst_hadiah_periode_awal").val();
        var mst_hadiah_periode_akhir = $("#mst_hadiah_periode_akhir").val();
        var mst_hadiah_foto = $("#mst_hadiah_foto").val();
        var mst_hadiah_keterangan = CKEDITOR.instances['mst_hadiah_keterangan'].getData();

        //EDIT
        if (submit_status == 'Edit') {
            if (mst_hadiah_kode.length < 3) {
                toastr.error('Data belum lengkap');
            } else if (mst_hadiah_nama.length < 1) {
                toastr.error('Data belum lengkap');
            } else if (mst_hadiah_jenis.length < 3) {
                toastr.error('Data belum lengkap');
            } else if (mst_hadiah_harga.length < 1) {
                toastr.error('Data belum lengkap');
            } else if (mst_hadiah_stok.length < 1) {
                toastr.error('Data belum lengkap');
            } else if (mst_hadiah_periode_awal.length < 1) {
                toastr.error('Data belum lengkap');
            } else if (mst_hadiah_periode_akhir.length < 1) {
                toastr.error('Data belum lengkap');
            } else if (mst_hadiah_foto.length < 1) {
                toastr.error('Data belum lengkap');
            } else if (mst_hadiah_keterangan.length < 1) {
                toastr.error('Data belum lengkap');
            } else {
                document.getElementById("modal_loading").style.visibility = "visible";

                var formData = new FormData();
                formData.append("mst_hadiah_kode", mst_hadiah_kode);
                formData.append("mst_hadiah_nama", mst_hadiah_nama);
                formData.append("mst_hadiah_jenis", mst_hadiah_jenis);
                formData.append("mst_hadiah_harga", mst_hadiah_harga);
                formData.append("mst_hadiah_stok", mst_hadiah_stok);
                formData.append("mst_hadiah_periode_awal", mst_hadiah_periode_awal);
                formData.append("mst_hadiah_periode_akhir", mst_hadiah_periode_akhir);
                formData.append("mst_hadiah_foto", $("#mst_hadiah_foto")[0].files[0]);
                formData.append("mst_hadiah_keterangan", mst_hadiah_keterangan);

                $.ajax({
                    url: '<?php echo base_url() ?>hadiah/aksi_edit',
                    type: "POST",
                    data: formData,
                    processData: false,
                    contentType: false,
                    cache: false,
                    async: false,
                    success: function(data) {
                        toastr.success('Hadiah berhasil di edit');

                        //SET VALUE
                        document.getElementById("mst_hadiah_kode").value = '';
                        document.getElementById("mst_hadiah_nama").value = '';
                        $("#mst_hadiah_jenis").val('').trigger("change");
                        document.getElementById("mst_hadiah_harga").value = '';
                        document.getElementById("mst_hadiah_stok").value = '';
                        document.getElementById("mst_hadiah_periode_awal").value = '';
                        document.getElementById("mst_hadiah_periode_akhir").value = '';
                        document.getElementById("mst_hadiah_foto").value = '';
                        CKEDITOR.instances['mst_hadiah_keterangan'].setData('');

                        //LOADING
                        document.getElementById("modal_loading").style.visibility = "hidden";

                        //MODAL
                        $("#modal_hadiah").modal('hide');

                        aksi_data();
                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                        toastr.error('Hadiah gagal di edit');
                        document.getElementById("modal_loading").style.visibility = "hidden";
                    }
                });
            }
        }

        //TAMBAH
        if (submit_status == 'Tambah') {
            if (mst_hadiah_kode.length < 3) {
                toastr.error('Data belum lengkap');
            } else if (mst_hadiah_nama.length < 1) {
                toastr.error('Data belum lengkap');
            } else if (mst_hadiah_jenis.length < 3) {
                toastr.error('Data belum lengkap');
            } else if (mst_hadiah_harga.length < 1) {
                toastr.error('Data belum lengkap');
            } else if (mst_hadiah_stok.length < 1) {
                toastr.error('Data belum lengkap');
            } else if (mst_hadiah_periode_awal.length < 1) {
                toastr.error('Data belum lengkap');
            } else if (mst_hadiah_periode_akhir.length < 1) {
                toastr.error('Data belum lengkap');
            } else if (mst_hadiah_keterangan.length < 1) {
                toastr.error('Data belum lengkap');
            } else {
                document.getElementById("modal_loading").style.visibility = "visible";

                var formData = new FormData();
                formData.append("mst_hadiah_kode", mst_hadiah_kode);
                formData.append("mst_hadiah_nama", mst_hadiah_nama);
                formData.append("mst_hadiah_jenis", mst_hadiah_jenis);
                formData.append("mst_hadiah_harga", mst_hadiah_harga);
                formData.append("mst_hadiah_stok", mst_hadiah_stok);
                formData.append("mst_hadiah_periode_awal", mst_hadiah_periode_awal);
                formData.append("mst_hadiah_periode_akhir", mst_hadiah_periode_akhir);
                formData.append("mst_hadiah_foto", $("#mst_hadiah_foto")[0].files[0]);
                formData.append("mst_hadiah_keterangan", mst_hadiah_keterangan);

                $.ajax({
                    url: '<?php echo base_url() ?>hadiah/aksi_tambah',
                    type: "POST",
                    data: formData,
                    processData: false,
                    contentType: false,
                    cache: false,
                    async: false,
                    success: function(data) {
                        var obj = JSON.parse(data);
                        var tambah_status = obj.tambah_status;

                        if (tambah_status == '0') {
                            toastr.success('Hadiah berhasil di tambahkan');

                            //SET VALUE
                            document.getElementById("mst_hadiah_kode").value = '';
                            document.getElementById("mst_hadiah_nama").value = '';
                            $("#mst_hadiah_jenis").val('').trigger("change");
                            document.getElementById("mst_hadiah_harga").value = '';
                            document.getElementById("mst_hadiah_stok").value = '';
                            document.getElementById("mst_hadiah_periode_awal").value = '';
                            document.getElementById("mst_hadiah_periode_akhir").value = '';
                            document.getElementById("mst_hadiah_foto").value = '';
                            CKEDITOR.instances['mst_hadiah_keterangan'].setData('');

                            //LOADING
                            document.getElementById("modal_loading").style.visibility = "hidden";

                            aksi_data();
                        } else {
                            toastr.error('Hadiah gagal di tambahkan karena kode hadiah sudah pernah ditambahkan sebelumnya!');
                            document.getElementById("modal_loading").style.visibility = "hidden";
                        }

                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                        toastr.error('Hadiah gagal di tambahkan');
                        document.getElementById("modal_loading").style.visibility = "hidden";
                    }
                });
            }
        }

    });

    function aksi_data() {
        document.getElementById("tabel_loading").style.visibility = "visible";
        $.ajax({
            type: 'POST',
            url: '<?php echo base_url() ?>hadiah/aksi_data',
            success: function(html) {
                document.getElementById("tabel_loading").style.visibility = "hidden";
                $("#tabel").html(html);
            }
        })
    }

    function aksi_edit_modal(element) {
        document.getElementById("modal_loading").style.visibility = "hidden";

        var $row = $(element).closest("tr");
        var mst_hadiah_kode = $row.find("#tbl_mst_hadiah_kode").text();
        var mst_hadiah_nama = $row.find("#tbl_mst_hadiah_nama").text();
        var mst_hadiah_jenis = $row.find("#tbl_mst_hadiah_jenis").text();
        var mst_hadiah_harga = $row.find("#tbl_mst_hadiah_harga").text();
        var mst_hadiah_stok = $row.find("#tbl_mst_hadiah_stok").text();
        var mst_hadiah_periode_awal = $row.find("#tbl_mst_hadiah_periode_awal").text();
        var mst_hadiah_periode_akhir = $row.find("#tbl_mst_hadiah_periode_akhir").text();
        var mst_hadiah_foto = $row.find("#tbl_mst_hadiah_foto").text();
        var mst_hadiah_keterangan = $row.find("#tbl_mst_hadiah_keterangan").text();


        //SET VALUE
        document.getElementById("mst_hadiah_kode").value = mst_hadiah_kode;
        document.getElementById("mst_hadiah_nama").value = mst_hadiah_nama;
        $("#mst_hadiah_jenis").val(mst_hadiah_jenis).trigger("change");
        document.getElementById("mst_hadiah_harga").value = mst_hadiah_harga;
        document.getElementById("mst_hadiah_stok").value = mst_hadiah_stok;
        document.getElementById("mst_hadiah_periode_awal").value = aksi_date(mst_hadiah_periode_awal);
        document.getElementById("mst_hadiah_periode_akhir").value = aksi_date(mst_hadiah_periode_akhir);
        document.getElementById("mst_hadiah_foto").value = mst_hadiah_foto;
        CKEDITOR.instances['mst_hadiah_keterangan'].setData(mst_hadiah_keterangan);


        //DISABLE VALUE
        document.getElementById("mst_hadiah_kode").readOnly = true;

        //SET STATUS
        submit_status = 'Edit';

        //SET TITLE
        $("#modal_title").html('EDIT HADIAH');

        //SHOW MODAL
        $('#modal_hadiah').modal({
            backdrop: 'static',
            keyboard: false
        }, 'show');
    }

    function aksi_tambah_modal() {
        document.getElementById("modal_loading").style.visibility = "hidden";

        //SET TITLE
        $("#modal_title").html('TAMBAH HADIAH');

        //ENABLE VALUE
        document.getElementById("mst_hadiah_kode").readOnly = false;

        //SET VALUE
        document.getElementById("mst_hadiah_kode").value = '';
        document.getElementById("mst_hadiah_nama").value = '';
        $("#mst_hadiah_jenis").val('').trigger("change");
        document.getElementById("mst_hadiah_harga").value = '';
        document.getElementById("mst_hadiah_stok").value = '';
        document.getElementById("mst_hadiah_periode_awal").value = '';
        document.getElementById("mst_hadiah_periode_akhir").value = '';
        document.getElementById("mst_hadiah_foto").value = '';
        CKEDITOR.instances['mst_hadiah_keterangan'].setData('');

        //SET STATUS
        submit_status = 'Tambah';

        //SHOW MODAL
        $('#modal_hadiah').modal({
            backdrop: 'static',
            keyboard: false
        }, 'show');
    }

    function aksi_tidak_aktif(mst_hadiah_kode) {
        $.ajax({
            url: '<?php echo base_url() ?>hadiah/aksi_tidak_aktif/' + mst_hadiah_kode,
            type: "POST",
            success: function() {
                toastr.success('Berhasil mengubah status hadiah menjadi tidak aktif');
                aksi_data();
            },
            error: function(xhr, ajaxOptions, thrownError) {
                toastr.error('Gagal mengubah status hadiah menjadi tidak aktif');
            }
        });
    }

    function aksi_aktif(mst_hadiah_kode) {
        $.ajax({
            url: '<?php echo base_url() ?>hadiah/aksi_aktif/' + mst_hadiah_kode,
            type: "POST",
            success: function() {
                toastr.success('Berhasil mengubah status hadiah menjadi aktif');
                aksi_data();
            },
            error: function(xhr, ajaxOptions, thrownError) {
                toastr.error('Gagal mengubah status hadiah menjadi tidak aktif');
            }
        });
    }

    function aksi_hapus(mst_hadiah_kode) {
        Swal.fire({
            title: 'Yakin ingin menghapus hadiah?',
            text: "Setelah menghapus, data tidak bisa dikembalikan lagi!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Hapus!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '<?php echo base_url() ?>hadiah/aksi_hapus/' + mst_hadiah_kode,
                    type: "POST",
                    success: function() {
                        toastr.success('Berhasil menghapus hadiah');
                        aksi_data();
                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                        toastr.error('Gagal menghapus hadiah');
                    }
                });
            }
        })
    }

    function aksi_tutup_modal() {
        aksi_data();
        document.getElementById("modal_loading").style.visibility = "hidden";
        $("#modal_hadiah").modal('hide');
    }

    function aksi_rupiah(angka, prefix) {
        var number_string = angka.replace(/[^,\d]/g, '').toString(),
            split = number_string.split(','),
            sisa = split[0].length % 3,
            rupiah = split[0].substr(0, sisa),
            ribuan = split[0].substr(sisa).match(/\d{3}/gi);

        if (ribuan) {
            separator = sisa ? '.' : '';
            rupiah += separator + ribuan.join('.');
        }

        rupiah = split[1] != undefined ? rupiah + ',' + split[1] : rupiah;
        return prefix == undefined ? rupiah : (rupiah ? '' + rupiah : '');
    }

    function aksi_date(inputDate) {
        var date = new Date(inputDate);

        var year = date.getFullYear();
        var month = ("0" + (date.getMonth() + 1)).slice(-2);
        var day = ("0" + date.getDate()).slice(-2);
        var hours = ("0" + date.getHours()).slice(-2);
        var minutes = ("0" + date.getMinutes()).slice(-2);

        var formattedDate = year + "-" + month + "-" + day + "T" + hours + ":" + minutes;
        return formattedDate;
    }
</script>