<?php

defined('BASEPATH') || exit('No direct script access allowed');

class Admin extends CI_Controller {

    var $title      = 'Halaman Pelaksana Ujian Online';
    var $js         = array();
    var $status_cbt = FALSE;
    var $username   = "";

    public function __construct() {
        parent::__construct();
        $this->load->library('session');

        $this->validate_user();

        $status = $this->db->from('status_cbt')
            ->get()
            ->row();

        $this->status_cbt = $status;
    }

    public function index() {
        $data = array();

        $this->load->library('form_validation');
        $this->form_validation->set_rules('ip_server', 'Alamat Server', 'required|valid_url');
        $this->form_validation->set_rules('token', 'Token', 'required');

        if ($this->form_validation->run() == FALSE) {
            $data['keterangan'] = validation_errors();
        } else {
            $ip    = $this->input->post('ip_server');
            $token = $this->input->post('token');
            $unix  = $this->input->post('unix');

            $in                      = array();
            $in['alamat_server_cbt'] = $ip;
            $in['token_cbt']         = $token;
            $in['kode_unix']         = $unix;
            $in['status_sync']       = 0;

            $this->db->insert('status_cbt', $in);

            redirect('admin');
        }

        $this->render_page($data, 'admin/template/dashboard');
    }

    function qrcode() {
        $this->load->library('ciqrcode'); //pemanggilan library QR CODE

        $config['cacheable'] = true; //boolean, the default is true
        $config['cachedir']  = './assets/'; //string, the default is application/cache/
        $config['errorlog']  = './assets/'; //string, the default is application/logs/
        $config['imagedir']  = './assets/uploads/qrcode/'; //direktori penyimpanan qr code
        $config['quality']   = true; //boolean, the default is true
        $config['size']      = '1024'; //interger, the default is 1024
        $config['black']     = array(224, 255, 255); // array, default is array(255,255,255)
        $config['white']     = array(70, 130, 180); // array, default is array(0,0,0)
        $this->ciqrcode->initialize($config);

        $image_name = 'server_url.png'; //buat name dari qr code sesuai dengan nim

        $params['data']     = $this->status_cbt->url_pelaksana; //data yang akan di jadikan QR CODE
        $params['level']    = 'H'; //H=High
        $params['size']     = 10;
        $params['savename'] = FCPATH . $config['imagedir'] . $image_name; //simpan image QR CODE ke folder assets/images/
        $this->ciqrcode->generate($params); // fungsi untuk generate QR CODE

        $data        = array();
        $this->title = 'QR Code Server';
        $this->render_page($data, 'admin/template/qrcode');
    }

    public function profil() {
        $data = array();

        $btn_update = $this->input->post('btn_update', true);
        if ($btn_update != "") {
            $username  = $this->input->post('username', true);
            $pass_lama = $this->input->post('pass_lama', true);
            $new_pass  = $this->input->post('new_pass', true);
            $re_pass   = $this->input->post('re_pass', true);

            if ($username == "" || $pass_lama == "" || $new_pass == "" || $re_pass == "") {
                $data['keterangan'] = "Form isian tidak boleh Kosong";
            }

            if ($new_pass != $re_pass) {
                $data['keterangan'] = "Password dan konfirmasi Password tidak sama";
            }

            $user = $this->db->from('user')
                ->where('username', $username)
                ->where('password', md5($pass_lama))
                ->get()->row();
            if (!$user) {
                $data['keterangan'] = "Username dan Password lama tidak Sesuai";
            } else {
                $this->db->where('id_user', $user->id_user)
                    ->update('user', array('username' => $username, 'password' => md5($new_pass)));

                $data['keterangan'] = "<h3>Password berhasil di update</h3>";
            }
        }

        $this->title = 'Profil Data';
        $this->render_page($data, 'admin/template/profil');
    }

    public function singkronisasi() {

        $data        = array();
        $this->title = 'Singkronisasi Data';
        $this->render_page($data, 'admin/template/singkronisasi');
    }

