<?= $this->extend('layout/main') ?>

<?= $this->section('content_header') ?>
<div class="row border-bottom">
    <div class="col-sm-6"><h3 class="mb-0">Produk</h3></div>
    <div class="col-sm-6">
        <ol class="breadcrumb float-sm-end">
        <li class="breadcrumb-item"><a href="<?=base_url()?>">Home</a></li>
        <li class="breadcrumb-item"><a href="<?=base_url()?>produk">Produk</a></li>
        <li class="breadcrumb-item active" aria-current="page">View</li>
        </ol>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('content') ?>
<div class="row mb-3">
    <div class="col-lg-12 d-flex justify-content-end gap-2">
        <a href="<?=base_url()?>produk" class="btn btn-sm btn-warning btn-icon"><i class="button-icon bi bi-arrow-left-circle"></i> <span>Kembali</span></a>
         <a href="#" id="btn_delete" class="btn btn-sm btn-danger btn-icon"><i class="button-icon bi bi-trash"></i> <span>Delete Data</span></a>
    </div>
</div>

<div class="row g-4">
    <div class="col-lg-8">
        <form name="f1" id="f1" action="<?=base_url()?>produk/update" method="post" enctype="multipart/form-data">
            <div class="card card-warning card-outline mb-4">
                <div class="card-header">
                    <div class="card-title">View Data</div>
                </div>
                <div class="card-body">
                    <div class="row mb-3">
                        <label for="kode_produk" class="col-sm-3 col-form-label">Kode Produk : </label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control" id="kode_produk" name="kode_produk" value="<?=$data->kode_produk?>">
                            <span id="ekode_produk" class="text-danger invalid-feedback"></span>
                        </div>
                    </div>
                    <hr class="input_separator"/>
                    <div class="row mb-3">
                        <label for="nama_produk" class="col-sm-3 col-form-label">Nama Produk : </label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control" id="nama_produk" name="nama_produk" value="<?=$data->nama_produk?>">
                            <span id="enama_produk" class="text-danger invalid-feedback"></span>
                        </div>
                    </div>
                    <hr class="input_separator"/>
                    <div class="row mb-3">
                        <label for="kategori" class="col-sm-3 col-form-label">Kategori : </label>
                        <div class="col-sm-9">
                            <select class="form-control select2" id="kategori" name="kategori">
                                <option value="<?=$data->kategori?>"><?=$data->kategori?></option>
                                <option value="Makanan">Makanan</option>
                                <option value="Minuman">Minuman</option>
                                <option value="Jajanan">Jajanan</option>
                                <option value="Lainnya">Lainnya</option>
                            </select>
                            <span id="ekategori" class="text-danger invalid-feedback"></span>
                        </div>
                    </div>
                    <hr class="input_separator"/>
                    <div class="row mb-3">
                        <label for="status" class="col-sm-3 col-form-label">Status : </label>
                        <div class="col-sm-9">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="status" id="status" value="aktif" <?=($data->status=="aktif") ? "checked" : ""?>>
                                <label class="form-check-label" for="gridRadios1"> Aktif </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="status" id="status" value="tidak aktif" <?=($data->status=="tidak aktif") ? "checked" : ""?>>
                                <label class="form-check-label" for="gridRadios1"> Tidak Aktif </label>
                            </div>
                        </div>
                    </div>
                    <hr class="input_separator"/>
                    <div class="row mb-3">
                        <label for="gambar" class="col-sm-3 col-form-label">Gambar Produk : </label>
                        <div class="col-sm-9">
                            <div><img id="preview_img" src="<?=base_url()?>gambar/<?=$data->gambar?>" width="200px"> | <a href="#" class="btn btn-primary btn-sm" id="btn_browse"><i class="fas fa-file-upload"></i> Choose File</a></div>
                        </div>
                    </div>
                </div>
                <div class="card-footer d-flex gap-2">
                    <button type="submit" class="btn btn-primary">Save</button>
                    <button type="reset" class="btn btn-warning ml-auto">Cancel</button>
                </div>
            </div>
        </form>        
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('page_script') ?>

<?= $this->include('layout/css/sweetalert') ?>
<?= $this->include('layout/js/sweetalert') ?>

<?= $this->include('layout/css/select2') ?>
<?= $this->include('layout/js/select2') ?>

<?= $this->include('layout/js/plupload') ?>

