<?php
defined('BASEPATH') or exit('No direct script access allowed');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
class Operator extends CI_Controller
{
    private $dataNilai;
    private $dataPrestasi;
    private $dataAfirmasi;
    public function __construct()
    {
        parent::__construct();
        sekolah_is_log();
        $this->load->model('Operator_m', 'operator');
        $this->load->model('Akun_m', 'akun');
        $this->load->model('Register21', 'register');
        $this->load->model('Pendaftar_m', 'item_m');
        $this->load->model('Model_uploadBiodata', 'm_uploadBiodata');
    }
    public function index()
    {
        $data['title'] = "Operator";
        $data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
        $data['statistik'] = $this->operator->getStatistikByOps();
        $this->load->view('themplate/Operator/header', $data);
        $this->load->view('themplate/Operator/sidebar', $data);
        $this->load->view('themplate/Operator/topbar', $data);
        $this->load->view('Operator/index', $data);
        $this->load->view('themplate/Operator/footer', $data);
    }

    public function register(){
        if (empty($this->session->userdata('id_pendaftar'))) {
            $this->session->set_flashdata('message', '
       <div class="alert alert-danger" role="alert">
     Silahkan  Pilih Siswa Yg akan didaftarkan
      </div>');
            redirect('Operator/Pendaftaran');
        }
     
        $data['title'] = "Pendaftaran Siswa";
     
        $data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])
            ->row_array();
            $data['pendaftar'] = $this->db->get_where('register', ['id' => $this->session->userdata('id_pendaftar'), 'noOps' => $data['user']['id']])->row_array();
        $data['wali'] = $this->db->get_where('wali', ['idRegister' => $this->session->userdata('id_pendaftar')])->row_array();
        $data['formBiodata'] = $this->db->get_where('register', ['id' => $this->session->userdata('id_pendaftar')])->row_array();
        $data['provinsi'] = $this->db->get('provinces')->result_array();
        $data['dataUser'] = $this->operator->biodataAlamatSiswa($data['formBiodata']['id']);
        $data['setting'] = $this->db->get('kop_surat')->row_array();
        $data['pendidikan'] = $this->db->get('pendididikan')->result_array();
        $data['penghasilan'] = $this->db->get('penghasilan')->result_array();
        $data['pekerjaan'] = $this->db->get('pekerjaan')->result_array();
        $data['alamat'] = $this->operator->getAlamat($data['pendaftar']['id']);
        // $data['pendaftar'] = $this->operator->getDataPendaftarByOps();
        $data['statistik'] = $this->operator->getStatistikByOps();
        // pembatasaan jarur ppd berdaskan kota pendaftar
        $data['setting'] = $this->db->get('kop_surat')->row_array();
        
          $data['jalur'] = $this->akun->getJalur()->result_array();
        