    public function upload_nilai($do = '') {
        $url = $this->status_cbt->alamat_server_cbt . 'home/upload_nilai/';
//        echo $url;
        $pesan = '';
        if ($do != '') {
            if (function_exists('curl_version')) {
                $nilai = $this->db->from('ujian_dilaksanakan')->get()->result();
                $nilai = json_encode($nilai);

                $ch      = curl_init();
                $qry_str = "npsn=" . $this->status_cbt->npsn . "&data=" . $nilai;
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_TIMEOUT, 3);

// Set request method to POST
                curl_setopt($ch, CURLOPT_POST, 1);

// Set query data here with CURLOPT_POSTFIELDS
                curl_setopt($ch, CURLOPT_POSTFIELDS, $qry_str);

                $content = trim(curl_exec($ch));
                curl_close($ch);

                $pesan = html_escape($content);
            } else {
                $pesan = "Harap aktifkan CURL, agar proses dapat berjalan";
            }
        }
        $data          = array();
        $data['pesan'] = $pesan;
        $this->title   = 'Singkronisasi Nilai';
        $this->render_page($data, 'admin/template/sync_nilai');
    }

    public function sync_data_13() {
        $soal = $this->db->select('id_bank_soal')
            ->from('bank_soal')
            ->or_where('audio_file <>', '')
            ->or_where('video_file <>', '')
            ->get()
            ->result();

        $ket = array(
            'status'      => 'OK',
            'jumlah_data' => count($soal),
            'data'        => $soal,
        );

        echo json_encode($ket);
    }

    private function downloadFile($url, $path) {
        $newfname = $path;
        $file     = fopen($url, 'rb');
        if ($file) {
            $newf = fopen($newfname, 'wb');
            if ($newf) {
                while (!feof($file)) {
                    fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
                }
            }
        }
        if ($file) {
            fclose($file);
        }
        if ($newf) {
            fclose($newf);
        }
    }

    public function trunc_data_1($token) {
        $this->db->query('TRUNCATE master_kelas');
    }

    public function reset_data($token) {
        $this->db->query('TRUNCATE master_kelas');
        $this->db->query('TRUNCATE detail_jadwal_ujian');
        $this->db->query('TRUNCATE detail_paket_soal');
        $this->db->query('TRUNCATE master_jenjang_pendidikan');
        $this->db->query('TRUNCATE master_jurusan');
        $this->db->query('TRUNCATE ujian_dilaksanakan');
        $this->db->query('TRUNCATE soal_ujian');
        $this->db->query('TRUNCATE mata_pelajaran');
        $this->db->query('TRUNCATE materi_pelajaran');
        $this->db->query('TRUNCATE jenis_ujian');
        $this->db->query('TRUNCATE siswa');
        $this->db->query('TRUNCATE data_paket_soal');
        $this->db->query('TRUNCATE bank_soal');
        $this->db->query('TRUNCATE jadwal_ujian');

        $this->db->query("TRUNCATE tabel_sync");
        $this->db->update('tabel_download', array('status_download' => 0));
    }

    public function data_sinkron() {
        $url = $this->status_cbt->alamat_server_cbt . 'home/data_sinkron/' . $this->status_cbt->token_cbt . '/' . $this->status_cbt->id_server;

        $arrContextOptions = array(
            "ssl" => array(
                "verify_peer"      => false,
                "verify_peer_name" => false,
            ),
        );

        $responseBody = @file_get_contents($url, false, stream_context_create($arrContextOptions));

        // print_r($url);
        // print_r($responseBody);
        $jumlah_update = 30;

        if ($responseBody != "" && $responseBody != "ID SERVER TIDAK DITEMUKAN" && $responseBody != 'SERVER NONAKTIF' && $responseBody != 'TIDAK DAPAT MELAKUKAN SINKRONISASI KARENA SEKOLAH BELUM AKTIF') {
            $respon = json_decode($responseBody);

            foreach ($respon as $key => $value) {
                if ($key != 13) {
                    $jumlah = $value * 1;
                    if ($jumlah > $jumlah_update) {
                        $jml = ceil($jumlah / $jumlah_update);
                        for ($i = 1; $i <= $jml; $i++) {
                            $sync = array(
                                'id_sync'       => $key,
                                'data_ke'       => $i - 1,
                                'jumlah_update' => $i * $jumlah_update,
                                'status_sync'   => 0,
                            );

                            $this->db->insert('tabel_sync', $sync);
                        }
                    } else {
                        $sync = array(
                            'id_sync'       => $key,
                            'data_ke'       => 0,
                            'jumlah_update' => $jumlah,
                            'status_sync'   => 0,
                        );

                        $this->db->insert('tabel_sync', $sync);
                    }

                    $this->db->update('tabel_download', array('status_download' => 0), array('id_download' => $key));
                } elseif ($key == 13) {
                    $jumlah = $value * 1;
                    for ($i = 1; $i <= $jumlah; $i++) {
                        $sync = array(
                            'id_sync'       => $key,
                            'data_ke'       => $i - 1,
                            'jumlah_update' => $jumlah,
                            'status_sync'   => 0,
                        );

                        $this->db->insert('tabel_sync', $sync);
                    }

                    $this->db->update('tabel_download', array('status_download' => 0), array('id_download' => $key));
                }
            }

            echo 'OK';
        } else {
            echo $responseBody;
        }
    }

    public function download_1($no) {
        //master kelas
        $detail = $this->db->from('tabel_sync')->where('data_ke', $no)
            ->where('id_sync', 1)
            ->get()->row();
        if (!$detail) {
            echo 0;
            die();
        }

        $url               = $this->status_cbt->alamat_server_cbt . 'home/download_1/' . $this->status_cbt->token_cbt . '/' . ($no * 30) . '/' . ($detail->jumlah_update - 1);
        $arrContextOptions = array(
            "ssl" => array(
                "verify_peer"      => false,
                "verify_peer_name" => false,
            ),
        );

        $responseBody = @file_get_contents($url, false, stream_context_create($arrContextOptions));

        if ($responseBody != "") {
            $json = json_decode($responseBody);
            if (isset($json->error) && $json->error == 0) {
                foreach ($json->master_kelas as $dbase) {
                    unset($dbase->jenjang_pendidikan);

                    $this->db->insert('master_kelas', $dbase);
                }

                $this->db->update('tabel_sync', array('status_sync' => 1), array('id_sync' => 1, 'data_ke' => $no));

                $data_1 = $this->db->query("SELECT COALESCE(SUM(CASE WHEN status_sync = 0 THEN 1 ELSE 0 END), 0) as belum, COALESCE(SUM(CASE WHEN status_sync = 1 THEN 1 ELSE 0 END), 0) as sudah FROM tabel_sync WHERE id_sync = 1")->row();

                $total_1  = $data_1->sudah + $data_1->belum;
                $persen_1 = ($data_1->sudah / ($total_1 == 0 ? 1 : $total_1)) * 100;
                if ($persen_1 == 100) {
                    $this->db->update('tabel_download', array('status_download' => 1), array('id_download' => 1));
                }

                echo $persen_1;
            } else {
                echo $responseBody;
            }
        } else {
            echo 0;
        }
    }

    public function download_2($no) {
        //master kelas
        $detail = $this->db->from('tabel_sync')->where('data_ke', $no)
            ->where('id_sync', 2)
            ->get()->row();
        if (!$detail) {
            echo 0;
            die();
        }

        $url = $this->status_cbt->alamat_server_cbt . 'home/download_2/' . $this->status_cbt->token_cbt . '/' . ($no * 30) . '/' . ($detail->jumlah_update - 1);
//        echo $url;
        $arrContextOptions = array(
            "ssl" => array(
                "verify_peer"      => false,
                "verify_peer_name" => false,
            ),
        );

        $responseBody = @file_get_contents($url, false, stream_context_create($arrContextOptions));

        if ($responseBody != "") {
            $json = json_decode($responseBody);
            if (isset($json->error) && $json->error == 0) {
                foreach ($json->master_jurusan as $dbase) {
                    unset($dbase->jenjang_pendidikan);

                    $this->db->insert('master_jurusan', $dbase);
                }

                $this->db->update('tabel_sync', array('status_sync' => 1), array('id_sync' => 2, 'data_ke' => $no));

                $data_1 = $this->db->query("SELECT COALESCE(SUM(CASE WHEN status_sync = 0 THEN 1 ELSE 0 END), 0) as belum, COALESCE(SUM(CASE WHEN status_sync = 1 THEN 1 ELSE 0 END), 0) as sudah FROM tabel_sync WHERE id_sync = 2")->row();

                $total_1  = $data_1->sudah + $data_1->belum;
                $persen_1 = ($data_1->sudah / ($total_1 == 0 ? 1 : $total_1)) * 100;
                if ($persen_1 == 100) {
                    $this->db->update('tabel_download', array('status_download' => 1), array('id_download' => 2));
                }

                echo $persen_1;
            } else {
                echo $responseBody;
            }
        } else {
            echo 0;
        }
    }

    public function download_3($no) {
        //master kelas
        $detail = $this->db->from('tabel_sync')->where('data_ke', $no)
            ->where('id_sync', 3)
            ->get()->row();
        if (!$detail) {
            echo 0;
            die();
        }

        $url = $this->status_cbt->alamat_server_cbt . 'home/download_3/' . $this->status_cbt->token_cbt . '/' . ($no * 30) . '/' . ($detail->jumlah_update - 1);
//        echo $url;
        $arrContextOptions = array(
            "ssl" => array(
                "verify_peer"      => false,
                "verify_peer_name" => false,
            ),
        );

        $responseBody = @file_get_contents($url, false, stream_context_create($arrContextOptions));

//        print_r($responseBody);

        if ($responseBody != "") {
            $json = json_decode($responseBody);
            if (isset($json->error) && $json->error == 0) {
                foreach ($json->mapel as $dbase) {
//                    unset($dbase->jenjang_pendidikan);
                    //                    $this->db->insert('mata_pelajaran', $dbase);

                    $in  = array();
                    $cek = $this->db->from('mata_pelajaran')->where('id_mata_pelajaran', $dbase->id_mata_pelajaran)->get()->row();
                    if ($cek) {
                        $in['nama_mata_pelajaran'] = $dbase->nama_mata_pelajaran;

                        $this->db->where('id_mata_pelajaran', $dbase->id_mata_pelajaran);
                        $this->db->update('mata_pelajaran', $in);
                    } else {
                        $in['id_mata_pelajaran']   = $dbase->id_mata_pelajaran;
                        $in['nama_mata_pelajaran'] = $dbase->nama_mata_pelajaran;

                        $this->db->insert('mata_pelajaran', $in);
                    }
                }

                $this->db->update('tabel_sync', array('status_sync' => 1), array('id_sync' => 3, 'data_ke' => $no));

                $data_1 = $this->db->query("SELECT COALESCE(SUM(CASE WHEN status_sync = 0 THEN 1 ELSE 0 END), 0) as belum, COALESCE(SUM(CASE WHEN status_sync = 1 THEN 1 ELSE 0 END), 0) as sudah FROM tabel_sync WHERE id_sync = 3")->row();

                $total_1  = $data_1->sudah + $data_1->belum;
                $persen_1 = ($data_1->sudah / ($total_1 == 0 ? 1 : $total_1)) * 100;
                if ($persen_1 == 100) {
                    $this->db->update('tabel_download', array('status_download' => 1), array('id_download' => 3));
                }

                echo $persen_1;
            } else {
                echo $responseBody;
            }
        } else {
            echo 0;
        }
    }

    public function download_4($no) {
        //master kelas
        $detail = $this->db->from('tabel_sync')->where('data_ke', $no)
            ->where('id_sync', 4)
            ->get()->row();
        if (!$detail) {
            echo 0;
            die();
        }

        $url = $this->status_cbt->alamat_server_cbt . 'home/download_4/' . $this->status_cbt->token_cbt . '/' . ($no * 30) . '/' . ($detail->jumlah_update - 1);
//        echo $url;

        $arrContextOptions = array(
            "ssl" => array(
                "verify_peer"      => false,
                "verify_peer_name" => false,
            ),
        );

        $responseBody = @file_get_contents($url, false, stream_context_create($arrContextOptions));

//        print_r($responseBody);

        if ($responseBody != "") {
            $json = json_decode($responseBody);
            if (isset($json->error) && $json->error == 0) {
                foreach ($json->mapel as $dbase) {
                    $this->db->insert('materi_pelajaran', $dbase);
                }

                $this->db->update('tabel_sync', array('status_sync' => 1), array('id_sync' => 4, 'data_ke' => $no));

                $data_1 = $this->db->query("SELECT COALESCE(SUM(CASE WHEN status_sync = 0 THEN 1 ELSE 0 END), 0) as belum, COALESCE(SUM(CASE WHEN status_sync = 1 THEN 1 ELSE 0 END), 0) as sudah FROM tabel_sync WHERE id_sync = 4")->row();

                $total_1  = $data_1->sudah + $data_1->belum;
                $persen_1 = ($data_1->sudah / ($total_1 == 0 ? 1 : $total_1)) * 100;
                if ($persen_1 == 100) {
                    $this->db->update('tabel_download', array('status_download' => 1), array('id_download' => 4));
                }

                echo $persen_1;
            } else {
                echo $responseBody;
            }
        } else {
            echo 'No Response Body';
        }
    }

    public function download_5($no) {
        //master kelas
        $detail = $this->db->from('tabel_sync')->where('data_ke', $no)
            ->where('id_sync', 5)
            ->get()->row();
        if (!$detail) {
            echo 0;
            die();
        }

        $url = $this->status_cbt->alamat_server_cbt . 'home/download_5/' . $this->status_cbt->token_cbt . '/' . ($no * 30) . '/' . ($detail->jumlah_update - 1);
//        echo $url;

        $arrContextOptions = array(
            "ssl" => array(
                "verify_peer"      => false,
                "verify_peer_name" => false,
            ),
        );

        $responseBody = @file_get_contents($url, false, stream_context_create($arrContextOptions));

//        print_r($responseBody);

        if ($responseBody != "") {
            $json = json_decode($responseBody);
            if (isset($json->error) && $json->error == 0) {
                foreach ($json->jenis_ujian as $dbase) {
                    $this->db->insert('jenis_ujian', $dbase);
                }

                $this->db->update('tabel_sync', array('status_sync' => 1), array('id_sync' => 5, 'data_ke' => $no));

                $data_1 = $this->db->query("SELECT COALESCE(SUM(CASE WHEN status_sync = 0 THEN 1 ELSE 0 END), 0) as belum, COALESCE(SUM(CASE WHEN status_sync = 1 THEN 1 ELSE 0 END), 0) as sudah FROM tabel_sync WHERE id_sync = 5")->row();

                $total_1  = $data_1->sudah + $data_1->belum;
                $persen_1 = ($data_1->sudah / ($total_1 == 0 ? 1 : $total_1)) * 100;
                if ($persen_1 == 100) {
                    $this->db->update('tabel_download', array('status_download' => 1), array('id_download' => 5));
                }

                echo $persen_1;
            } else {
                echo $responseBody;
            }
        } else {
            echo 'No Response Body';
        }
    }

    public function download_6($no) {
        //master kelas
        $detail = $this->db->from('tabel_sync')->where('data_ke', $no)
            ->where('id_sync', 6)
            ->get()->row();
        if (!$detail) {
            echo 0;
            die();
        }

        $url = $this->status_cbt->alamat_server_cbt . 'home/download_6/' . $this->status_cbt->token_cbt . '/' . ($no * 30) . '/' . $this->status_cbt->id_server;
//        echo $url;

        $arrContextOptions = array(
            "ssl" => array(
                "verify_peer"      => false,
                "verify_peer_name" => false,
            ),
        );

        $responseBody = @file_get_contents($url, false, stream_context_create($arrContextOptions));

//        print_r($responseBody);

        if ($responseBody != "") {
            $json = json_decode($responseBody);
            if (isset($json->error) && $json->error == 0) {
                foreach ($json->siswa as $dbase) {
                    $this->db->insert('siswa', $dbase);
                }

                $this->db->update('tabel_sync', array('status_sync' => 1), array('id_sync' => 6, 'data_ke' => $no));

                $data_1 = $this->db->query("SELECT COALESCE(SUM(CASE WHEN status_sync = 0 THEN 1 ELSE 0 END), 0) as belum, COALESCE(SUM(CASE WHEN status_sync = 1 THEN 1 ELSE 0 END), 0) as sudah FROM tabel_sync WHERE id_sync = 6")->row();

                $total_1  = $data_1->sudah + $data_1->belum;
                $persen_1 = ($data_1->sudah / ($total_1 == 0 ? 1 : $total_1)) * 100;
                if ($persen_1 == 100) {
                    $this->db->update('tabel_download', array('status_download' => 1), array('id_download' => 6));
                }

                echo $persen_1;
            } else {
                echo $responseBody;
            }
        } else {
            echo 'No Response Body';
        }
    }

    public function download_7($no) {
        //master kelas
        $detail = $this->db->from('tabel_sync')->where('data_ke', $no)
            ->where('id_sync', 7)
            ->get()->row();
        if (!$detail) {
            echo 0;
            die();
        }

        $url = $this->status_cbt->alamat_server_cbt . 'home/download_7/' . $this->status_cbt->token_cbt . '/' . ($no * 30) . '/' . $this->status_cbt->id_server;
//        echo $url;

        $arrContextOptions = array(
            "ssl" => array(
                "verify_peer"      => false,
                "verify_peer_name" => false,
            ),
        );

        $responseBody = @file_get_contents($url, false, stream_context_create($arrContextOptions));

//        print_r($responseBody);

        if ($responseBody != "") {
            $json = json_decode($responseBody);
            if (isset($json->error) && $json->error == 0) {
                foreach ($json->paket_soal as $dbase) {
                    $this->db->insert('data_paket_soal', $dbase);
                }

                $this->db->update('tabel_sync', array('status_sync' => 1), array('id_sync' => 7, 'data_ke' => $no));

                $data_1 = $this->db->query("SELECT COALESCE(SUM(CASE WHEN status_sync = 0 THEN 1 ELSE 0 END), 0) as belum, COALESCE(SUM(CASE WHEN status_sync = 1 THEN 1 ELSE 0 END), 0) as sudah FROM tabel_sync WHERE id_sync = 7")->row();

                $total_1  = $data_1->sudah + $data_1->belum;
                $persen_1 = ($data_1->sudah / ($total_1 == 0 ? 1 : $total_1)) * 100;
                if ($persen_1 == 100) {
                    $this->db->update('tabel_download', array('status_download' => 1), array('id_download' => 7));
                }

                echo $persen_1;
            } else {
                echo $responseBody;
            }
        } else {
            echo 'No Response Body';
        }
    }

    public function download_8($no) {
        //master kelas
        $detail = $this->db->from('tabel_sync')->where('data_ke', $no)
            ->where('id_sync', 8)
            ->get()->row();
        if (!$detail) {
            echo 0;
            die();
        }

        $url = $this->status_cbt->alamat_server_cbt . 'home/download_8/' . $this->status_cbt->token_cbt . '/' . ($no * 30) . '/' . $this->status_cbt->id_server;
//        echo $url;

        $arrContextOptions = array(
            "ssl" => array(
                "verify_peer"      => false,
                "verify_peer_name" => false,
            ),
        );

        $responseBody = @file_get_contents($url, false, stream_context_create($arrContextOptions));

//        print_r($responseBody);

        $url_lokal = $this->status_cbt->alamat_server_cbt;
        $url_lokal = str_replace('https://', '', $url_lokal);
        $url_lokal = str_replace('http://', '', $url_lokal);
        $url_lokal = str_replace('/', '', $url_lokal);

        // $host = $_SERVER['HTTP_HOST'];
        $host = $this->status_cbt->url_pelaksana;
        $host = str_replace('https://', '', $host);
        $host = str_replace('http://', '', $host);
        $host = str_replace('/', '', $host);

        if ($responseBody != "") {
            $json = json_decode($responseBody);
            if (isset($json->error) && $json->error == 0) {
                foreach ($json->bank_soal as $dbase) {
                    $dbase->deskripsi_soal = str_replace($url_lokal, $host, $dbase->deskripsi_soal);
                    $dbase->deskripsi_soal = str_replace("https", "http", $dbase->deskripsi_soal);

                    $dbase->jawaban_a = str_replace($url_lokal, $host, $dbase->jawaban_a);
                    $dbase->jawaban_a = str_replace("https", "http", $dbase->jawaban_a);

                    $dbase->jawaban_b = str_replace($url_lokal, $host, $dbase->jawaban_b);
                    $dbase->jawaban_b = str_replace("https", "http", $dbase->jawaban_b);

                    $dbase->jawaban_c = str_replace($url_lokal, $host, $dbase->jawaban_c);
                    $dbase->jawaban_c = str_replace("https", "http", $dbase->jawaban_c);

                    $dbase->jawaban_d = str_replace($url_lokal, $host, $dbase->jawaban_d);
                    $dbase->jawaban_d = str_replace("https", "http", $dbase->jawaban_d);

                    $dbase->jawaban_e = str_replace($url_lokal, $host, $dbase->jawaban_e);
                    $dbase->jawaban_e = str_replace("https", "http", $dbase->jawaban_e);

                    $dbase->jawaban_mengurutkan = str_replace($url_lokal, $host, $dbase->jawaban_mengurutkan);
                    $dbase->jawaban_mengurutkan = str_replace("https", "http", $dbase->jawaban_mengurutkan);

                    $dbase->jawaban_menjodohkan = str_replace($url_lokal, $host, $dbase->jawaban_menjodohkan);
                    $dbase->jawaban_menjodohkan = str_replace("https", "http", $dbase->jawaban_menjodohkan);

                    $dbase->jawaban_bs_multi = str_replace($url_lokal, $host, $dbase->jawaban_bs_multi);
                    $dbase->jawaban_bs_multi = str_replace("https", "http", $dbase->jawaban_bs_multi);

                    $this->db->insert('bank_soal', $dbase);
                }

                $this->db->update('tabel_sync', array('status_sync' => 1), array('id_sync' => 8, 'data_ke' => $no));

                $data_1 = $this->db->query("SELECT COALESCE(SUM(CASE WHEN status_sync = 0 THEN 1 ELSE 0 END), 0) as belum, COALESCE(SUM(CASE WHEN status_sync = 1 THEN 1 ELSE 0 END), 0) as sudah FROM tabel_sync WHERE id_sync = 8")->row();

                $total_1  = $data_1->sudah + $data_1->belum;
                $persen_1 = ($data_1->sudah / ($total_1 == 0 ? 1 : $total_1)) * 100;
                if ($persen_1 == 100) {
                    $this->db->update('tabel_download', array('status_download' => 1), array('id_download' => 8));
                }

                echo $persen_1;
            } else {
                echo $responseBody;
            }
        } else {
            echo 'No Response Body';
        }
    }

    public function download_9($no) {
        //master kelas
        $detail = $this->db->from('tabel_sync')->where('data_ke', $no)
            ->where('id_sync', 9)
            ->get()->row();
        if (!$detail) {
            echo 0;
            die();
        }

        $url = $this->status_cbt->alamat_server_cbt . 'home/download_9/' . $this->status_cbt->token_cbt . '/' . ($no * 30) . '/' . $this->status_cbt->id_server;
//        echo $url;

        $arrContextOptions = array(
            "ssl" => array(
                "verify_peer"      => false,
                "verify_peer_name" => false,
            ),
        );

        $responseBody = @file_get_contents($url, false, stream_context_create($arrContextOptions));

//        print_r($responseBody);

        if ($responseBody != "") {
            $json = json_decode($responseBody);
            if (isset($json->error) && $json->error == 0) {
                foreach ($json->jadwal_ujian as $dbase) {
                    $this->db->insert('jadwal_ujian', $dbase);
                }

                $this->db->update('tabel_sync', array('status_sync' => 1), array('id_sync' => 9, 'data_ke' => $no));

                $data_1 = $this->db->query("SELECT COALESCE(SUM(CASE WHEN status_sync = 0 THEN 1 ELSE 0 END), 0) as belum, COALESCE(SUM(CASE WHEN status_sync = 1 THEN 1 ELSE 0 END), 0) as sudah FROM tabel_sync WHERE id_sync = 9")->row();

                $total_1  = $data_1->sudah + $data_1->belum;
                $persen_1 = ($data_1->sudah / ($total_1 == 0 ? 1 : $total_1)) * 100;
                if ($persen_1 == 100) {
                    $this->db->update('tabel_download', array('status_download' => 1), array('id_download' => 9));
                }

                echo $persen_1;
            } else {
                echo $responseBody;
            }
        } else {
            echo 'No Response Body';
        }
    }

    public function download_10($no) {
        //master kelas
        $detail = $this->db->from('tabel_sync')->where('data_ke', $no)
            ->where('id_sync', 10)
            ->get()->row();
        if (!$detail) {
            echo 0;
            die();
        }

        $url = $this->status_cbt->alamat_server_cbt . 'home/download_10/' . $this->status_cbt->token_cbt . '/' . ($no * 30) . '/' . $this->status_cbt->id_server;
//        echo $url;

        $arrContextOptions = array(
            "ssl" => array(
                "verify_peer"      => false,
                "verify_peer_name" => false,
            ),
        );

        $responseBody = @file_get_contents($url, false, stream_context_create($arrContextOptions));

//        print_r($responseBody);

        if ($responseBody != "") {
            $json = json_decode($responseBody);
            if (isset($json->error) && $json->error == 0) {
                foreach ($json->detail_jadwal_ujian as $dbase) {
                    $this->db->insert('detail_jadwal_ujian', $dbase);
                }

                $this->db->update('tabel_sync', array('status_sync' => 1), array('id_sync' => 10, 'data_ke' => $no));

                $data_1 = $this->db->query("SELECT COALESCE(SUM(CASE WHEN status_sync = 0 THEN 1 ELSE 0 END), 0) as belum, COALESCE(SUM(CASE WHEN status_sync = 1 THEN 1 ELSE 0 END), 0) as sudah FROM tabel_sync WHERE id_sync = 9")->row();

                $total_1  = $data_1->sudah + $data_1->belum;
                $persen_1 = ($data_1->sudah / ($total_1 == 0 ? 1 : $total_1)) * 100;
                if ($persen_1 == 100) {
                    $this->db->update('tabel_download', array('status_download' => 1), array('id_download' => 10));
                }

                echo $persen_1;
            } else {
                echo $responseBody;
            }
        } else {
            echo 'No Response Body';
        }
    }

    public function download_11($no) {
        //master kelas
        $detail = $this->db->from('tabel_sync')->where('data_ke', $no)
            ->where('id_sync', 11)
            ->get()->row();
        if (!$detail) {
            echo 0;
            die();
        }

        $url = $this->status_cbt->alamat_server_cbt . 'home/download_11/' . $this->status_cbt->token_cbt . '/' . ($no * 30) . '/' . $this->status_cbt->id_server;
//        echo $url;

        $arrContextOptions = array(
            "ssl" => array(
                "verify_peer"      => false,
                "verify_peer_name" => false,
            ),
        );

        $responseBody = @file_get_contents($url, false, stream_context_create($arrContextOptions));

//        print_r($responseBody);

        if ($responseBody != "") {
            $json = json_decode($responseBody);
            if (isset($json->error) && $json->error == 0) {
                foreach ($json->detail_paket_soal as $dbase) {
                    $this->db->insert('detail_paket_soal', $dbase);
                }

                $this->db->update('tabel_sync', array('status_sync' => 1), array('id_sync' => 11, 'data_ke' => $no));

                $data_1 = $this->db->query("SELECT COALESCE(SUM(CASE WHEN status_sync = 0 THEN 1 ELSE 0 END), 0) as belum, COALESCE(SUM(CASE WHEN status_sync = 1 THEN 1 ELSE 0 END), 0) as sudah FROM tabel_sync WHERE id_sync = 11")->row();

                $total_1  = $data_1->sudah + $data_1->belum;
                $persen_1 = ($data_1->sudah / ($total_1 == 0 ? 1 : $total_1)) * 100;
                if ($persen_1 == 100) {
                    $this->db->update('tabel_download', array('status_download' => 1), array('id_download' => 11));
                }

                echo $persen_1;
            } else {
                echo $responseBody;
            }
        } else {
            echo 'No Response Body';
        }
    }

    public function download_12($no) {
        //master kelas
        $detail = $this->db->from('tabel_sync')->where('data_ke', $no)
            ->where('id_sync', 12)
            ->get()->row();
        if (!$detail) {
            echo 0;
            die();
        }

        $url = $this->status_cbt->alamat_server_cbt . 'home/download_12/' . $this->status_cbt->token_cbt . '/' . ($no * 30) . '/' . $this->status_cbt->id_server;
//        echo $url;

        $arrContextOptions = array(
            "ssl" => array(
                "verify_peer"      => false,
                "verify_peer_name" => false,
            ),
        );

        $responseBody = @file_get_contents($url, false, stream_context_create($arrContextOptions));

//        print_r($responseBody);

        if ($responseBody != "") {
            $json = json_decode($responseBody);
            if (isset($json->error) && $json->error == 0) {
                foreach ($json->master_jenjang_pendidikan as $dbase) {
                    $this->db->insert('master_jenjang_pendidikan', $dbase);
                }

                $this->db->update('tabel_sync', array('status_sync' => 1), array('id_sync' => 12, 'data_ke' => $no));

                $data_1 = $this->db->query("SELECT COALESCE(SUM(CASE WHEN status_sync = 0 THEN 1 ELSE 0 END), 0) as belum, COALESCE(SUM(CASE WHEN status_sync = 1 THEN 1 ELSE 0 END), 0) as sudah FROM tabel_sync WHERE id_sync = 11")->row();

                $total_1  = $data_1->sudah + $data_1->belum;
                $persen_1 = ($data_1->sudah / ($total_1 == 0 ? 1 : $total_1)) * 100;
                if ($persen_1 == 100) {
                    $this->db->update('tabel_download', array('status_download' => 1), array('id_download' => 12));
                }

                echo $persen_1;
            } else {
                echo $responseBody;
            }
        } else {
            echo 'No Response Body';
        }
    }

    private function deleteDirectory($dir) {
        if (!file_exists($dir)) {
            return true;
        }

        if (!is_dir($dir)) {
            return unlink($dir);
        }

        foreach (scandir($dir) as $item) {
            if ($item == '.' || $item == '..') {
                continue;
            }

            if (!$this->deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
                return false;
            }

        }

        return rmdir($dir);
    }

    public function download_13($no = 0) {
        //master kelas
        $detail = $this->db->from('tabel_sync')->where('data_ke', $no)
            ->where('id_sync', 13)
            ->get()->row();
        if (!$detail) {
            //echo 0;
            //die();

            // Set the path of the folder to replace
            $folderPath = 'assets/uploads';

            // Set the path of the temporary directory to extract the zip file
            $tempDir = 'assets/uploads';

            $this->deleteDirectory($tempDir . "/soal");

            //download from raw
            // Set the URL of the zip file to download
            $url = $this->status_cbt->alamat_server_cbt . 'assets/uploads/soal_assets.zip';

// Download the zip file
            $zipContents = file_get_contents($url);

// Save the zip file to a temporary location
            $tempZipPath = $tempDir . '/archive.zip';
            file_put_contents($tempZipPath, $zipContents);

// Extract the contents of the zip file to the temporary directory
            $zip = new ZipArchive();
            if ($zip->open($tempZipPath) === true) {
                $zip->extractTo($tempDir);
                $zip->close();
            }

// Replace the contents of the specified folder with the contents of the temporary directory
            // $files = glob($tempDir . '/*');
            // foreach ($files as $file) {
            //     $basename = basename($file);
            //     $dest     = $folderPath . '/' . $basename;
            //     if (is_file($file)) {
            //         copy($file, $dest);
            //     } elseif (is_dir($file)) {
            //         $this->deleteDirectory($dest);
            //         // rmdir($dest);
            //         rename($file, $dest);
            //     }
            // }

// Remove the temporary directory and zip file
            // array_map('unlink', glob($tempDir . '/*'));
            // rmdir($tempDir);
            unlink($tempZipPath);

            $this->db->update('tabel_download', array('status_download' => 1), array('id_download' => 13));

            echo "100";
            die();
        }

        $bank = $this->db->from('bank_soal')
            ->or_where('audio_file <>', '')
            ->or_where('video_file <>', '')
            ->limit(1, $no)
            ->get()->row();

        if ($bank) {
            $path = $this->status_cbt->alamat_server_cbt . 'assets/';
            if ($bank->video_file != '') {
                //download VIdeo File
                $this->downloadFile($path . 'video/' . $bank->video_file, 'assets/video/' . $bank->video_file);
            }

            if ($bank->audio_file) {
                $this->downloadFile($path . 'audio/' . $bank->audio_file, 'assets/audio/' . $bank->audio_file);
            }

            $this->db->update('tabel_sync', array('status_sync' => 1), array('id_sync' => 13, 'data_ke' => $no));

            $data_1 = $this->db->query("SELECT COALESCE(SUM(CASE WHEN status_sync = 0 THEN 1 ELSE 0 END), 0) as belum, COALESCE(SUM(CASE WHEN status_sync = 1 THEN 1 ELSE 0 END), 0) as sudah FROM tabel_sync WHERE id_sync = 13")->row();

            $total_1  = $data_1->sudah + $data_1->belum;
            $persen_1 = ($data_1->sudah / ($total_1 == 0 ? 1 : $total_1)) * 100;
            if ($persen_1 == 100) {
                $this->db->update('tabel_download', array('status_download' => 1), array('id_download' => 13));
            }

            echo $persen_1;
        } else {
            echo 'GAGAL DOWNLOAD';
        }
    }

    public function sync_data_1($token) {
        $id_kelas = $this->input->post('id');
        $url      = $this->status_cbt->alamat_server_cbt . '/home/get_data_1/' . $token . '/' . $id_kelas;

        //print_r($url);

        $hasil = @file_get_contents($url);

        $json = json_decode($hasil);

        if ($json->status == 'OK') {
            $in               = array();
            $in['id_kelas']   = $json->data->id_kelas;
            $in['nama_kelas'] = $json->data->nama_kelas;

            $this->db->insert('master_kelas', $in);

            $sekolah                 = array();
            $sekolah['nama_sekolah'] = $json->sekolah->nama_sekolah;
            $sekolah['npsn']         = $json->sekolah->nss;

            $this->db->update('status_cbt', $sekolah);

            echo 'OK';
        } else {
            echo 'GAGAL';
        }
    }

    public function trunc_data_2($token) {
        $this->db->query('TRUNCATE master_jurusan');
    }

    public function sync_data_2($token) {
        $id_jurusan = $this->input->post('id');
        $url        = $this->status_cbt->alamat_server_cbt . '/home/get_data_2/' . $token . '/' . $id_jurusan;

        //print_r($url);

        $hasil = @file_get_contents($url);

        $json = json_decode($hasil);

        if ($json->status == 'OK') {
            $in                 = array();
            $in['id_jurusan']   = $json->data->id_jurusan;
            $in['nama_jurusan'] = $json->data->nama_jurusan;

            $this->db->insert('master_jurusan', $in);

            echo 'OK';
        } else {
            echo 'GAGAL';
        }
    }

    public function trunc_data_3($token) {
        $this->db->query('TRUNCATE mata_pelajaran');
    }

    public function sync_data_3($token) {
        $id_mata_pelajaran = $this->input->post('id');
        $url               = $this->status_cbt->alamat_server_cbt . '/home/get_data_3/' . $token . '/' . $id_mata_pelajaran;

        //print_r($url);

        $hasil = @file_get_contents($url);

        $json = json_decode($hasil);

        if ($json->status == 'OK') {
            $in  = array();
            $cek = $this->db->from('mata_pelajaran')->where('id_mata_pelajaran', $id_mata_pelajaran)->get()->row();
            if ($cek) {
                $in['nama_mata_pelajaran'] = $json->data->nama_mata_pelajaran;

                $this->db->where('id_mata_pelajaran', $id_mata_pelajaran);
                $this->db->update('mata_pelajaran', $in);
            } else {
                $in['id_mata_pelajaran']   = $json->data->id_mata_pelajaran;
                $in['nama_mata_pelajaran'] = $json->data->nama_mata_pelajaran;

                $this->db->insert('mata_pelajaran', $in);
            }

            echo 'OK';
        } else {
            echo 'GAGAL';
        }
    }

    public function trunc_data_4($token) {
        $this->db->query('TRUNCATE materi_pelajaran');
    }

    public function sync_data_4($token) {
        $id_materi = $this->input->post('id');
        $url       = $this->status_cbt->alamat_server_cbt . '/home/get_data_4/' . $token . '/' . $id_materi;

        //print_r($url);

        $hasil = @file_get_contents($url);

        $json = json_decode($hasil);

        if ($json->status == 'OK') {

            $this->db->insert('materi_pelajaran', $json->data);

            echo 'OK';
        } else {
            echo 'GAGAL';
        }
    }

    public function trunc_data_5($token) {
        $this->db->query('TRUNCATE jenis_ujian');
    }

    public function sync_data_5($token) {
        $id_materi = $this->input->post('id');
        $url       = $this->status_cbt->alamat_server_cbt . '/home/get_data_5/' . $token . '/' . $id_materi;

        //print_r($url);

        $hasil = @file_get_contents($url);

        $json = json_decode($hasil);

        if ($json->status == 'OK') {

            $this->db->insert('jenis_ujian', $json->data);

            echo 'OK';
        } else {
            echo 'GAGAL';
        }
    }

    public function trunc_data_6($token) {
        $this->db->query('TRUNCATE siswa');
    }

    public function sync_data_6() {
        $url = $this->status_cbt->alamat_server_cbt . '/home/sync_data_6/' . $this->status_cbt->token_cbt . '/' . $this->status_cbt->id_server;

        //print_r($url);

        $hasil = @file_get_contents($url);

        $json = json_decode($hasil);

//        print_r($json);

        if ($json->jumlah_data > 0) {
            //cek apakah ada data siswa
            $this->db->insert_batch('siswa', $json->data);

            echo json_encode(array('status' => 'OK'));
        } else {
            echo json_encode(array('status' => 'GAGAL'));
        }
    }

    public function trunc_data_7($token) {
        $this->db->query('TRUNCATE data_paket_soal');
    }

    public function sync_data_7($token) {
        $id_peserta = $this->input->post('id');

        $url = $this->status_cbt->alamat_server_cbt . '/home/get_data_7/' . $token . '/' . $id_peserta;

        //print_r($url);

        $hasil = @file_get_contents($url);

        $json = json_decode($hasil);

        if ($json->status == 'OK') {
            $this->db->insert('data_paket_soal', $json->data);

            echo 'OK';
        } else {
            echo 'GAGAL';
        }
    }

    public function trunc_data_8($token) {
        $this->db->query('TRUNCATE bank_soal');
    }

    /**
     * BANK SOAL
     */
    public function sync_data_8($token, $id_soal) {
        $url = $this->status_cbt->alamat_server_cbt . '/home/get_data_8/' . $this->status_cbt->token_cbt . '/' . $id_soal;

//        $ch = curl_init();
        //        $timeout = 15;
        //
        //        curl_setopt($ch, CURLOPT_URL, $url);
        //        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        //
        //        $lines_string = curl_exec($ch);
        //        curl_close($ch);

        $hasil = @file_get_contents($url);

//        $json = json_decode($lines_string);
        $json = json_decode($hasil);

        if ($json->status == 'OK') {
            $this->db->insert('bank_soal', $json->data);

            echo 'OK';
        } else {
            echo 'GAGAL';
        }
    }

    public function trunc_data_9($token) {
        $this->db->query('TRUNCATE jadwal_ujian');
    }

    public function sync_data_9($token) {
        $id_peserta = $this->input->post('id');
        $url        = $this->status_cbt->alamat_server_cbt . '/home/get_data_9/' . $token . '/' . $id_peserta;

        //print_r($url);

        $hasil = @file_get_contents($url);

        $json = json_decode($hasil);

        if ($json->status == 'OK') {
            $this->db->insert('jadwal_ujian', $json->data);

            echo 'OK';
        } else {
            echo 'GAGAL';
        }
    }

    public function trunc_data_10($token) {
        $this->db->query('TRUNCATE detail_jadwal_ujian');
    }

    public function sync_data_10($token) {
        $id_peserta = $this->input->post('id');
        $url        = $this->status_cbt->alamat_server_cbt . '/home/get_data_10/' . $token . '/' . $id_peserta;

        //print_r($url);

        $hasil = @file_get_contents($url);

        $json = json_decode($hasil);

        if ($json->status == 'OK') {
            $this->db->insert('detail_jadwal_ujian', $json->data);

            echo 'OK';
        } else {
            echo 'GAGAL';
        }
    }

    public function trunc_data_11($token) {
        $this->db->query('TRUNCATE detail_paket_soal');
    }

    public function sync_data_11($token) {
        $id_peserta = $this->input->post('id');
        $url        = $this->status_cbt->alamat_server_cbt . '/home/get_data_11/' . $token . '/' . $id_peserta;

        //print_r($url);
        //        $hasil = @file_get_contents($url);
        //
        //        $json = json_decode($hasil);

        $ch      = curl_init();
        $timeout = 15;

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

// Get URL content
        $lines_string = curl_exec($ch);
// close handle to release resources
        curl_close($ch);
//output, you can also save it locally on the server
        //echo $lines_string;
        // die();

        $json = json_decode($lines_string);

        if ($json->status == 'OK') {
            $this->db->insert('detail_paket_soal', $json->data);

            echo 'OK';
        } else {
            echo 'GAGAL';
        }
    }

    public function trunc_data_12($token) {
        $this->db->query('TRUNCATE master_jenjang_pendidikan');
    }

    public function sync_data_12($token) {
        $id_peserta = $this->input->post('id');
        $url        = $this->status_cbt->alamat_server_cbt . '/home/get_data_12/' . $token . '/' . $id_peserta;

        //print_r($url);

        $hasil = @file_get_contents($url);

        $json = json_decode($hasil);

        if ($json->status == 'OK') {
            $this->db->insert('master_jenjang_pendidikan', $json->data);

            echo 'OK';
        } else {
            echo 'GAGAL';
        }
    }

    public function patch() {
        $pesan   = '';
        $pesan_2 = '';
        if ($this->input->post('save') != '') {
            $config['upload_path']   = './patch/';
            $config['allowed_types'] = '|txt|csv';
            $config['max_size']      = 200000;
            $config['overwrite']     = TRUE;

            $this->load->library('upload', $config);

            if (!$this->upload->do_upload('import')) {
                $pesan = $this->upload->display_errors();
            } else {
                //$pesan = 'file Berhasil di upload, silahkan proses restore dengan menu di samping';
                $media         = $this->upload->data();
                $inputFileName = './patch/' . $media['file_name'];

                $isi = @file_get_contents($inputFileName);
                $isi = $this->rc4("jajan", $isi);
                if (filter_var($isi, FILTER_VALIDATE_URL)) {
                    $pesan = 'ISI: ' . $isi;

                    $array = array(
                        'alamat_server_cbt' => $isi,
                    );

                    $this->db->update('status_cbt', $array);

                    $pesan = "PATCH BERHASIL";
                } else {
                    $pesan = "HARAP UPLOAD FILE PATCH YANG BENAR";
                }
            }
        }

        if ($this->input->post('save_text') != '') {
            $config['upload_path']   = './patch/';
            $config['allowed_types'] = 'txt|csv';
            $config['max_size']      = 200000;
            $config['overwrite']     = TRUE;

            $this->load->library('upload', $config);

            if (!$this->upload->do_upload('import_text')) {
                $pesan_2 = $this->upload->display_errors();
                print_r($this->upload->data());
            } else {
                //$pesan = 'file Berhasil di upload, silahkan proses restore dengan menu di samping';
                $media         = $this->upload->data();
                $inputFileName = './patch/' . $media['file_name'];

                $isi = @file_get_contents($inputFileName);
                $isi = $this->rc4("jajan", $isi);

                if (!$this->db->simple_query($isi)) {
                    $pesan_2 = "FILE PATCH SUDAH PERNAH DI EKSEKUSI ATAU ANDA MEMASUKAN FILE PATCH YANG SALAH";
                } else {
                    $pesan_2 = "PATCH BERHASIL";
                }
            }
        }

        $output            = array();
        $output['pesan']   = $pesan;
        $output['pesan_2'] = $pesan_2;

        $this->render_page($output, 'admin/template/patch');
    }

    public function update_aplikasi() {
        $this->render_page([], 'admin/template/update');
    }

    public function do_update() {
        // Cek apakah ekstensi zip dan curl ada
        if (!extension_loaded('zip') || !function_exists('curl_version')) {
            echo json_encode(['status' => 'error', 'message' => 'ZIP or cURL is not enabled on the server.']);
            return;
        }

        $history_update = $this->db->from('history_update')
        ->where('status_update', 'Menunggu Install')
        ->order_by('waktu_update', 'desc')->get()->row();

        if(!$history_update) {
            echo json_encode(['status' => 'error', 'message' => 'Tidak ada update.']);
            die();
        }

        // Dapatkan URL untuk update berdasarkan waktu terakhir update
        $server_update = $this->status_cbt->alamat_server_cbt . 'home/get_update/' . $this->status_cbt->token_cbt . '/' . $history_update->nama_file;

        // Menggunakan cURL untuk memeriksa tipe file dari URL
        $ch = curl_init($server_update);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_NOBODY, true); // Hanya memeriksa header, tanpa mendownload konten
        curl_exec($ch);
        $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
        curl_close($ch);

        // Periksa apakah tipe konten adalah file ZIP
        if (strpos($content_type, 'zip') === false) {
            echo json_encode(['status' => 'error', 'message' => 'The server did not return a ZIP file.']);
            return;
        }

        // Jika file adalah ZIP, lanjutkan ke proses pengunduhan dan ekstraksi
        // Menggunakan cURL untuk mengakses server dan mendapatkan file update
        $ch = curl_init($server_update);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $update_link = curl_exec($ch);
        curl_close($ch);

        //cek apakah ada file atau tidak/ url ada atau tidak
        if (!$update_link) {
            echo json_encode(['status' => 'error', 'message' => 'Failed to retrieve update file link from server.']);
            return;
        }

        // Tentukan folder tempat update diekstrak
        $extract_to = './';

        // Membuat folder jika belum ada
        if (!is_dir($extract_to)) {
            mkdir($extract_to, 0755, true);
        }

        // Download file update menggunakan cURL
        $update_file = $extract_to . 'update.zip';

        $ch = curl_init($server_update);

