<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Ijin extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('ijin_model','ijin');
		$this->load->model('kelas_model');
		$this->load->model('pelajaran_model');
		$this->load->helper('url');
		if ($this->session->userdata('username')=='') {
            redirect('login');
        }
	}

	public function index()
	{
		$data['pelajaran'] = $this->pelajaran_model->view();
		$this->template->display('admin/ijin',$data);
	}
	public function import()
	{
		$this->template->display('admin/imijin');
	}
	public function upload(){
		$file_mimes = array('application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		$gagal=0;
		$sukses=0;
		if(isset($_FILES['userfile']['name']) && in_array($_FILES['userfile']['type'], $file_mimes)) {

			$arr_file = explode('.', $_FILES['userfile']['name']);
			$extension = end($arr_file);

			if($extension == 'csv'){
				$reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
			} elseif($extension == 'xlsx') {
				$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
			} else {
				$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
			}

			$spreadsheet = $reader->load($_FILES['userfile']['tmp_name']);

			$sheetData = $spreadsheet->getActiveSheet()->toArray();
			for($i = 1;$i < count($sheetData);$i++)
			{
				$tgl = $sheetData[$i]['0'];
				$absen = $sheetData[$i]['1'];
				$status = $sheetData[$i]['2'];
				$ket = $sheetData[$i]['3'];
				if ($absen =='') {
						$gagal++;
				} else {
						//echo "INSERT INTO users (`user_id`, `nama`, `jurusan`, `angkatan`, `pararel`, `alamat`, `telp`, `password`, `email`, `status`, `status_user`, `agama`, `kode_mapel`) VALUES ('$user_id', '$nama', '$jurusan', '$angkatan', '$paralel', '$alamat', '$telp', '$password', '$email', '$status', '$status_user', '$agama', '$kode_mapel')"."<br>";
						$query = "INSERT INTO `web_ijin`(`tgl`, `absen`, `status`, `ket`) VALUES
						('$tgl', '$absen', '$status', '$ket')";
						$hasil = $this->db->query($query);
						if ($hasil) $sukses++;
							else $gagal++;
				}
			}
			if($sukses > 0){
					$pesan = "Jumlah data yang sukses diimport : ".$sukses." dan Jumlah data yang gagal diimport : ".$gagal;
					$ke = "../../ijin";
					echo "<script>alert('$pesan');location.href='$ke'</script>";
				} else {
					$pesan = "Gagal Import Ijin";
					$ke = "../../ijin/import";
					echo "<script>alert('$pesan');location.href='$ke'</script>";
				}
		}
	}
	public function balikin($str){
		$search = array ("'xpsijix'");
		$replace = array ("'");
		$str = preg_replace($search,$replace,$str);
		return $str;
	}
	public function ajax_list()
	{
		$list = $this->ijin->get_datatables();
		$data = array();
		$no = $_POST['start'];
		$atts = array(
				'width'       => 800,
				'height'      => 600,
				'scrollbars'  => 'yes',
				'status'      => 'yes',
				'resizable'   => 'yes',
				'screenx'     => 0,
				'screeny'     => 0,
				'window_name' => '_blank',
				'class'		=> 'btn btn-warning btn-sm'
		);
		$kehadiran='';
		foreach ($list as $ijin) {
			$no++;
			$row = array();
			$row[] = $no;
			$row[] = '<a class="btn btn-white btn-primary btn-sm" href="javascript:void(0)" title="Edit Log" onclick="edit_ijin('."'".$ijin->id."'".')"><i class="glyphicon glyphicon-pencil"></i></a>
				  <a class="btn btn-white btn-danger btn-sm" href="javascript:void(0)" title="Hapus" onclick="delete_ijin('."'".$ijin->id."'".')"><i class="glyphicon glyphicon-trash"></i></a>';

			$row[] = $ijin->tgl;
			$ceksiswa=$this->db->query("SELECT * FROM web_siswa WHERE absen='".$ijin->absen."'");
			foreach ($ceksiswa->result() as $baris) {
				$namasiswa=balikin($baris->NM_PEGAWAI);
				$kodekelas=$baris->KD_JENIS_KETENAGAAN;
				$foto=$baris->filex1;
			}
			$row[] = $namasiswa;

			$cekst=$this->db->query("SELECT * FROM web_status WHERE kd_jenis='".$ijin->status."'");
			foreach ($cekst->result() as $rsst) {
				$kehadiran=$rsst->status;
			}
			$row[] = $kehadiran;
			$row[] = $ijin->ket;
			if ($ijin->file=='') {
				$row[] = "Tidak ada file";
			} else {
				$row[] = "<a class='btn btn-white btn-danger btn-sm' href=".base_url()."upload/ijin/".$ijin->file."><i class='glyphicon glyphicon-download'></i> ".$ijin->file."</a>";
			}
			$data[] = $row;
		}

			$output = array(
						"draw" => $_POST['draw'],
						"recordsTotal" => $this->ijin->count_all(),
						"recordsFiltered" => $this->ijin->count_filtered(),
						"data" => $data,
				);

		echo json_encode($output);
	}
	public function listsiswa(){
		$kode = $this->input->post('kd_jenis');
		$kota = $this->kelas_model->viewkelas($kode);
		$lists = "<option value=''>Pilih Individu</option>";

		foreach($kota as $data){
			$lists .= "<option value='".$data->absen."'>".$data->NM_PEGAWAI."</option>"; // Tambahkan tag option ke variabel $lists
		}

		$callback = array('list_kelas'=>$lists); // Masukan variabel lists tadi ke dalam array $callback dengan index array : list_kota

		echo json_encode($callback); // konversi varibael $callback menjadi JSON
	}

	public function ajax_edit($id)
	{
		$data = $this->ijin->get_by_id($id);
		echo json_encode($data);
	}
	public function ajax_add()
	{
		$this->_validate();
		if($_FILES['userfile']['name']!=""){
		$this->load->library('upload');
		$config['upload_path'] = './upload/ijin/';
		$config['allowed_types'] = 'pdf|jpeg|gif|jpg|png';
		$config['max_size'] = '1024';
		$config['overwrite'] = FALSE;
		$this->upload->initialize($config);
		if( ! $this->upload->do_upload("userfile")){
		    echo json_encode(array("status" => FALSE));
				$nama_berkas ='';
				exit();
		}
		$nama_berkas = $this->upload->file_name;
		$data = array(
			'tgl' => $this->input->post('tgl'),
			'absen' => $this->input->post('kikd'),
			'status' => $this->input->post('status'),
			'ket' => $this->input->post('ket'),
			'file' => $nama_berkas,
			);
		} else {
		$data = array(
			'tgl' => $this->input->post('tgl'),
			'absen' => $this->input->post('kikd'),
			'status' => $this->input->post('status'),
			'ket' => $this->input->post('ket'),
			);
		}
		$insert = $this->ijin->save($data);

		echo json_encode(array("status" => TRUE));
	}
	public function ajax_update()
	{
		$this->_validate();
		$config['upload_path']          = './upload/ijin/';
		$config['allowed_types']        = 'jepg|pdf|jpg|png';
		$config['max_size']             = 1024;

		$this->load->library('upload', $config);
		if($_FILES['userfile']['name']!=""){
			$this->load->library('upload');
			$config['upload_path'] = './upload/ijin/';
			$config['allowed_types'] = 'pdf|jpeg|gif|jpg|png';
			$config['max_size'] = '1024';
			$config['overwrite'] = FALSE;
			$config['file_name'] = $nmfile;
			$this->upload->initialize($config);
			if( ! $this->upload->do_upload("userfile")){
			    echo json_encode(array("status" => FALSE));
					exit();
			}
			$nama_berkas = $this->upload->file_name;
			$data = array(
				'tgl' => $this->input->post('tgl'),
				'absen' => $this->input->post('kikd'),
				'status' => $this->input->post('status'),
				'ket' => $this->input->post('ket'),
				'file' => $nama_berkas,
				);
		} else {
			$data = array(
				'tgl' => $this->input->post('tgl'),
				'absen' => $this->input->post('kikd'),
				'status' => $this->input->post('status'),
				'ket' => $this->input->post('ket'),
				);
		}


		$this->ijin->update(array('id' => $this->input->post('id')), $data);
		echo json_encode(array("status" => TRUE));
	}
	public function ajax_delete($id)
	{
		$ijin = $this->ijin->get_by_id($id);
		$this->ijin->delete_by_id($id);
		echo json_encode(array("status" => TRUE));
	}

	private function _validate()
	{
		$data = array();
		$data['error_string'] = array();
		$data['inputerror'] = array();
		$data['status'] = TRUE;

		if($this->input->post('kikd') == '')
		{
			$data['inputerror'][] = 'kikd';
			$data['error_string'][] = 'Nama Individu wajib di pilih';
			$data['status'] = FALSE;
		}
		if($this->input->post('status') == '')
		{
			$data['inputerror'][] = 'status';
			$data['error_string'][] = 'Status ijin wajib di pilih';
			$data['status'] = FALSE;
		}
		if($this->input->post('ket') == '')
		{
			$data['inputerror'][] = 'ket';
			$data['error_string'][] = 'Keterangan ijin wajib di pilih';
			$data['status'] = FALSE;
		}
		if($data['status'] === FALSE)
		{
			echo json_encode($data);
			exit();
		}
	}

}