        $this->load->view('themplate/Operator/header', $data);
        $this->load->view('themplate/Operator/sidebar', $data);
        $this->load->view('themplate/Operator/topbar', $data);
        $this->load->view('Operator/register', $data);
        $this->load->view('themplate/Operator/footer', $data);
        $this->load->view('themplate/Akun/footermaps', $data);

    }

    // Halaman Upload Biodata
    public function Biodata()
    {
        $data['title'] = "Upload Biodata Pendaftar";
        $data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
        $this->load->view('themplate/Operator/header', $data);
        $this->load->view('themplate/Operator/sidebar', $data);
        $this->load->view('themplate/Operator/topbar', $data);
        $this->load->view('Operator/UploadBiodata', $data);
        $this->load->view('themplate/Operator/footer', $data);
        $this->load->view('themplate/Operator/footerMap', $data);
    }


    // halaman Upload NIlai
    public function Nilai()
    {
        $data['title'] = "Upload Nilai Pendaftar";
        $data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
        $this->load->view('themplate/Operator/header', $data);
        $this->load->view('themplate/Operator/sidebar', $data);
        $this->load->view('themplate/Operator/topbar', $data);
        $this->load->view('Operator/UploadNilai', $data);
        $this->load->view('themplate/Operator/footer', $data);
        $this->load->view('themplate/Operator/footer', $data);
    }
    public function Pendaftaran()
    {
        $data['title'] = "Pendaftaran Siswa";
        $data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
        $data['setting'] = $this->db->get_where('kop_surat', ['id' => 1])->row_array();
        $data['pendaftar'] = $this->operator->getDataPendaftarByOps();
        $this->load->view('themplate/Operator/header', $data);
        $this->load->view('themplate/Operator/sidebar', $data);
        $this->load->view('themplate/Operator/topbar', $data);
        $this->load->view('Operator/PendaftaranSiswa', $data);
        $this->load->view('themplate/Operator/footer', $data);
        $this->load->view('themplate/Operator/footerOperator', $data);

    }

    public function FormBiodata()
    {
        if (empty($this->session->userdata('id_pendaftar'))) {
            $this->session->set_flashdata('message', '
       <div class="alert alert-danger" role="alert">
     Silahkan  Pilih Siswa Yg akan didaftarkan
      </div>');
            redirect('Operator/Pendaftaran');
        }
        $data['title'] = "Pendaftaran Siswa";
        $data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])
            ->row_array();
        $data['formBiodata'] = $this->db->get_where('register', ['id' => $this->session->userdata('id_pendaftar')])->row_array();
        $data['provinsi'] = $this->db->get('provinces')->result_array();
        $data['dataUser'] = $this->operator->biodataAlamatSiswa($data['formBiodata']['id']);
        $data['pendaftar'] = $this->operator->getDataPendaftarByOps();
        $this->load->view('themplate/Operatorn/header', $data);
        $this->load->view('themplate/Operator/sidebar', $data);
        $this->load->view('themplate/Operator/topbar', $data);
        $this->load->view('Operator/formBiodata', $data);
        $this->load->view('themplate/Operator/footer', $data);
        $this->load->view('themplate/Akun/footermaps', $data);
    }

    public function formNilai()
    {
        if (empty($this->session->userdata('id_pendaftar'))) {
            $this->session->set_flashdata('message', '
       <div class="alert alert-danger" role="alert">
     Silahkan  Pilih Siswa Yg akan didaftarkan
      </div>');
            redirect('Operator/Pendaftaran');
        }
        $data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
        $data['pendaftar'] = $this->db->get_where('register', ['id' => $this->session->userdata('id_pendaftar')])->row_array();
        $data['title'] = 'Pendaftaran';
        $data['nilai'] = $this->db->get_where('nilai', ['nisn' => $this->session->userdata('nisn')])->row_array();
        $data['setting'] = $this->db->get('kop_surat')->row_array();
        $data['alamat'] = $this->operator->getAlamat($this->session->userdata('id_pendaftar'));
        $this->load->view('themplate/Operator/header', $data);
        $this->load->view('themplate/Operator/sidebar', $data);
        $this->load->view('themplate/Operator/topbar', $data);
        $this->load->view('Operator/formNilai', $data);
        $this->load->view('themplate/Operator/footer', $data);
        // $this->load->view('themplate/Akun/footermaps', $data);
    }

    // untuk halaman status pendaftar terverifikasi
    public function statusDaftar()
    {
        if (empty($this->session->userdata('idStatus'))) {
            $this->session->set_flashdata('message', '
       <div class="alert alert-danger" role="alert">
     Silahkan  Pilih Siswa untuk di cek di menu pendaftaran
      </div>');
            redirect('Operator/Pendaftaran');
        }
        $data['title'] = "Status Pendaftaran";
        $data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
        $data['siswa'] = $this->db->get_where('register', ['id' => $this->session->userdata('idStatus')])->row_array();
        $data['wali'] = $this->db->get_where('wali', ['idRegister' => $data['siswa']['id']])->row_array();
        $data['jarak'] = $this->akun->statistikJarakPerjalaur($data['siswa']['id_jalur']);
        $data['nilai'] = $this->akun->statistiknilaiPerjalaur($data['siswa']['id_jalur']);
        $data['usia'] = $this->akun->statistikUsiaPerjalaur($data['siswa']['id_jalur']);
        $data['skor'] = $this->akun->statistikKejuaraan();
        $data['statistik'] = $this->operator->statistikPendaftar();
        $data['alamat'] = $this->operator->getAlamat($data['siswa']['id']);
        $data['pendaftar'] = $this->operator->pendaftaran();
        $this->load->view('themplate/Operator/header', $data);
        $this->load->view('themplate/Operator/sidebar', $data);
        $this->load->view('themplate/Operator/topbar', $data);
        $this->load->view('Operator/statusPendaftaran_v', $data);
        $this->load->view('themplate/Operator/footer', $data);
        $this->load->view('themplate/Operator/footer', $data);
    }

    // unset session status dafttar
    public function unsetStatus()
    {
        $this->session->unset_userdata('idStatus');
        redirect('Operator/Pendaftaran');
    }

    // simpan data pendaftrsn
    public function simpanDataNilai()
    {
        $userdata['pendaftar'] = $this->db->get_where('register', ['nisn' => $this->session->userdata('nisn')])->row_array();
        $operator = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
        $user = $userdata['pendaftar'];
        $form = $_POST;
        $jmlRataRatapai = round(($form['paiK4S1'] + $form['paiK4S2'] + $form['paiK5S1'] + $form['paiK5S2'] + $form['paiK6S1']) / 5, 2);
        $jmlRataRatapkn = round(($form['pknK4S1'] + $form['pknK4S2'] + $form['pknK5S1'] + $form['pknK5S2'] + $form['pknK6S1']) / 5, 2);
        $jmlRataRataIndo = round(($form['indoK4S1'] + $form['indoK4S2'] + $form['indoK5S1'] + $form['indoK5S2'] + $form['indoK6S1']) / 5, 2);
        $jmlRataRataMtk = round(($form['mtkK4S1'] + $form['mtkK4S2'] + $form['mtkK5S1'] + $form['mtkK5S2'] + $form['mtkK6S1']) / 5, 2);
        $jmlRataRataIpa = round(($form['ipaK4S1'] + $form['ipaK4S2'] + $form['ipaK5S1'] + $form['ipaK5S2'] + $form['ipaK6S1']) / 5, 2);
        $jmlRataRataips = round(($form['ipsK4S1'] + $form['ipsK4S2'] + $form['ipsK5S1'] + $form['ipsK5S2'] + $form['ipsK6S1']) / 5, 2);
        $jmlRataRatasbdp = round(($form['sbdpK4S1'] + $form['sbdpK4S2'] + $form['sbdpK5S1'] + $form['sbdpK5S2'] + $form['sbdpK6S1']) / 5, 2);
        $jmlRataRatapjok = round(($form['pjokK4S1'] + $form['pjokK4S2'] + $form['pjokK5S1'] + $form['pjokK5S2'] + $form['pjokK6S1']) / 5, 2);
        $jmlRataRatasunda = round(($form['sundaK4S1'] + $form['sundaK4S2'] + $form['sundaK5S1'] + $form['sundaK5S2'] + $form['sundaK6S1']) / 5, 2);
        $totalRataRataNilai = $jmlRataRatapai + $jmlRataRatapkn + $jmlRataRataIndo + $jmlRataRataIpa + $jmlRataRataMtk + $jmlRataRataips + $jmlRataRatasbdp + $jmlRataRatapjok + $jmlRataRatasunda;
        $data = [
            'id_pendaftar' => htmlspecialchars($user['id']),
            'nisn' => htmlspecialchars($user['nisn']),
            'noOps' => htmlspecialchars($operator['id']),
            'recordNilaiNama' => htmlspecialchars($user['nama']),
            'paiK4S1' => htmlspecialchars($this->input->post('paiK4S1')),
            'paiK4S2' => htmlspecialchars($this->input->post('paiK4S2')),
            'paiK5S1' => htmlspecialchars($this->input->post('paiK5S1')),
            'paiK5S2' => htmlspecialchars($this->input->post('paiK5S2')),
            'paiK6S1' => htmlspecialchars($this->input->post('paiK6S1')),

            'pknK4S1' => htmlspecialchars($this->input->post('pknK4S1')),
            'pknK4S2' => htmlspecialchars($this->input->post('pknK4S2')),
            'pknK5S1' => htmlspecialchars($this->input->post('pknK5S1')),
            'pknK5S2' => htmlspecialchars($this->input->post('pknK5S2')),
            'pknK6S1' => htmlspecialchars($this->input->post('pknK6S1')),

            'indoK4S1' => htmlspecialchars($this->input->post('indoK4S1')),
            'indoK4S2' => htmlspecialchars($this->input->post('indoK4S2')),
            'indoK5S1' => htmlspecialchars($this->input->post('indoK5S1')),
            'indoK5S2' => htmlspecialchars($this->input->post('indoK5S2')),
            'indoK6S1' => htmlspecialchars($this->input->post('indoK6S1')),

            'mtkK4S1' => htmlspecialchars($this->input->post('mtkK4S1')),
            'mtkK4S2' => htmlspecialchars($this->input->post('mtkK4S2')),
            'mtkK5S1' => htmlspecialchars($this->input->post('mtkK5S1')),
            'mtkK5S2' => htmlspecialchars($this->input->post('mtkK5S2')),
            'mtkK6S1' => htmlspecialchars($this->input->post('mtkK6S1')),

            'ipaK4S1' => htmlspecialchars($this->input->post('ipaK4S1')),
            'ipaK4S2' => htmlspecialchars($this->input->post('ipaK4S2')),
            'ipaK5S1' => htmlspecialchars($this->input->post('ipaK5S1')),
            'ipaK5S2' => htmlspecialchars($this->input->post('ipaK5S2')),
            'ipaK6S1' => htmlspecialchars($this->input->post('ipaK6S1')),

            'ipsK4S1' => htmlspecialchars($this->input->post('ipsK4S1')),
            'ipsK4S2' => htmlspecialchars($this->input->post('ipsK4S2')),
            'ipsK5S1' => htmlspecialchars($this->input->post('ipsK5S1')),
            'ipsK5S2' => htmlspecialchars($this->input->post('ipsK5S2')),
            'ipsK6S1' => htmlspecialchars($this->input->post('ipsK6S1')),

            'sbdpK4S1' => htmlspecialchars($this->input->post('sbdpK4S1')),
            'sbdpK4S2' => htmlspecialchars($this->input->post('sbdpK4S2')),
            'sbdpK5S1' => htmlspecialchars($this->input->post('sbdpK5S1')),
            'sbdpK5S2' => htmlspecialchars($this->input->post('sbdpK5S2')),
            'sbdpK6S1' => htmlspecialchars($this->input->post('sbdpK6S1')),

            'pjokK4S1' => htmlspecialchars($this->input->post('pjokK4S1')),
            'pjokK4S2' => htmlspecialchars($this->input->post('pjokK4S2')),
            'pjokK5S1' => htmlspecialchars($this->input->post('pjokK5S1')),
            'pjokK5S2' => htmlspecialchars($this->input->post('pjokK5S2')),
            'pjokK6S1' => htmlspecialchars($this->input->post('pjokK6S1')),

            'sundaK4S1' => htmlspecialchars($this->input->post('sundaK4S1')),
            'sundaK4S2' => htmlspecialchars($this->input->post('sundaK4S2')),
            'sundaK5S1' => htmlspecialchars($this->input->post('sundaK5S1')),
            'sundaK5S2' => htmlspecialchars($this->input->post('sundaK5S2')),
            'sundaK6S1' => htmlspecialchars($this->input->post('sundaK6S1')),
            'total' => $totalRataRataNilai
        ];

        if ($this->operator->simpanNilai($data) > 0) {
            echo json_encode(['pesan' => 'ok']);
        } else {
            echo json_encode(['pesan' => 'gagal']);
        }
    }

    // form pemilihan jalur ppdn
    public function formJalur()
    {
        if (empty($this->session->userdata('id_pendaftar'))) {
            $this->session->set_flashdata('message', '
       <div class="alert alert-danger" role="alert">
     Silahkan  Pilih Siswa Yg akan didaftarkan
      </div>');
            redirect('Operator/Pendaftaran');
        }

        $data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
        $operator = $data['user'];
        $data['pendaftar'] = $this->db->get_where('register', ['id' => $this->session->userdata('id_pendaftar'), 'noOps' => $operator['id']])->row_array();
        $data['title'] = 'Registrasi';
        $data['setting'] = $this->db->get('kop_surat')->row_array();
        if ($data['setting']['wilayah'] == $data['pendaftar']['kota']) {
            $data['jalur'] = $this->akun->getJalur()->result_array();
        } else {
            $data['jalur'] = $this->akun->getJalurWil()->result_array();
        }
        $this->load->view('themplate/Operator/header', $data);
        $this->load->view('themplate/Operator/sidebar', $data);
        $this->load->view('themplate/Operator/topbar', $data);
        $this->load->view('Operator/formJalur', $data);
        $this->load->view('themplate/Operator/footer', $data);
        
    }

    // hapus Sesssion Pendaftar
    private function _hapusDataSetPendaftar()
    {
        $this->session->unset_userdata('id_pendaftar');
        $this->session->unset_userdata('nisn');
    }
    // simpan jalur ppdb
    public function simpanJalur()
    {
        $operator = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
        $pendaftar = $this->db->get_where('register', ['id' => $this->session->userdata('id_pendaftar'), 'noOps' => $operator['id']])->row_array();
        $dataUpdateRegister = [
            'koreg' => $this->register->koreg(),
            'noDaftar' => $this->register->urut(),
            'id' =>  $pendaftar['id'],
            'nisn' =>  $pendaftar['nisn'],
            'noOps' =>  $operator['id'],
            'id_jalur' => $this->input->post('jalurPpdb')
        ];

        // update tabel register,nilai,wali


        if ($this->operator->updateRegister($dataUpdateRegister) > 0) {
            $pendaftar = $this->db->get_where('register', ['id' => $this->session->userdata('id_pendaftar'), 'noOps' => $operator['id']])->row_array();

            // hapus Session pendaftar
            $this->_hapusDataSetPendaftar();
            // update tabel nilai
            $dataUpdatenilai = [
                'koreg' =>  $pendaftar['koreg'],
                'nama' =>  $pendaftar['nama'],
                'id' =>  $pendaftar['id'],
                'noOps' =>  $operator['id'],
            ];
            // setelah berhasil update nilai baru update table wali
            if ($this->operator->updateNilai($dataUpdatenilai) > 0) {
                $dataUpdateWali = [
                    'koreg' =>  $pendaftar['koreg'],
                    'id' =>  $pendaftar['id'],
                    'noOps' =>  $operator['id'],
                ];
                // setelah berhasil update nilai baru update table wali
                if ($this->operator->updateWali($dataUpdateWali) > 0) {

                    // jika jalur kejuaraan
                    if ($pendaftar['id_jalur'] == 4) {
                        $cekKejuaraan = $this->db->get_where('kejuaraansiswa', ['id_pendaftar' => $pendaftar['id']])->row_array();
                        $tingkatPrestasi = $this->input->post('tingkatPrestasi');
                        $skor = $this->akun->getDataTingkatPresatasi($tingkatPrestasi)->row_array();
                        $data = [
                            'id_pendaftar' => $pendaftar['id'],
                            'koreg' => $pendaftar['koreg'],
                            'id_kejuaraan' => $tingkatPrestasi,
                            'namaKejuaraan' => $this->input->post('namaKejuaraan'),
                            'skor' => $skor['score']
                        ];

                        // cek ke tabel kejuaraan sudah ada atau tidak
                        if ($cekKejuaraan) {
                            // jika ada update datanya
                            if ($this->operator->updatePendaftarKejuaraan($data) > 0) {
                                echo json_encode(['pesan' => 'ok']);
                            } else {
                                echo json_encode(['pesan' => 'gagal']);
                            }
                        } else {
                            // jika tidak ada tambahkan
                            if ($this->operator->SimpanPendaftarKejuaraan($data) > 0) {
                                echo json_encode(['pesan' => 'ok']);
                            } else {
                                echo json_encode(['pesan' => 'gagal']);
                            }
                        }

                        // jika jalaur Afirmasi
                    } else if ($pendaftar['id_jalur'] == 2) {
                        $data = [
                            'id_pendaftar' => $pendaftar['id'],
                            'koreg' => $pendaftar['koreg'],
                            'afirmasi' => htmlspecialchars($this->input->post('namaAfrimasi')),
                            'nama_afirmasi' => htmlspecialchars($this->input->post('namaPemilik')),
                            'no_afirmasi' => htmlspecialchars($this->input->post('noKartu')),
                            'dtks' => htmlspecialchars($this->input->post('dtks')),
                        ];

                        // cek dulu ke jalur afirmasi
                        $cekAfirmasi = $this->db->get_where('afirmasi', ['id_pendaftar' => $pendaftar['id']])->row_array();
                        if ($cekAfirmasi) {
                            // jika ada update datanya

                            if ($this->operator->updateDataAfirmasiDaftar($data) > 0) {
                                // jika upadete success
                                echo json_encode(['pesan' => 'ok']);
                            } else {
                                // jika gagal
                                echo json_encode(['pesan' => 'ok']);
                            }
                        } else {
                            // jika belum ada tambahkan
                            if ($this->operator->simpanDataAfirmasiDaftar($data) > 0) {
                                echo json_encode(['pesan' => 'ok']);
                            } else {
                                echo json_encode(['pesan' => 'gagal']);
                            }
                        }
                    } else {
                        // menanganai selain jalur afirmasi dan kejuaraan
                        echo json_encode(['pesan' => 'ok']);
                    }
                }
            } else {
                // jika gagal update table nilai
                echo json_encode(['pesan' => 'gagal']);
            }
        } else {
            // jika gagal update table register
            echo json_encode(['pesan' => 'gagal']);
        }
    }

    public function changejalur(){

        echo json_encode($this->operator->getDataJalur($_POST['id']));
     
       }


    // set session data pendaftaran
    public function setPendaftaran($id = 0)
    {
        // ambil pendaftar
        $operator = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
        $pendaftar = $this->db->get_where('register', ['id' => $id, 'noOps' => $operator['id']])->row_array();
        $setting = $this->db->get_where('kop_surat', ['id' => 1])->row_array();
        if (sizeOf($operator) > 0) {
            // cek apakh sudah di verifikasi
            if ($pendaftar['statusDaftar'] == 3) {
                // jika sudah verifikasi
                $this->session->set_flashdata('message', '
       <div class="alert alert-danger" role="alert">
                Pendaftar ' . $pendaftar['nama'] . ' sudah di Verifikasi
      </div>');
                redirect('Operator/Pendaftaran');
            } else if ($pendaftar['statusDaftar'] == 2) {
                // jika Sudah Didaftarkan
                $this->session->set_flashdata('message', '
                <div class="alert alert-danger" role="alert">
                         Pendaftar ' . $pendaftar['nama'] . ' sudah di Daftarkan
               </div>');
                redirect('Operator/Pendaftaran');
            } else if ($pendaftar['statusDaftar'] == 4) {
                // jika sudah cabut berkas
                $this->session->set_flashdata('message', '
                <div class="alert alert-danger" role="alert">
                         Pendaftar ' . $pendaftar['nama'] . ' sudah Cabut Berkas
               </div>');
                redirect('Operator/Pendaftaran');
            } else if (count($pendaftar) == 0 || count($pendaftar) == null) {
                // jika pendaftar tidak ditemukan
                $this->session->set_flashdata('message', '
                <div class="alert alert-danger" role="alert">
                         Pendaftar tidak di kenali!!
               </div>');
                redirect('Operator/Pendaftaran');
            } else {
                // jika belum di daftarkan
                // cek apakah akses untuk daftar operator tidak di tutup
                if ($setting['aksesOperator'] == 0) {
                    $this->session->set_flashdata('message', '
                    <div class="alert alert-danger" role="alert">
                    Akses Pendaftaran ditutup
                   </div>');
                    redirect('Operator/Pendaftaran');
                } else {

                    $data = [
                        'id_pendaftar' => $pendaftar['id'],
                        'nisn' => $pendaftar['nisn']
                    ];
                    $this->session->set_userdata($data);
                    redirect('Operator/register');
                }
            }
        } else {
            $this->session->set_flashdata('message', '
       <div class="alert alert-danger" role="alert">
     Silahkan Ulangi Pemilihan Siswa Yg akan didaftarkan
      </div>');
            $this->session->unset_userdata('id_pendaftar');
            $this->session->unset_userdata('nisn');
            redirect('Operator/FormBiodata');
        }
    }

    // set session untuk status pendaftaran
    public function setStatusDaftar($id = 0)
    {
        // ambil pendaftar
        $operator = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
        $pendaftar = $this->db->get_where('register', ['id' => $id, 'noOps' => $operator['id']])->row_array();
        if (sizeOf($operator) > 0) {
            // jika belum submit / pilih jalur
            if ($pendaftar['statusDaftar'] == 1) {
                $this->session->set_flashdata('message', '
                <div class="alert alert-danger" role="alert">
                            Pendaftar ' . $pendaftar['nama'] . ' belum menyelesaikan pendaftaran
                </div>');
                redirect('Operator/Pendaftaran');
            } else if ($pendaftar['statusDaftar'] == 2) {
                // jika belum di verifikasi Operator
                $this->session->set_flashdata('message', '
                <div class="alert alert-danger" role="alert">
                            Pendaftar ' . $pendaftar['nama'] . ' belum diverifikasi
                </div>');
                redirect('Operator/Pendaftaran');
            } else if ($pendaftar['statusDaftar'] == 4) {
                // jika pendaftar cabut berkas
                $this->session->set_flashdata('message', '
                <div class="alert alert-danger" role="alert">
                            Pendaftar ' . $pendaftar['nama'] . ' Cabut Berkas
                </div>');
                redirect('Operator/Pendaftaran');
            } else if (count($pendaftar) == 0 || count($pendaftar) == null) {
                // jika pendaftar tidak ditemukan
                $this->session->set_flashdata('message', '
                <div class="alert alert-danger" role="alert">
                            Pendaftar Tidak Ditemukan !!!
                </div>');
                redirect('Operator/Pendaftaran');
            } else {
                $data = [
                    'idStatus' => $pendaftar['id'],
                ];
                $this->session->set_userdata($data);
                redirect('Operator/statusDaftar');
            }
        } else {
            $this->session->set_flashdata('message', '
       <div class="alert alert-danger" role="alert">
     Silahkan Ulangi Pemilihan Siswa Yg akan didaftarkan
      </div>');
            $this->session->unset_userdata('id_pendaftar');
            $this->session->unset_userdata('nisn');
            redirect('Operator/FormBiodata');
        }
    }

    public function Wali()
    {
        if (empty($this->session->userdata('id_pendaftar')) || empty($this->session->userdata('email'))) {
            $this->session->set_flashdata('message', '
       <div class="alert alert-danger" role="alert">
     Silahkan  Pilih Siswa Yg akan didaftarkan
      </div>');
            redirect('Operator/Pendaftaran');
        }
        $data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
        $data['pendaftar'] = $this->db->get_where('register', ['nisn' => $this->session->userdata('nisn'), 'noOps' => $data['user']['id']])->row_array();
        $data['title'] = 'Pendaftaran';
        $data['wali'] = $this->db->get_where('wali', ['nisn' => $data['pendaftar']['nisn']])->row_array();
        $data['setting'] = $this->db->get('kop_surat')->row_array();
        $data['pendidikan'] = $this->db->get('pendididikan')->result_array();
        $data['penghasilan'] = $this->db->get('penghasilan')->result_array();
        $data['pekerjaan'] = $this->db->get('pekerjaan')->result_array();
        $data['alamat'] = $this->operator->getAlamat($data['pendaftar']['id']);
        $this->load->view('themplate/Operator/header', $data);
        $this->load->view('themplate/Operator/sidebar', $data);
        $this->load->view('themplate/Operator/topbar', $data);
        $this->load->view('Operator/formWali', $data);
        $this->load->view('themplate/Operator/footer', $data);
    }

    public function simpanDataWali()
    {
        if (empty($this->session->userdata('id_pendaftar')) || empty($this->session->userdata('email'))) {
            $this->session->set_flashdata('message', '
       <div class="alert alert-danger" role="alert">
     Silahkan  Pilih Siswa Yg akan didaftarkan
      </div>');
            redirect('Operator/Pendaftaran');
        }
        $operator = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
        $userdata = $this->db->get_where('register', ['id' => $this->session->userdata('id_pendaftar'), 'noOps' => $operator['id']])->row_array();
        $data = [
            'idRegister' => htmlspecialchars($userdata['id']),
            'ayah' => htmlspecialchars($this->input->post('ayah')),
            'ibu' => htmlspecialchars($this->input->post('ibu')),
            'nikAyah' => htmlspecialchars($this->input->post('nikAyah')),
            'nikIbu' => htmlspecialchars($this->input->post('nikIbu')),
            'TanggalLahirAyah' => htmlspecialchars($this->input->post('tanggalLahirAyah')),
            'TanggalLahirIbu' => htmlspecialchars($this->input->post('tanggalLahirIbu')),
            'pendidikanAyah' => htmlspecialchars($this->input->post('pendidikanAyah')),
            'pendidikanIbu' => htmlspecialchars($this->input->post('pendidikanIbu')),
            'pekerjaanAyah' => htmlspecialchars($this->input->post('pekerjaanAyah')),
            'pekerjaanIbu' => htmlspecialchars($this->input->post('pekerjaanIbu')),
            'penghasilanAyah' => htmlspecialchars($this->input->post('penghasilanAyah')),
            'penghasilanIbu' => htmlspecialchars($this->input->post('penghasilanIbu')),
            'notelepon' => htmlspecialchars($this->input->post('notelepon')),
            'status' => 1
        ];
        if ($this->operator->simpanWali($data) > 0) {
            echo json_encode(['pesan' => 'ok']);
        } else {
            echo json_encode(['pesan' => 'gagal']);
        }
    }

    // menambil data siswa yang akan di daftarkan oleh operator
    public function get_dataNilai()
    {
        $list = $this->operator->get_datatables();
        // var_dump($list);
        // die;
        $data = array();
        $no = @$_POST['start'];

        // lakukan perulangan data dari model
        foreach ($list as $item) {
            $no++;
            $row = array();
            $row[] = $no . ".";
            $row[] = $item->nisn;
            $row[] = $item->nama;
            $row[] = $item->total;
            // $row[] = '<button data-nisn="' . $item->nisn . '" data-id="' . $item->id . '" data-target=".bd-example-modal-lg" class="badge badge-primary viewPendaftar"><i class="fa fa-pencil"></i> Liat</button>';
            $data[] = $row;
        }
        $output = array(
            "draw" => @$_POST['draw'],
            "recordsTotal" => $this->operator->count_all(),
            "recordsFiltered" => $this->operator->count_filtered(),
            "data" => $data,
        );
        // output to json format

        echo json_encode($output);
    }

    // upload nilai
    public function uploadNilai()
    {

        if (isset($_POST['import'])) {

            $ext = pathinfo($_FILES['nilai']['name'], PATHINFO_EXTENSION);

            $nama_file_baru = 'datanilai.xlsx';
            // cek apakah file excel yang di upload
            if ($ext == 'xlsx') {
                $config['upload_path'] = 'assets/fileupload/';
                $config['allowed_types'] = 'xlsx';
                $config['file_name'] =  $nama_file_baru;
                $this->load->library('upload', $config);
                if (file_exists('assets/fileupload/' . $nama_file_baru)) {
                    unlink('assets/fileupload/' . $nama_file_baru);
                }
                // cek jika upload gagal
                if (!$this->upload->do_upload('nilai')) {
                    $this->session->set_flashdata('message', '
                    <div class="alert alert-danger" role="alert">
                  Gagal Upload Nilai
                   </div>');
                    redirect('Operator/Nilai');
                } else {
                    try {
                        $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
                        $spreadsheet = $reader->load('assets/fileupload/' . $nama_file_baru);
                        $sheet = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
                        $this->load->model('Model_uploadNilai', 'uploadNilai');
                        $result = $this->uploadNilai->prosesUploadNilai($sheet);
                        $this->session->set_tempdata('dataflash',$result ,60);
                        $this->session->set_flashdata('flash', 'ok');
                        redirect('Operator/Nilai');
                    } catch (\Exception $exception) {
                        $this->session->set_flashdata('message', '
                        <div class="alert alert-danger" role="alert">
                     ' . $exception->getMessage() . '
                       </div>');
                        redirect('Operator/Nilai');
                    }
                }
            } else {
                $this->session->set_flashdata('message', '
                <div class="alert alert-danger" role="alert">
                Data Yang Di Upload Buka Excel
               </div>');
                redirect('Operator/Nilai');
            }
        } else {
            $this->session->set_flashdata('message', '
                <div class="alert alert-danger" role="alert">
               Silahkan Upload Melalui Form
               </div>');
            redirect('Operator/Nilai');
        }
    }



    public function uploadBiodata()
    {

        if (isset($_POST['import'])) {

            $ext = pathinfo($_FILES['biodata']['name'], PATHINFO_EXTENSION);

            $nama_file_baru = 'databiodata.xlsx';
            // cek apakah file excel yang di upload
            if ($ext == 'xlsx') {
                $config['upload_path'] = 'assets/fileupload/';
                $config['allowed_types'] = 'xlsx';
                $config['file_name'] =  $nama_file_baru;
                $this->load->library('upload', $config);
                if (file_exists('assets/fileupload/' . $nama_file_baru)) {
                    unlink('assets/fileupload/' . $nama_file_baru);
                }
                // cek jika upload gagal
                if (!$this->upload->do_upload('biodata')) {
                    $this->session->set_flashdata('message', '
                    <div class="alert alert-danger" role="alert">
                Gagal Upload Biodata
                   </div>');
                    redirect('Operator/Pendaftaran');
                    // else jika berhasil uploade
                } else {
                    try {
                       
                        

                        $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
                        $spreadsheet = $reader->load('assets/fileupload/' . $nama_file_baru);
                        $sheet = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
                        $hasilUploadBiodata = $this->m_uploadBiodata->prosesUploadBiodata($sheet);

                        $this->session->set_tempdata('dataflash', $hasilUploadBiodata,60);
                        $this->session->set_flashdata('flash', ' ');
                    //     $this->session->set_flashdata('message', '
                    //     <div class="alert alert-success" role="alert">
                    //     <button type="button" class="btn btn-danger btn-sm close" data-dismiss="alert" aria-label="Close">
                    //     <span aria-hidden="true">&times;</span>
                    //   </button>
                    //     <h4 class="alert-heading">Hasil Upload</h4>
                    //     <table class="table table-sm">
                    //         <tr>
                    //            <td>Data Baru Berhasil Upload</td>
                    //            <td>:</td>
                    //            <td>' . $hasil['upload'] . '</td>
                    //         </tr>
                    //         <tr>
                    //         <td>Gagal Upload NISN Sudah Digunakan</td>
                    //         <td>:</td>
                    //         <td style="color:red;">' . $hasil['namaNisnDuplikast'] . '</td>
                    //         </tr>
                    //         <tr>
                    //             <td>Data Gagal Upload Sdh. Verifikasi</td>
                    //             <td>:</td>
                    //             <td style="color:red;">' . $hasil['sudahVerifikasi'] . '</td>
                    //         </tr>
                    //         <tr>
                    //         <td>Data Gagal Upload Email Duplikat</td>
                    //         <td>:</td>
                    //         <td style="color:red;">' . $hasil['emailDuplikat'] . '</td>
                    //         </tr>
                    //         <tr>
                    //         <td>Data Gagal Upload nisn > 10 karakter</td>
                    //         <td>:</td>
                    //         <td style="color:red;">' . $hasil['nisnLebih'] . '</td>
                    //         </tr>
                    //     </table>
                    //     <p>Silahkan Cek Kembali File Excel Import Data</p>
                       
                    //   </div>');
                        redirect('Operator/Pendaftaran');
                    } catch (\Exception $exception) {
                        $this->session->set_flashdata('message', '
                        <div class="alert alert-danger" role="alert">
                     ' . $exception->getMessage() . '
                       </div>');
                        redirect('Operator/Pendaftaran');
                    }
                }
            } else {
                // jika bukan file excel yang di upload
                $this->session->set_flashdata('message', '
                <div class="alert alert-danger" role="alert">
              Data yang di upload bukan format excel
               </div>');
                redirect('Operator/Pendaftaran');
            }
        } else {
            $this->session->set_flashdata('message', '
                <div class="alert alert-danger" role="alert">
               Silahkan Upload Melalui Form
               </div>');
            redirect('Operator/Pendaftaran');
        }
    }


    // ====================================get data biodata dari ajak opration js
    public function SimpanBiodata()
    {
        $longitude = $this->input->post('longitude');
        $sekolah = $this->db->get_where('kop_surat', ['id' => 1])->row_array();
        $longSekolah = $sekolah['longitude'];
        $jarak = $this->akun->jarak($longSekolah, $longitude) * 1000;
        $jarak = round($jarak, 2);
        $data = [
            'nama' => htmlspecialchars($this->input->post('nama')),
            'nisn' => htmlspecialchars($this->input->post('nisn')),
            'tempatLahir' => htmlspecialchars($this->input->post('tempatLahir')),
            'tglLahir' => htmlspecialchars($this->input->post('tglLahir')),
            'kk' => htmlspecialchars($this->input->post('kk')),
            'jk' => htmlspecialchars($this->input->post('jk')),
            'noHp' => htmlspecialchars($this->input->post('noHp')),
            'tinggiBadan' => htmlspecialchars($this->input->post('tinggiBadan')),
            'beratBadan' => htmlspecialchars($this->input->post('beratBadan')),
            'sekolahAsal' => htmlspecialchars($this->input->post('sekolahAsal')),
            'npsn' => htmlspecialchars($this->input->post('npsn')),
            'provinsi' => htmlspecialchars($this->input->post('provinsi')),
            'kota' => htmlspecialchars($this->input->post('kota')),
            'kecamatan' => htmlspecialchars($this->input->post('kecamatan')),
            'desa' => htmlspecialchars($this->input->post('desa')),
            'rt' => htmlspecialchars($this->input->post('rt')),
            'rw' => htmlspecialchars($this->input->post('rw')),
            'longitude' => $longitude,
            'kodePos' => htmlspecialchars($this->input->post('kodePos')),
            'alamat' => htmlspecialchars(trim($this->input->post('alamat'))),
            'agama' => htmlspecialchars(trim($this->input->post('agama'))),
            'anak_ke' => htmlspecialchars(trim($this->input->post('anak_ke'))),
            'jarak' => $jarak,
            'usia' => $this->akun->hitungUsia($this->input->post('tglLahir')),
            'statusDaftar' => 1
        ];

        if ($this->operator->prosesBiodata($data) > 0) {
            echo json_encode(['pesan' => 'ok',]);
        } else {
            echo json_encode(['pesan' => 'gagal']);
        }
    }




    // Get data longitudeBy user
    public function getLongitudeByUser()
    {

        $data = $this->db->get_where('register', ['id' => $this->session->userdata('id_pendaftar')])->row_array();
        $result = [
            "longitude" => $data['longitude']
        ];

        echo json_encode($result);
        // echo json_encode($this->akun->prosesGetDataLongByUser());
    }

    // get data jenis afirmasi
    public function jenisAfirmasi()
    {
        echo json_encode($this->akun->jenisAfirmasi()->result_array());
    }

    // get data afirmasi by id
    public function getAfirmasiById()
    {
        echo json_encode($this->akun->getAfirmasiById($_POST['id'])->row_array());
    }

    // load nilai raport()
    public function loadDataRaportByPendaftar(){
        if(isset($_POST['key'])){
            if ($_POST['key'] == '34$8882998iu@!'){
                // ambil data raport nya
                echo json_encode($this->operator->getDataRaportByid($this->session->userdata('id_pendaftar')));

            }else{
                return false;
                ;
            }
                

        }else{
            return false;
        }
    }

 // Simpen data pendaftaran
 public function saveDaftar(){
    
    if (isset($_POST['jalurPpdb'])){
      $this->load->model('Ppdb_model', 'ppdb');
      $message = [];
      $jalur = $this->ppdb->getDataJalur($_POST['jalurPpdb']);
      if($jalur['input_nilai']==1){
        // prepare data sesuai syarat khusus
        $dataNilai=MyFilter::fPostRaport($_POST);
        $this->dataNilai=$dataNilai;
      }
      if($jalur['inputPrestasi']==1){
        // iput prestasi di perlukan
           $dataPrestasi=MyFilter::fPostKejuaraan($_POST);
           $this->dataPrestasi=$dataPrestasi;
          
      }
       if($jalur['input_afirmasi']==1){
           // iput prestasi di perlukan
           $dataAfirmasi=MyFilter::fPostAfirmasi($_POST);
           $this->dataAfirmasi = $dataAfirmasi;
      }

      $result= $this->operator->simpanDataPenftaran($this->dataAfirmasi,$this->dataPrestasi,$this->dataNilai,$jalur);
      if($result == true){
        $this->session->unset_userdata('id_pendaftar');
        $this->session->unset_userdata('nisn');
        $message=['pesan'=>'ok'];
        echo json_encode($message);
      }else{
         $message=['pesan'=>'error'];
         echo json_encode($message);
      }
       
    }else{
      // gagal Simpan
      $message=['pesan'=>'error'];
      echo json_encode($message);
       
    }
      
  }


    // get data penyelengara
    public function penyelengara()
    {
        echo json_encode($this->akun->dataPeyelengara()->result_array());
    }

    // memilih kategori kejuaraan berdasarkan penyelengagara
    public function KategoriKejuaraan()
    {
        echo json_encode($this->akun->KategoriKejuaraan($_POST['id'])->result_array());
    }

    public function tingkatPrestasi()
    {
        echo json_encode($this->akun->tingkatKejuaraan($_POST['id'])->result_array());
    }


    // cetak bukti pendaftaran
    public function cetakBuktiDaftar($koreg)
    {
        if(!isset($koreg)){
            redirect('Operator/Pendaftaran');
        }

        $data= $this->item_m->getdataprintByjalur($koreg);
        $mpdf = new \Mpdf\Mpdf(['debug' => false,
            'format' => 'Legal-P',
            'margin_left' => 22,
            'margin_right' => 20,
            'margin_top' => 15,
            'margin_bottom' => 0,
            'margin_header' => 0,
            'margin_footer' => 0,
        ]);
        $html = '';
     
        $html = $this->load->view('Home2/Cetak', $data, true);
        $html2 = $this->load->view('Home2/perjanjianMutlakOrangtua', $data, true);
        $mpdf->WriteHTML($html);
        $mpdf->AddPage();
        $mpdf->WriteHTML($html2);
        $mpdf->SetHTMLFooter('
    <table width="100%">
        <tr>
            <td width="33%" style="font-size:8px;">{DATE j-m-Y}</td>
            <td width="33%" align="center" style="font-size:8px;">{PAGENO}/{nbpg}</td>
            <td width="33%" style="text-align: right; font-size:8px;">' . $data['dataSekolah']['nama_sekolah']  . '</td>
        </tr>
    </table>');
        $mpdf->Output($koreg . '-' . $data['user']['nama'] . '-' . $data['user']['sekolahAsal'] . '-' . $data['user']['nisn'] . '.pdf', 'I');
    }

    public function CekNisn(){
     $nisn = $_POST['nisnsiswa'] ? $_POST['nisnsiswa'] : false;


      $cek =  $this->operator->cekEmailOrNISN('nisn', $nisn);
        if($cek > 0){
            echo "false";
        }else{
            echo "true";
        }
       
    }

    public function CekEmail(){
        $email = $_POST['email'] ? $_POST['email'] : false;

        $cek = $this->operator->cekEmailOrNISN('email', $email);
        if($cek > 0){
            echo "false";
        }else{
            echo "true";
        }
       
    }
}