// Buka file untuk menulis data
        $fp = fopen($update_file, 'wb'); // Menyimpan file yang didownload ke lokasi yang sudah ditentukan

// Set opsi cURL
        curl_setopt($ch, CURLOPT_FILE, $fp); // Set file output
        curl_setopt($ch, CURLOPT_HEADER, 0); // Jangan sertakan header dalam respons

// Eksekusi cURL untuk mendownload file
        curl_exec($ch);

        // Periksa apakah file zip berhasil diunduh
        if (!file_exists($update_file)) {
            echo json_encode(['status' => 'error', 'message' => 'Failed to download update file.']);
            return;
        }

        // Ekstrak file zip ke folder tujuan
        $zip = new ZipArchive;
        if ($zip->open($update_file) === true) {
            // Cek apakah file ZIP valid
            if ($zip->numFiles === 0) {
                echo json_encode(['status' => 'error', 'message' => 'The ZIP file is empty.']);
                return;
            }

            // Coba ekstrak file ZIP
            $extraction_result = $zip->extractTo($extract_to);
            if ($extraction_result) {
                $zip->close();
                unlink($update_file); // Hapus file zip setelah ekstraksi selesai
                $this->db->update('status_cbt', ['last_update' => date('Y-m-d H:i:s')]);
                
                $this->db->where('id', $history_update->id);
                $this->db->update('history_update', ['status_update' => "Berhasil", 'tanggal_install'=> date('Y-m-d H:i:s')]);

                echo json_encode(['status' => 'success', 'message' => 'Update successful.']);
            } else {
                $zip->close();
                echo json_encode(['status' => 'error', 'message' => 'Failed to extract update file. Extraction failed.']);
            }
        } else {
            // Menampilkan alasan kegagalan membuka file ZIP
            echo json_encode(['status' => 'error', 'message' => 'Failed to open ZIP file. Error: ' . $zip->getStatusString()]);
        }
    }

    public function cek_update() {
        // Dapatkan URL untuk update berdasarkan waktu terakhir update
        $server_update = $this->status_cbt->alamat_server_cbt . 'home/cek_update/' . $this->status_cbt->token_cbt;

        // Inisialisasi cURL
        $ch = curl_init();

        // Set opsi cURL
        curl_setopt($ch, CURLOPT_URL, $server_update); // Set URL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Mengembalikan hasil sebagai string
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Set timeout (10 detik)

        // Eksekusi cURL dan ambil hasilnya
        $response = curl_exec($ch);

        // Cek jika terjadi kesalahan
        if (curl_errno($ch)) {
            // Tangani kesalahan cURL
            $error_msg = curl_error($ch);
            curl_close($ch);
            return [
                'status'  => 'error',
                'message' => 'cURL Error: ' . $error_msg,
            ];
        }

        // Tutup cURL
        curl_close($ch);

        // Decode hasil JSON jika ada
        $data = json_decode($response, true);

        // Cek apakah data berhasil diambil
        if (isset($data['status']) && $data['status'] === 'ada') {
            // Ambil data yang diperlukan dari respons
            // Misalnya, jika ada data update

            if (isset($data['list_update'])) {
                foreach ($data['list_update'] as $update) {
                    $cek = $this->db->from('history_update')->where('nama_file', $update['file_update'])->get()->row();
                    if (!$cek) {
                        $this->db->insert('history_update', [
                            'waktu_update'      => $update['tanggal_update'],
                            'nama_file'         => $update['file_update'],
                            'keterangan_update' => $update['keterangan_update'],
                            'status_update'     => 'Menunggu Install',
                            'tanggal_install'   => null,
                        ]);
                    }
                }
            }

            $total_update = $this->db->from('history_update')->where('status_update', 'Menunggu Install')->get()->num_rows();

            // Lakukan sesuatu dengan data update
            $out = [
                'status'  => 'ada',
                'message' => $total_update > 0 ? "Ada (" . $total_update . ") Update" : "Up to date",
            ];
        } else {
            // Jika status tidak success
            $out = [
                'status'  => 'error',
                'message' => 'Update check failed or no updates available.',
            ];
        }

        echo json_encode($out);
    }

    private function rc4($key, $str) {
        $s = array();
        for ($i = 0; $i < 256; $i++) {
            $s[$i] = $i;
        }
        $j = 0;
        for ($i = 0; $i < 256; $i++) {
            $j     = ($j + $s[$i] + ord($key[$i % strlen($key)])) % 256;
            $x     = $s[$i];
            $s[$i] = $s[$j];
            $s[$j] = $x;
        }
        $i   = 0;
        $j   = 0;
        $res = '';
        for ($y = 0; $y < strlen($str); $y++) {
            $i     = ($i + 1) % 256;
            $j     = ($j + $s[$i]) % 256;
            $x     = $s[$i];
            $s[$i] = $s[$j];
            $s[$j] = $x;
            $res .= $str[$y] ^ chr($s[($s[$i] + $s[$j]) % 256]);
        }
        return $res;
    }

    public function atur_data_server() {
        //redirect('admin');
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('status_cbt');
        $crud->set_subject('Pengaturan ID Server');

        $crud->required_fields('token_cbt');

        $crud->unset_read();
        $crud->unset_add();
        $crud->unset_export();
        $crud->unset_print();
        $crud->unset_delete();

        $crud->unset_columns('alamat_server_cbt', 'id_status_cbt', 'kode_unix', 'status_sync', 'terakhir_sync', 'data_master', 'siswa', 'soal', 'jadwal_ujian');
        $crud->unset_edit_fields('alamat_server_cbt', 'id_status_cbt', 'kode_unix', 'status_sync', 'terakhir_sync', 'data_master', 'siswa', 'soal', 'jadwal_ujian');

        $output = $crud->render();

        $this->title = 'ID Server';
        $this->render_page($output, 'admin/template/crud');
    }

    public function master_jenjang_pendidikan() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('master_jenjang_pendidikan');
        $crud->set_subject('Jenjang Pendidikan');

        $crud->unset_operations();

        $crud->required_fields('jenjang_pendidikan');

        $output = $crud->render();

        $this->title = 'Kelola Jenjang Pendidikan';
        $this->render_page($output, 'admin/template/crud');
    }

    public function master_jurusan() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('master_jurusan');
        $crud->set_subject('Jurusan');

        $crud->required_fields('nama_jurusan');

        $crud->unset_operations();

        $output = $crud->render();

        $this->title = 'Kelola Data Jurusan';
        $this->render_page($output, 'admin/template/crud');
    }

    public function master_kelas() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('master_kelas');
        $crud->set_subject('Kelas');

        $crud->required_fields('nama_kelas');

        $crud->unset_operations();

        $output = $crud->render();

        $this->title = 'Kelola Data Kelas';
        $this->render_page($output, 'admin/template/crud');
    }

    public function siswa() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('siswa');
        $crud->set_subject('Data Siswa');

        $crud->set_primary_key('kode_unix_sekolah', 'master_sekolah');
        $crud->set_relation('kelas', 'master_kelas', 'nama_kelas');
        $crud->set_relation('jurusan', 'master_jurusan', 'nama_jurusan');
        $crud->set_relation('jenjang_pendidikan', 'master_jenjang_pendidikan', 'nama_jenjang_pendidikan');
        $crud->unique_fields('username', 'password');

        $crud->required_fields('username', 'password');

        $crud->set_field_upload('photo', 'assets/uploads/siswa/');

        $crud->display_as('jenis_kelamin', 'JK');
        $crud->display_as('ruang_ujian', 'ID Server');

        $crud->edit_fields('no_peserta', 'no_induk', 'nama_lengkap', 'username', 'password');

        $crud->field_type('no_peserta', 'readonly');
        $crud->field_type('no_induk', 'readonly');
        $crud->field_type('nama_lengkap', 'readonly');
        // $crud->field_type('username', 'readonly');