<script type="text/javascript">
$(document).ready(function() {
$(".select2").select2({
    theme: 'bootstrap-5'
});

$("#f1").submit(function (e) {
    e.preventDefault();
    Swal.fire({
        text: 'Menyimpan data.. Silahkan tunggu..',
        allowOutsideClick: false
    });
    Swal.showLoading();
    var data_kirim = $("#f1").serializeArray();
    data_kirim.push({name : "id", value : "<?=$data->id_produk?>"});

    $.post("<?=base_url()?>produk/update",data_kirim).done(function (data) {
        if (data.status == 'success')
        {
            Swal.fire({
                text:'Data berhasil disimpan!',
                icon : 'success'
            }).then(function () {
                // window.location.href = '<?=base_url()?>meja/add';
                if(uploader1.files.length > 0){
                    upload(uploader1);
                }
            });
        }
    }).fail(function (data) {
        if(data.statusText == 'input'){
            Object.keys(data.responseJSON.messages).forEach(function(key){
                $("#e"+key).html(data.responseJSON.messages[key]);
                $("#e"+key).show();
            });
            Swal.close();
        }else{
            Swal.fire({
                text:'Terjadi kesalahan sistem!',
                icon : 'error'
            });
        }
    });
});

$("#btn_delete").click(function(e) {
    e.preventDefault();

    Swal.fire({
        title:'Delete Data..',
        html: '<p>Yakin ingin menghapus data ini?</p>',
        showDenyButton: true,
        showCancelButton: true,
        confirmButtonText: 'Yes',
        denyButtonText: 'No',
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                text: 'Menghapus data.. Silahkan tunggu..',
                allowOutsideClick: false
            });
            Swal.showLoading();
            $.post("<?=base_url()?>produk/delete",{id:<?=$data->id_produk?>}).done(function (data) {
                if (data.status == 'success')
                {
                    Swal.fire({
                        text:'Data berhasil dihapus!',
                        icon : 'success'
                    }).then(function () {
                        window.location.href = '<?=base_url()?>produk';
                    });
                }
            }).fail(function (data) {
                Swal.fire({
                    text:'Terjadi kesalahan pada saat operasi delete!',
                    icon : 'error'
                });
            });
        } else if (result.isDenied) {
            Swal.fire('Operasi dibatalkan..', '', 'info')
        }
    });
});

function init_uploader() {
    var uploader = new plupload.Uploader({
        'multi_selection' : false,
        'unique_names' : true,
        'browse_button' : 'btn_browse',
        'chunk_size':'1024kb',
        'max_retries' : 3,
        'url' : '<?=base_url()?>produk/upload',
    });

    uploader.init();

    uploader.bind("BeforeUpload", function(up,file) {
        var timestamp = Math.floor(Date.now() / 1000); // timestamp detik
        var random = Math.floor(Math.random() * 10000); // angka random 0–9999
        file.name = timestamp + '_' + random + '_'+file.target_name;

        var params = up.settings.multipart_params;
        params.Filename = file.target_name;
    });

    uploader.bind('UploadProgress', function(up, file) {
        /*document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";*/
        $("#filelist_inner").html(file.name + ' : ' + file.percent + '%');
        $("#filelist").attr('aria-valuenow',file.percent);
        $("#filelist_inner").attr('style','width:'+file.percent+'%');
    });

    uploader.bind('FileUploaded', function(up, file, info) {
        var response = JSON.parse(info.response);

        Swal.fire({
            text:'Uploading Sukses',
            icon : 'success',
            allowOutsideClick:false
        }).then(function () {
            window.location.href = '<?=base_url()?>produk/view/<?=$data->id_produk?>';
        });
    });

    uploader.bind('Error', function(up, err) {
        up.stop();
        console.log(err);
        Swal.fire({
            text:'Uploading Failed! Error : '+err.message,
            icon : 'error',
            allowOutsideClick:false
        });
    });

    uploader.bind('FilesAdded', function(up, files) {
        if(up.files.length > 1)
        {
            tfile = up.files[0];
            up.removeFile(tfile);
        }

        tfile = up.files[0];
        var allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
        var fileExt = tfile.name.split('.').pop().toLowerCase();

        if (!allowedExt.includes(fileExt)) {
            alert('File yang diunggah harus berupa gambar (jpg, jpeg, png, gif, webp)');
            up.removeFile(tfile);
            $("#preview_img").attr('src', ''); // hapus preview
            return false;
        }

        // Validasi ukuran file (opsional, contoh: maksimal 2 MB)
        if (tfile.size > 2 * 1024 * 1024) { // 2 MB
            alert('Ukuran file maksimal 2 MB!');
            up.removeFile(tfile);
            $("#preview_img").attr('src', '');
            return false;
        }

        // Tampilkan preview gambar (gunakan FileReader)
        var reader = new FileReader();
        reader.onload = function(e) {
            $("#preview_img").attr('src', e.target.result);
        };
        
        reader.readAsDataURL(tfile.getSource().getSource());
    });

    return uploader;
}

function upload(up)
{
    if (up.files.length <= 0)
    {
        Swal.fire({
            title:'Upload',
            html:'Tidak ada file yang akan diupload..',
            icon : 'error',
            allowOutsideClick:false
        }).then(function () {
            return false;
        });
    }

    Swal.fire({
        title:'Uploading..',
        html:'<div id="filelist" class="progress" role="progressbar" aria-label="test" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"><div class="progress-bar progress-bar-striped progress-bar-animated" id="filelist_inner" style="width: 0%">0%</div></div>',
        allowOutsideClick:false
    });
    Swal.showLoading();
    up.start();
}

var uploader1 = init_uploader();
});
</script>
<?= $this->endSection() ?>