//        $crud->add_action('Cetak Kartu', 'tambah.png', 'panel/kartu_ujian');

        $crud->unset_columns('kode_unix', 'sekolah');

        $crud->unset_add();
        $crud->unset_delete();
        $crud->unset_read();
        $crud->unset_export();
        $crud->unset_print();

        $output = $crud->render();

        $this->title = 'Kelola Data Siswa';
        $this->render_page($output, 'admin/template/crud');
    }

    public function mapel() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('mata_pelajaran');
        $crud->set_subject('Mata Pelajaran');

        $crud->required_fields('mata_pelajaran');
        $crud->unique_fields('mata_pelajaran');

        $crud->unset_operations();

        $output = $crud->render();

        $this->title = 'Kelola Mata Pelajaran';
        $this->render_page($output, 'admin/template/crud');
    }

    public function mapel_materi() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('materi_pelajaran');
        $crud->set_subject('Materi Pelajaran');
        $crud->order_by('mata_pelajaran');

        $crud->set_relation('mata_pelajaran', 'mata_pelajaran', 'nama_mata_pelajaran');
        $crud->set_relation('kelas', 'master_kelas', 'nama_kelas');
        $crud->set_relation('jurusan', 'master_jurusan', 'nama_jurusan');
        $crud->set_relation('jenjang_pendidikan', 'master_jenjang_pendidikan', 'nama_jenjang_pendidikan');

        $crud->required_fields('mata_pelajaran', 'kelas', 'jurusan', 'jenjang_pendidikan', 'deskripsi_materi', 'bobot_soal');

        $crud->unset_operations();

        $output = $crud->render();

        $this->title = 'Kelola Materi Pelajaran';
        $this->render_page($output, 'admin/template/crud');
    }

    public function ujian_jadwal() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('jadwal_ujian');
        $crud->set_subject('Jadwal Ujian');
        $crud->set_relation('jenis_ujian', 'jenis_ujian', 'nama_jenis_ujian');
        $crud->set_relation('jenjang_pendidikan', 'master_jenjang_pendidikan', 'nama_jenjang_pendidikan');

        $crud->add_action('Mata Pelajaran', 'hapus.png', 'admin/detail_pelajaran_ujian');

        $crud->required_fields('nama_jadwal_ujian', 'jenjang_pendidikan', 'aktif');
        $crud->unique_fields('nama_jadwal_ujian');

        //$crud->unset_operations();

        $output = $crud->render();

        $this->title = 'Kelola Jadwal Ujian';
        $this->render_page($output, 'admin/template/crud');
    }

    public function detail_pelajaran_ujian($id_jadwal_ujian = '') {
        if ($id_jadwal_ujian == '') {
            redirect('panel/jadwal_ujian');
        }

        $this->load->model('msite');
        $detail_jadwal = $this->db->from('jadwal_ujian')
            ->where('id_jadwal_ujian', $id_jadwal_ujian)
            ->join('jenis_ujian', 'id_jenis_ujian=jenis_ujian', 'LEFT')
            ->join('master_jenjang_pendidikan', 'id_jenjang_pendidikan=jenjang_pendidikan', 'LEFT')
            ->limit(1)
            ->get()
            ->row();

        if (!$detail_jadwal) {
            redirect('admin/ujian_jadwal');
        }

        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('detail_jadwal_ujian');
        $crud->set_subject('Mata Pelajaran');
        $crud->where('jadwal_ujian', $id_jadwal_ujian);
        $crud->order_by('tanggal_pelaksanaan');

        $crud->field_type('jadwal_ujian', 'hidden', $id_jadwal_ujian);

        $crud->set_relation('mata_pelajaran', 'mata_pelajaran', 'nama_mata_pelajaran');
        $crud->set_relation('kelas', 'master_kelas', 'nama_kelas');
        $crud->set_relation('jurusan', 'master_jurusan', 'nama_jurusan');

        $crud->columns('mata_pelajaran', 'keterangan', 'kelas', 'jurusan', 'tanggal_pelaksanaan', 'ditutup', 'lama_ujian', 'daftar_hadir', 'berita_acara', 'monitoring');
        $crud->required_fields('mata_pelajaran', 'kelas', 'tanggal_pelaksanaan', 'ditutup', 'lama_ujian');

        $crud->callback_column('monitoring', array($this, '_callback_monitoring'));
        $crud->callback_column('daftar_hadir', array($this, '_callback_daftar_hadir'));
        $crud->callback_column('berita_acara', array($this, '_callback_berita_acara'));

        $output = $crud->render();

        $output->jadwal = $detail_jadwal;

        $this->render_page($output, 'admin/template/detail_pelajaran_ujian');
    }

    public function monitoring_ujian_ujian($id_jadwal_ujian = '') {
        if ($id_jadwal_ujian == '') {
            redirect('panel/jadwal_ujian');
        }

        $detail_paket = $this->db->select('*, NOW() as sekarang')
            ->from('detail_jadwal_ujian')
            ->where('id_detail_jadwal_ujian', $id_jadwal_ujian)
            ->join('jadwal_ujian', 'jadwal_ujian = id_jadwal_ujian', 'LEFT')
            ->join('mata_pelajaran', 'mata_pelajaran= id_mata_pelajaran', 'LEFT')
            ->join('master_kelas', 'kelas= id_kelas', 'LEFT')
            ->get()
            ->row();

        if (!$detail_paket) {
            redirect('admin/ujian_jadwal');
        }

        $output['jadwal'] = $detail_paket;

        $this->render_page($output, 'admin/template/monitoring_ujian_ujian');
    }

    public function download_snapshoot($id_ujian_dilaksanakan) {
        $this->load->helper('download'); // Helper untuk unduhan

        // Path folder yang berisi snapshoot
        $folder = FCPATH . 'assets/snapshoots/' . $id_ujian_dilaksanakan;

        // Periksa apakah folder ada
        if (!is_dir($folder)) {
            show_404(); // Jika folder tidak ditemukan, tampilkan halaman 404
            return;
        }

        // Buat file ZIP
        $zip      = new ZipArchive();
        $zip_file = tempnam(sys_get_temp_dir(), 'snapshots_') . '.zip';

        if ($zip->open($zip_file, ZipArchive::CREATE) !== true) {
            echo "Tidak dapat membuat file ZIP.";
            return;
        }

        // Tambahkan semua file dalam folder ke ZIP
        $files = array_diff(scandir($folder), ['.', '..']);
        foreach ($files as $file) {
            $file_path = $folder . '/' . $file;
            if (is_file($file_path)) {
                $zip->addFile($file_path, $file); // Tambahkan file ke ZIP
            }
        }

        $zip->close();

        // Header unduhan
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="snapshots_' . $id_ujian_dilaksanakan . '.zip"');
        header('Content-Length: ' . filesize($zip_file));

        // Kirim file ZIP ke pengguna
        readfile($zip_file);

        // Hapus file ZIP sementara
        unlink($zip_file);
    }

    public function ujian_jenis() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('jenis_ujian');
        $crud->set_subject('Jenis Ujian');

        $crud->required_fields('nama_jenis_ujian');
        $crud->unique_fields('nama_jenis_ujian');
        $output = $crud->render();

        $this->title = 'Kelola Jenis Ujian';
        $this->render_page($output, 'admin/template/crud');
    }

    public function atur_kartu() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('setting_kartu');
        $crud->set_subject('Pengaturan');

        $crud->required_fields('no_peserta', 'nama_lengkap', 'jenis_kelamin', 'kelas', 'username', 'password');

        $crud->set_field_upload('logo', 'assets/uploads/');

        $crud->unset_add();
        $crud->unset_export();
        $crud->unset_print();
        $crud->unset_delete();

        $output = $crud->render();

        $this->title = 'Kelola Jenis Ujian';
        $this->render_page($output, 'admin/template/crud');
    }

    public function cetak_kartu_ujian() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('setting_kartu');
        $crud->set_subject('Pengaturan');

        $crud->required_fields('no_peserta', 'nama_lengkap', 'jenis_kelamin', 'kelas', 'username', 'password');

        $crud->set_field_upload('logo', 'assets/uploads/');

        $crud->unset_jquery();
        $crud->unset_add();
        $crud->unset_export();
        $crud->unset_print();
        $crud->unset_delete();

        $output = $crud->render();

        $this->load->model('msite');

        $kelas = $this->db->from('master_kelas')
            ->get()
            ->result();
        $jenjang_pendidikan = $this->db->from('master_jenjang_pendidikan')
            ->get()
            ->result();
        $jurusan = $this->db->from('master_jurusan')
            ->get()
            ->result();

        $output->kelas              = $kelas;
        $output->jenjang_pendidikan = $jenjang_pendidikan;
        $output->jurusan            = $jurusan;

        $this->render_page($output, 'admin/template/filter_kartu');
    }

    public function cetak_kartu_perkelas() {
        $jenjang_pendidikan = $this->input->post('jenjang_pendidikan');
        $kelas              = $this->input->post('kelas');
        $jurusan            = $this->input->post('jurusan');

        $siswa = $this->db->from('siswa')
            ->where('kelas', $kelas)
            ->where('jenjang_pendidikan', $jenjang_pendidikan)
            ->where('jurusan', $jurusan)
            ->join('master_kelas', 'kelas=id_kelas', 'left')
            ->join('master_jenjang_pendidikan', 'jenjang_pendidikan=id_jenjang_pendidikan', 'left')
            ->join('master_jurusan', 'kelas=id_jurusan', 'left')
            ->get()
            ->result();

        $setting = $this->db->from('setting_kartu')
            ->limit(1)->get()->row();

        $data           = array();
        $data['siswa']  = $siswa;
        $data['seting'] = $setting;

        $this->load->view('admin/template/cetak_kartu_perkelas', $data);
    }

    public function atur_tata_tertib() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('tata_tertib');
        $crud->set_subject('Tata Tertib Ujian');

        $crud->required_fields('isi_tata_tertib', 'tanggal_buat', 'aktif');

        $output = $crud->render();

        $this->title = 'Kelola Tata Tertib Ujian';
        $this->render_page($output, 'admin/template/crud');
    }

    public function lap_hasil_ujian() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('jadwal_ujian');
        $crud->set_subject('Jadwal Ujian');
        $crud->set_relation('jenis_ujian', 'jenis_ujian', 'nama_jenis_ujian');

        $crud->add_action('Buka Hasil Ujian', 'hapus.png', 'admin/hasil_ujian');

        $crud->required_fields('nama_jadwal_ujian', 'jenjang_pendidikan', 'aktif');
        $crud->unique_fields('nama_jadwal_ujian');
        $crud->unset_operations();

        $output = $crud->render();

        $this->title = 'Kelola Tata Tertib Ujian';
        $this->render_page($output, 'admin/template/crud');
    }

    public function koreksi_essay() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('jadwal_ujian');
        $crud->set_subject('Jadwal Ujian');
        $crud->set_relation('jenis_ujian', 'jenis_ujian', 'nama_jenis_ujian');

        $crud->add_action('Buka Hasil Ujian', 'hapus.png', 'admin/koreksi_hasil_ujian');

        $crud->required_fields('nama_jadwal_ujian', 'jenjang_pendidikan', 'aktif');
        $crud->unique_fields('nama_jadwal_ujian');
        $crud->unset_operations();

        $output = $crud->render();

        $this->title = 'Koreksi Hasil Ujian Essay';
        $this->render_page($output, 'admin/template/crud');
    }

    public function koreksi_hasil_ujian($idJadwalUjian = '') {
        if ($idJadwalUjian == '') {
            redirect('admin/lap_hasil_ujian');
        }

        $detail_jadwal = $this->db->from('jadwal_ujian')
            ->where('id_jadwal_ujian', $idJadwalUjian)
            ->join('jenis_ujian', 'id_jenis_ujian=jenis_ujian', 'LEFT')
            ->get()
            ->row();

        if (!$detail_jadwal) {
            redirect('admin/lap_hasil_ujian');
        }

        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('detail_jadwal_ujian');
        $crud->set_subject('Mata Pelajaran');
        $crud->where('jadwal_ujian', $idJadwalUjian);
        // $crud->where('keterangan', 'ESSAY');
        $crud->order_by('tanggal_pelaksanaan');

        $crud->set_relation('mata_pelajaran', 'mata_pelajaran', 'nama_mata_pelajaran');
        $crud->set_relation('kelas', 'master_kelas', 'nama_kelas');
        $crud->set_relation('jurusan', 'master_jurusan', 'nama_jurusan');
        $crud->unset_columns('jadwal_ujian');
        //$crud->columns('mata_pelajaran', 'kelas', 'tanggal_pelaksanaan', 'ditutup');

        $crud->add_action('Koreksi Hasil Ujian Essay', 'tambah.png', 'admin/lihat_hasil_ujian_essay');

        $crud->unset_jquery();
        $crud->unset_operations();

        $output = $crud->render();

        $output->jadwal = $detail_jadwal;

        $this->title = 'Kelola Tata Tertib Ujian';
        $this->render_page($output, 'admin/template/crud');
    }

    public function lihat_hasil_ujian_essay($detailJadwalUjian = '') {
        if ($detailJadwalUjian == '') {
            redirect('admin/koreksi_essay');
        }

        $detail_paket = $this->db->select('*, NOW() as sekarang')
            ->from('detail_jadwal_ujian')
            ->where('id_detail_jadwal_ujian', $detailJadwalUjian)
            ->join('jadwal_ujian', 'jadwal_ujian = id_jadwal_ujian', 'LEFT')
            ->join('mata_pelajaran', 'mata_pelajaran= id_mata_pelajaran', 'LEFT')
            ->join('master_kelas', 'kelas= id_kelas', 'LEFT')
            ->get()
            ->row();

        if (!$detail_paket) {
            redirect('admin/koreksi_essay');
        }

        $pesan = "";
        if ($this->input->post('save')) {
            $this->load->library(array('PHPExcel', 'PHPExcel/IOFactory'));

            $fileName = date('HisdmY') . '-' . $_FILES['import']['name'];

            $config['upload_path']   = './assets/uploads/files/';
            $config['file_name']     = $fileName;
            $config['allowed_types'] = 'xls';
            $config['max_size']      = 3000;

            $this->load->library('upload', $config);

            if (!$this->upload->do_upload('import')) {
                $pesan .= '<br/>' . $this->upload->display_errors();
            } else {
                $media         = $this->upload->data();
                $inputFileName = './assets/uploads/files/' . $media['file_name'];

                //echo $media;
                //  Read your Excel workbook
                try {
                    $inputFileType = IOFactory::identify($inputFileName);
                    $objReader     = IOFactory::createReader($inputFileType);
                    $objPHPExcel   = $objReader->load($inputFileName);

//  Get worksheet dimensions
                    $sheet         = $objPHPExcel->getSheet(0);
                    $highestRow    = $sheet->getHighestRow();
                    $highestColumn = $sheet->getHighestColumn();

//  Loop through each row of the worksheet in turn
                    $insert_data = array();
                    for ($row = 2; $row <= $highestRow; $row++) {
                        $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, null, true, false);
                        $id      = $rowData[0][0];
                        $nilai   = $rowData[0][7];

                        $this->db->update('soal_ujian', array('nilai_essay' => $nilai), array('id_soal_ujian' => $id));
                    }

                    $pesan .= "<br/>Import Nilai Essay Success";
                } catch (Exception $e) {
                    $pesan .= '<br/>Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage();
                }
            }
        }

        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('ujian_dilaksanakan');
        $crud->set_subject('Hasil Ujian');
        $crud->where('detail_jadwal_ujian', $detailJadwalUjian);

        $crud->set_relation('peserta', 'siswa', '{no_induk} - {nama_lengkap} (Rombel: {rombel})');
        $crud->set_relation('paket_soal', 'data_paket_soal', 'deskripsi');

        $crud->columns('peserta', 'mata_pelajaran', 'paket_soal', 'jumlah_soal', 'status_ujian', 'jumlah_benar', 'koreksi');

        $crud->callback_column('koreksi', array($this, '_callback_koreksi'));
        $crud->callback_column('jumlah_benar', array($this, '_callback_jumlah_benar'));

        $crud->display_as('peserta', 'NIS - Nama Siswa (Rombel)');
        $crud->display_as('jumlah_benar', 'Nilai (JUMLAH)');

        $crud->unset_jquery();
        $crud->unset_add();
        $crud->unset_read();
        $crud->unset_edit();
        $crud->unset_delete();

        $output = $crud->render();

        $output->detail = $detail_paket;
        $output->pesan  = $pesan;

        $this->render_page($output, 'admin/template/tampilkan_hasil_ujian');
    }

    public function koreksi_soal_essay($idujiandilaksanakan = '') {
        if ($idujiandilaksanakan == '') {
            redirect('admin/koreksi_essay');
        }

        $detail_ujian = $this->db->select('*')
            ->from('ujian_dilaksanakan')
            ->join('siswa', 'peserta=id_peserta', 'left')
            ->join('master_kelas', 'kelas=id_kelas', 'left')
            ->where('id_ujian_dilaksanakan', $idujiandilaksanakan)
            ->get()
            ->row();

        if (!$detail_ujian) {
            redirect('admin/koreksi_essay');
        }

        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('soal_ujian');
        $crud->set_subject('Hasil Ujian Essay');
        $crud->where('ujian_yang_dilaksanakan', $idujiandilaksanakan);
        $crud->where("(soal_ujian.jenis_soal = 'ESSAY' OR soal_ujian.jenis_soal = 'JAWABAN SINGKAT')");

        $crud->set_relation('pertanyaan', 'bank_soal', 'deskripsi_soal');

        $crud->columns('no_soal', 'pertanyaan', 'jawaban_essay', 'skor_ujian');
        $crud->edit_fields('no_soal', 'jenis_soal', 'pertanyaan', 'jawaban_essay', 'skor_ujian');

        $crud->field_type('ujian_yang_dilaksanakan', 'invisible');
        $crud->field_type('jawaban', 'invisible');
        $crud->field_type('waktu_jawab', 'invisible');
        $crud->field_type('status', 'invisible');
        $crud->field_type('jenis_soal', 'readonly');
        $crud->field_type('no_soal', 'readonly');
        $crud->field_type('pertanyaan', 'readonly');
        $crud->field_type('jawaban_essay', 'readonly');

        $crud->callback_after_update(array($this, 'ubah_nilai'));

        $crud->unset_jquery();
        $crud->unset_add();
        $crud->unset_read();
//        $crud->unset_edit();
        $crud->unset_delete();

        $output = $crud->render();

        $output->detail = $detail_ujian;

        $this->render_page($output, 'admin/template/tampilkan_hasil_ujian_essay1');
    }

    public function template_hasil_ujian($detailJadwalUjian = '') {
        if ($detailJadwalUjian == '') {
            redirect('admin/koreksi_essay');
        }

        $detail_paket = $this->db->select('*, NOW() as sekarang')
            ->from('detail_jadwal_ujian')
            ->where('id_detail_jadwal_ujian', $detailJadwalUjian)
            ->join('jadwal_ujian', 'jadwal_ujian = id_jadwal_ujian', 'LEFT')
            ->join('mata_pelajaran', 'mata_pelajaran= id_mata_pelajaran', 'LEFT')
            ->join('master_kelas', 'kelas= id_kelas', 'LEFT')
            ->get()
            ->row();

        if (!$detail_paket) {
            redirect('admin/koreksi_essay');
        }

        $this->load->library(array('PHPExcel', 'PHPExcel/IOFactory'));

        $objPHPExcel = new PHPExcel();

        // Set properties
        $objPHPExcel->getProperties()
            ->setCreator('CBT APPS') //creator
            ->setTitle("Template Import KOREKSI Essay"); //file title

        $objPHPExcel->setActiveSheetIndex(0)
            ->setTitle('Data Import')
            ->setCellValue('A1', 'KODE UNIX (TIDAK BOLEH DIUBAH)')
            ->setCellValue('B1', 'NO PESERTA (TIDAK MENGUBAH HASIL UJIAN)')
            ->setCellValue('C1', 'NIS (TIDAK MENGUBAH HASIL UJIAN)')
            ->setCellValue('D1', 'NAMA SISWA (TIDAK MENGUBAH HASIL UJIAN)')
            ->setCellValue('E1', 'MATA PELAJARAN(TIDAK MENGUBAH HASIL UJIAN)')
            ->setCellValue('F1', 'PERTANYAAN (TIDAK MENGUBAH HASIL UJIAN)')
            ->setCellValue('G1', 'JAWABAN SISWA (TIDAK MENGUBAH HASIL UJIAN)')
            ->setCellValue('H1', 'NILAI');

        $nilai = $this->db->select("soal_ujian.*, siswa.no_peserta, siswa.no_induk, siswa.nama_lengkap, bank_soal.deskripsi_soal")
            ->from('soal_ujian')
            ->join('ujian_dilaksanakan', 'ujian_yang_dilaksanakan=id_ujian_dilaksanakan', 'left')
            ->join('bank_soal', 'pertanyaan=id_bank_soal', 'left')
            ->join('siswa', 'peserta=id_peserta', 'LEFT')
            ->where('detail_jadwal_ujian', $detailJadwalUjian)
            ->order_by('ujian_yang_dilaksanakan')
            ->get()->result();

        $row = 1;
        foreach ($nilai as $n) {
            $row++;
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $row, $n->id_soal_ujian);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $row, $n->no_peserta);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $row, $n->no_induk);
            $objPHPExcel->getActiveSheet()->setCellValue('D' . $row, $n->nama_lengkap);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $row, $detail_paket->nama_mata_pelajaran);
            $objPHPExcel->getActiveSheet()->setCellValue('F' . $row, strip_tags($n->deskripsi_soal));
            $objPHPExcel->getActiveSheet()->setCellValue('G' . $row, strip_tags($n->jawaban_essay));
            $objPHPExcel->getActiveSheet()->setCellValue('H' . $row, 0);
        }

        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        // Redirect output to a client’s web browser (Excel5)
        //        header('Content-Type: application/vnd.ms-excel');
        header('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="template_import_nilai_essay.xls"');
        header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $objWriter->save('php://output');
        exit;
    }

    function ubah_nilai($post_array, $primary_key) {
        $uji        = 0;
        $soal_ujian = $this->db->select('ujian_yang_dilaksanakan')
            ->from('soal_ujian')
            ->where('id_soal_ujian', $primary_key)->get()->row();
        if ($soal_ujian) {
            $uji = $soal_ujian->ujian_yang_dilaksanakan;
        }

        $query = $this->db->query("SELECT COALESCE(AVG(nilai_essay),0)as nilai FROM soal_ujian WHERE ujian_yang_dilaksanakan = '$uji'")->row();

        $this->db->update('ujian_dilaksanakan', array('jumlah_benar' => $query->nilai), array('id_ujian_dilaksanakan' => $uji));

        return true;
    }

    public function _callback_koreksi($value, $row) {
        return '<a href="' . site_url('admin/koreksi_soal_essay/' . $row->id_ujian_dilaksanakan) . '" class="btn btn-xs btn-danger btn-block">Koreksi Hasil Ujian</a>';
    }

    public function _callback_jumlah_benar($value, $row) {
        $nilai = $this->db->query("SELECT COALESCE(SUM(skor_ujian),0) as nilai FROM soal_ujian WHERE ujian_yang_dilaksanakan='" . $row->id_ujian_dilaksanakan . "'")->row();
        return number_format($nilai->nilai, 2, ',', '.');
    }

    public function _callback_daftar_hadir($value, $row) {
        return '<a href="' . site_url('admin/cetak_daftar_hadir/' . $row->id_detail_jadwal_ujian) . '" class="btn btn-xs btn-danger btn-block" target="_blank" style="color:#fff; text-decoration:none">Cetak</a>';
    }

    public function _callback_monitoring($value, $row) {
        return '<a href="' . site_url('admin/monitoring_ujian_ujian/' . $row->id_detail_jadwal_ujian) . '" class="btn btn-xs btn-danger btn-block" style="color:#fff; text-decoration:none">Monitoring</a>';
    }

    public function _callback_berita_acara($value, $row) {
        return '<a href="' . site_url('admin/cetak_berita_acara/' . $row->id_detail_jadwal_ujian) . '" class="btn btn-xs btn-danger btn-block" target="_blank" style="color:#fff; text-decoration:none">Cetak</a>';
    }

    public function hasil_ujian($idJadwalUjian = '') {
        if ($idJadwalUjian == '') {
            redirect('admin/lap_hasil_ujian');
        }

        $detail_jadwal = $this->db->from('jadwal_ujian')
            ->where('id_jadwal_ujian', $idJadwalUjian)
            ->join('jenis_ujian', 'id_jenis_ujian=jenis_ujian', 'LEFT')
            ->get()
            ->row();

        if (!$detail_jadwal) {
            redirect('admin/lap_hasil_ujian');
        }

        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('detail_jadwal_ujian');
        $crud->set_subject('Mata Pelajaran');
        $crud->where('jadwal_ujian', $idJadwalUjian);
        $crud->order_by('tanggal_pelaksanaan');

        $crud->set_relation('mata_pelajaran', 'mata_pelajaran', 'nama_mata_pelajaran');
        $crud->set_relation('kelas', 'master_kelas', 'nama_kelas');
        $crud->set_relation('jurusan', 'master_jurusan', 'nama_jurusan');
        $crud->unset_columns('jadwal_ujian');
        //$crud->columns('mata_pelajaran', 'kelas', 'tanggal_pelaksanaan', 'ditutup');

        $crud->add_action('Hasil Ujian per Mapel', 'tambah.png', 'admin/tampilkan_hasil_ujian');
        $crud->add_action('Hasil Ujian Kelas', 'tambah.png', 'admin/filter_hasil_ujian_perkelas');

        $crud->unset_jquery();
        $crud->unset_operations();

        $output = $crud->render();

        $output->jadwal = $detail_jadwal;

        $this->title = 'Kelola Tata Tertib Ujian';
        $this->render_page($output, 'admin/template/crud');
    }

    public function tampilkan_hasil_ujian($detailJadwalUjian = '') {
        if ($detailJadwalUjian == '') {
            redirect('admin/hasil_ujian');
        }

        $detail_paket = $this->db->select('*, NOW() as sekarang')
            ->from('detail_jadwal_ujian')
            ->where('id_detail_jadwal_ujian', $detailJadwalUjian)
            ->join('jadwal_ujian', 'jadwal_ujian = id_jadwal_ujian', 'LEFT')
            ->join('mata_pelajaran', 'mata_pelajaran= id_mata_pelajaran', 'LEFT')
            ->join('master_kelas', 'kelas= id_kelas', 'LEFT')
            ->get()
            ->row();

        if (!$detail_paket) {
            redirect('admin/hasil_ujian');
        }

        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('ujian_dilaksanakan');
        $crud->set_subject('Hasil Ujian');
        $crud->where('detail_jadwal_ujian', $detailJadwalUjian);

        $crud->set_relation('peserta', 'siswa', '{no_induk} - {nama_lengkap} (Rombel: {rombel})');
        $crud->set_relation('paket_soal', 'data_paket_soal', 'deskripsi');

        $crud->columns('peserta', 'mata_pelajaran', 'paket_soal', 'jumlah_soal', 'status_ujian', 'skor');

        $crud->callback_column('skor', array($this, '_callback_persentase_nilai'));
        $crud->display_as('persentase', 'Nilai');

        $crud->display_as('peserta', 'NIS - Nama Siswa (Rombel)');
        $crud->display_as('jumlah_benar', 'Benar/Nilai');

        $crud->unset_jquery();
        $crud->unset_add();
        $crud->unset_read();
        $crud->unset_edit();
        $crud->unset_delete();

        $output = $crud->render();

        $output->detail = $detail_paket;

        $this->render_page($output, 'admin/template/tampilkan_hasil_ujian_essay');
    }

    public function _callback_persentase_nilai($value, $row) {
        $persen = $this->db->query("SELECT COALESCE(SUM(skor_ujian), 0) as jumlah from soal_ujian WHERE ujian_yang_dilaksanakan = '$row->id_ujian_dilaksanakan'")->row();

        return number_format($persen->jumlah, 2, ',', '.');
    }

    public function filter_hasil_ujian_perkelas($detailJadwalUjian = '') {
        if ($detailJadwalUjian == '') {
            redirect();
        }

        $detail_paket = $this->db->select('*, NOW() as sekarang')
            ->from('detail_jadwal_ujian')
            ->where('id_detail_jadwal_ujian', $detailJadwalUjian)
            ->join('jadwal_ujian', 'jadwal_ujian = id_jadwal_ujian', 'LEFT')
            ->join('mata_pelajaran', 'mata_pelajaran= id_mata_pelajaran', 'LEFT')
            ->join('master_kelas', 'kelas= id_kelas', 'LEFT')
            ->get()
            ->row();

        if (!$detail_paket) {
            redirect();
        }

        $kelas   = $this->db->from('master_kelas')->get()->result();
        $jurusan = $this->db->from('master_jurusan')->get()->result();

        $output            = array();
        $output['kelas']   = $kelas;
        $output['jurusan'] = $jurusan;
        $output['detail']  = $detail_paket;

        $this->render_page($output, 'admin/template/filter_hasil_ujian');
    }

    public function cetak_hasil_ujian($detailJadwalUjian = '') {
        if ($detailJadwalUjian == '') {
            redirect();
        }

        $detail_paket = $this->db->select('*, NOW() as sekarang')
            ->from('detail_jadwal_ujian')
            ->where('id_detail_jadwal_ujian', $detailJadwalUjian)
            ->join('jadwal_ujian', 'jadwal_ujian = id_jadwal_ujian', 'LEFT')
            ->join('mata_pelajaran', 'mata_pelajaran= id_mata_pelajaran', 'LEFT')
            ->join('master_kelas', 'kelas= id_kelas', 'LEFT')
            ->get()
            ->row();

        if (!$detail_paket) {
            redirect();
        }

        $kelas   = $this->input->post('kelas');
        $jurusan = $this->input->post('jurusan');

        $hu = $this->db->from('siswa')
            ->where('siswa.kelas', $kelas)
            ->where('siswa.jurusan', $jurusan)
            ->join('ujian_dilaksanakan', 'peserta=id_peserta', 'LEFT')
            ->join('data_paket_soal', 'paket_soal=id_paket_soal', 'LEFT')
            ->join('master_kelas', 'siswa.kelas=id_kelas', 'LEFT')
            ->join('master_jurusan', 'siswa.jurusan=id_jurusan', 'LEFT')
            ->order_by('nama_lengkap')
            ->get()->result();

        $data           = array();
        $data['hasil']  = $hu;
        $data['detail'] = $detail_paket;

        $this->load->view('admin/template/cetak_hasil_ujian_perkelas', $data);
    }

    public function cetak_daftar_hadir($detailJadwalUjian = '') {
        if ($detailJadwalUjian == '') {
            redirect();
        }

        $detail_paket = $this->db->select('*, NOW() as sekarang')
            ->from('detail_jadwal_ujian')
            ->where('id_detail_jadwal_ujian', $detailJadwalUjian)
            ->join('jadwal_ujian', 'jadwal_ujian = id_jadwal_ujian', 'LEFT')
            ->join('mata_pelajaran', 'mata_pelajaran= id_mata_pelajaran', 'LEFT')
            ->join('master_kelas', 'kelas= id_kelas', 'LEFT')
            ->get()
            ->row();

        if (!$detail_paket) {
            redirect();
        }

        $hu = $this->db->from('siswa')
            ->where('siswa.kelas', $detail_paket->kelas)
            ->where('siswa.jurusan', $detail_paket->jurusan)
            ->join('master_kelas', 'siswa.kelas=id_kelas', 'LEFT')
            ->join('master_jurusan', 'siswa.jurusan=id_jurusan', 'LEFT')
            ->order_by('nama_lengkap')
            ->get()->result();

//        $sekolah = $this->db->from('status_cbt')
        //        print_r($this->db->last_query());

        $data           = array();
        $data['hasil']  = $hu;
        $data['detail'] = $detail_paket;

        $this->load->view('admin/template/cetak_daftar_hadir', $data);
    }

    public function cetak_berita_acara($detailJadwalUjian = '') {
        if ($detailJadwalUjian == '') {
            redirect();
        }

        $detail_paket = $this->db->select('*, NOW() as sekarang')
            ->from('detail_jadwal_ujian')
            ->where('id_detail_jadwal_ujian', $detailJadwalUjian)
            ->join('jadwal_ujian', 'jadwal_ujian = id_jadwal_ujian', 'LEFT')
            ->join('mata_pelajaran', 'mata_pelajaran= id_mata_pelajaran', 'LEFT')
            ->join('master_kelas', 'kelas= id_kelas', 'LEFT')
            ->join('master_jurusan', 'jurusan= id_jurusan', 'LEFT')
            ->get()
            ->row();

        if (!$detail_paket) {
            redirect();
        }

        $hu = $this->db->from('siswa')
            ->where('siswa.kelas', $detail_paket->kelas)
            ->where('siswa.jurusan', $detail_paket->jurusan)
            ->join('master_kelas', 'siswa.kelas=id_kelas', 'LEFT')
            ->join('master_jurusan', 'siswa.jurusan=id_jurusan', 'LEFT')
            ->order_by('nama_lengkap')
            ->get()->result();

//        $sekolah = $this->db->from('status_cbt')
        //        print_r($this->db->last_query());

        $data           = array();
        $data['hasil']  = $hu;
        $data['detail'] = $detail_paket;

        $this->load->view('admin/template/cetak_berita_acara', $data);
    }

    public function lap_analisis_soal() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('data_paket_soal');
        $crud->set_subject('Paket Soal');

        $crud->set_relation('mata_pelajaran', 'mata_pelajaran', 'nama_mata_pelajaran');
        $crud->set_relation('kelas', 'master_kelas', 'nama_kelas');
        $crud->set_relation('jenjang_pendidikan', 'master_jenjang_pendidikan', 'nama_jenjang_pendidikan');
        $crud->set_relation('jurusan', 'master_jurusan', 'nama_jurusan');
        $crud->set_relation('jenis_ujian', 'jenis_ujian', 'nama_jenis_ujian');
        $crud->set_relation('dibuat_oleh', 'user', 'nama_lengkap');

        $crud->add_action('Tampilkan Analisis Soal', 'tambah.png', 'admin/analisis_paket_soal');

        $crud->unset_jquery();
        $crud->unset_operations();

        $output = $crud->render();

        $this->title = 'Analisis Soal Ujian';
        $this->render_page($output, 'admin/template/crud');
    }

    public function analisis_paket_soal($idPaket = '') {
        if ($idPaket == '') {
            redirect('panel/paket_soal');
        }

        $detail_paket = $this->db->from('data_paket_soal')
            ->where('id_paket_soal', $idPaket)
            ->join('mata_pelajaran', 'mata_pelajaran = id_mata_pelajaran', 'LEFT')
            ->get()
            ->row();

//print_r($detail_paket);

        if (!$detail_paket) {
            redirect('panel/analisis_hasil_ujian');
        }

        $soal = $this->db->from('detail_paket_soal')
            ->where('data_paket_soal', $idPaket)
            ->join('bank_soal', 'bank_soal=id_bank_soal', 'LEFT')
            ->get()
            ->result();

        $data           = array();
        $data['soal']   = $soal;
        $data['detail'] = $detail_paket;

        $this->load->view('admin/template/cetak_analisis_soal', $data);
    }

    public function history() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('log_user_login');
        $crud->set_subject('Data Soal');

        $crud->set_relation('peserta', 'siswa', '[NIS: {no_induk}] {nama_lengkap} ({username})');

        $crud->unset_add();
        $crud->unset_edit();
        $crud->unset_export();
        $crud->unset_print();

        $output = $crud->render();

        $this->load->view('admin/template/blank', (array) $output);
    }

    public function data_sudah_ujian() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('ujian_dilaksanakan');
        $crud->set_subject('Ujian');
        $crud->set_relation('peserta', 'siswa', '{no_induk} - {nama_lengkap}');
        $crud->where('status_ujian', 'SELESAI');
        $crud->columns('peserta', 'mata_pelajaran', 'jumlah_soal', 'total_skor', 'status_ujian');

        $crud->callback_column('total_skor', function ($val, $row) {
            $skor = $this->db->query("SELECT COALESCE(SUM(skor_ujian), 0) as skor FROM soal_ujian WHERE ujian_yang_dilaksanakan='" . $row->id_ujian_dilaksanakan . "' ")->row();

            return $skor->skor;
        });

        $crud->unset_add();
        $crud->unset_edit();
        $crud->unset_export();
        $crud->unset_print();

        $output = $crud->render();

        $this->load->view('admin/template/blank', (array) $output);
    }

    //private function
    private function validate_user() {
        $usr_sess = $this->session->userdata('cbt_sess_pelaksana');

        if (is_array($usr_sess)) {
            $this->username = $usr_sess['username'];
            $akses          = $usr_sess['akses'];
            if ($akses == 'ADMIN') {
                //okay, lets pass
            } elseif ($akses == 'SISWA') {
                redirect('ujian', 'refresh');
            } else {
                redirect('home', 'refresh');
            }
        } else {
            redirect('home/login', 'refresh');
        }
    }

    private function render_page($data = array(), $template = '') {
        if (is_object($data)) {
            $data = (array) $data;
        }
        $data['judul_halaman'] = $this->title;
        $data['js_tambahan']   = $this->js;
        $data['status_cbt']    = $this->status_cbt;

        $this->load->view('admin/header', $data);
        $this->load->view('admin/top_menu');
        $this->load->view('admin/sidebar');
        $this->load->view($template);
        $this->load->view('admin/footer');
    }

    private function addJS($param) {
        array_push($this->js, $param);
    }

}
