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

class Individu extends CI_Controller {

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

	public function index()
	{
		$this->template->display('admin/siswa');
	}
	public function ujicoba()
	{
		$this->template->display('admin/ujicoba');
	}
	public function import()
	{
		$this->template->display('admin/imsiswa');
	}
	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++)
			{
				$nama = cegah($sheetData[$i]['0']);
				$absen = cegah($sheetData[$i]['1']);
				$password = md5($sheetData[$i]['2']);
				$alamat = $sheetData[$i]['3'];
				$nohp = $sheetData[$i]['4'];
				$kdkelompok = $sheetData[$i]['5'];
				$senin = $sheetData[$i]['6'];
				$selasa = $sheetData[$i]['7'];
				$rabu = $sheetData[$i]['8'];
				$kamis = $sheetData[$i]['9'];
				$jumat = $sheetData[$i]['10'];
				$sabtu = $sheetData[$i]['11'];
				$minggu = $sheetData[$i]['12'];
				$spesial= $sheetData[$i]['13'];
				if ($absen <>'') {
					$main = $this->db->get_where('web_siswa', array('absen'=>$absen));
					$adajawab=$main->num_rows();
					if ($adajawab>=1) {
						$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_siswa`
						(`NOMOR_INDUK`, `NM_PEGAWAI`, `ALAMAT`, `KD_JENIS_KETENAGAAN`, `NO_HP`, `NOMOR_INDUK_BARU`, `absen`, `SEN`, `SEL`, `RAB`, `KAM`, `JUM`, `SAB`, `MIN`, `password`, `spesial`) VALUES
						('$absen', '$nama', '$alamat', '$kdkelompok', '$nohp', '$absen', '$absen', '$senin', '$selasa', '$rabu', '$kamis', '$jumat', '$sabtu', '$minggu', '$password', '$spesial')";
						$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 = "../../individu";
					echo "<script>alert('$pesan');location.href='$ke'</script>";
				} else {
					$pesan = "Gagal Import Individu";
					$ke = "../../individu/import";
					echo "<script>alert('$pesan');location.href='$ke'</script>";
				}
		}
	}
	public function lihatpresensi()
	{
		$this->template->display('admin/lihatpresensi');
	}
	public function lihatjurnal()
	{
		$this->template->display('admin/lihatjurnal');
	}
	public function balikin($str){
		$search = array ("'xpsijix'");
		$replace = array ("'");
		$str = preg_replace($search,$replace,$str);
		return $str;
	}
	public function ajax_list()
	{
		$list = $this->siswa->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'
		);
		foreach ($list as $siswa) {
			$no++;
			$row = array();
			$row[] = $no;
			$row[] = '<a class="btn btn-white btn-primary btn-sm" href="javascript:void(0)" title="Edit Individu" onclick="edit_siswa('."'".$siswa->NIP."'".')"><i class="glyphicon glyphicon-pencil"></i></a>
				  <a class="btn btn-white btn-danger btn-sm" href="javascript:void(0)" title="Hapus" onclick="delete_siswa('."'".$siswa->NIP."'".')"><i class="glyphicon glyphicon-trash"></i></a>';
			$row[] = $siswa->absen;
			$row[] = $siswa->NM_PEGAWAI;
			$row[] = $siswa->NOMOR_INDUK_BARU;
			$cekkelas=$this->db->query("SELECT * FROM web_kelas WHERE kode='".$siswa->KD_JENIS_KETENAGAAN."'");
			foreach ($cekkelas->result() as $baris) {
				$namakelas=$baris->nama;
			}
			$row[] =$namakelas;
			if ($siswa->hardware_kode == "") {
				$row[] = '<a class="btn btn-white btn-success btn-sm" href="#" ><i class="glyphicon glyphicon-ok"></i> '.$siswa->hardware_kode.'</a>';
			} else {
				$row[] = '<a class="btn btn-white btn-danger btn-sm" href="javascript:void(0)" title="Edit" onclick="edit_status('."'".$siswa->NIP."'".",'".$siswa->hardware_kode."'".')"><i class="glyphicon glyphicon-lock"></i> '.$siswa->hardware_kode.'</a>';
			}
			if ($siswa->password == md5($siswa->absen)) {
				$row[] = '<a class="btn btn-white btn-success btn-sm" href="#" ><i class="glyphicon glyphicon-ok"></i> OK </a>';
			} else {
				$row[] = '<a class="btn btn-white btn-danger btn-sm" href="javascript:void(0)" title="Edit" onclick="reset_password('."'".$siswa->NIP."'".",'".$siswa->absen."'".')"><i class="glyphicon glyphicon-lock"></i> Default</a>';
			}
			if ($siswa->spesial == "1") {
				$row[] = '<a class="btn btn-white btn-success btn-sm" href="javascript:void(0)" title="Edit" onclick="edit_spesial('."'".$siswa->NIP."'".",'".$siswa->spesial."'".')" ><i class="glyphicon glyphicon-ok"></i> On </a>';
			} else {
				$row[] = '<a class="btn btn-white btn-danger btn-sm" href="javascript:void(0)" title="Edit" onclick="edit_spesial('."'".$siswa->NIP."'".",'".$siswa->spesial."'".')"><i class="glyphicon glyphicon-lock"></i> Off</a>';
			}
			$data[] = $row;
		}

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

		echo json_encode($output);
	}
	public function ubah_status()
	{
		$status = $this->input->post('statusnya');
		if ($status<>'') {
			$statusnya='';
		}
		$data = array(
				'hardware_kode' => $statusnya,
			);

		$this->siswa->update(array('NIP' => $this->input->post('idnya')), $data);
		echo json_encode(array("status" => TRUE));
	}
	public function reset_password()
	{
		$status = $this->input->post('statusnya');
		if ($status<>'') {
			$statusnya=md5($status);
		}
		$data = array(
				'password' => $statusnya,
			);

		$this->siswa->update(array('NIP' => $this->input->post('idnya')), $data);
		echo json_encode(array("status" => TRUE));
	}
	public function ubah_spesial()
	{
		$status = $this->input->post('statusnya');
		if ($status=='0') {
			$statusnya='1';
		} else {
			$statusnya='0';
		}
		$data = array(
				'spesial' => $statusnya,
			);

		$this->siswa->update(array('NIP' => $this->input->post('idnya')), $data);
		echo json_encode(array("status" => TRUE));
	}
	public function cetakku()
	{
		$this->load->view('admin/cetakformulir');

	}
	public function export()
	{
		header("Content-type: application/vnd-ms-excel");
		header("Content-Disposition: attachment; filename=DataSiswa.xls");
		?>
		<table border="1">
					<thead>
					<tr>
						<th width="3%"><div align="center" >No</div></th>
						<th width="9%"><div align="center" >No Daftar</div></th>
						<th width="15%"><div align="center" >No Daftar Ulang</div></th>
						<th width="10%"><div align="center" >Nama</div></th>
						<th width="10%"><div align="center" >Tempat, Tanggal Lahir</div></th>
						<th width="2%"><div align="center" >JK</div></th>
						<th width="39%"><div align="center" >Alamat</div></th>
						<th width="10%"><div align="center" >No HP</div></th>
						<th width="10%"><div align="center" >NISN</div></th>
						<th width="10%"><div align="center" >NIK</div></th>
						<th width="20%"><div align="center" >Asal Sekolah</div></th>
						<th width="2%"><div align="center" >Jurusan</div></th>
						<th width="2%"><div align="center" >Gelombang</div></th>
					</tr>
					</thead>
		<tbody>
		<?php
		$dua=$this->db->query("SELECT * FROM `biodata_siswa`");
		$no=1;
		foreach ($dua->result() as $row) {
						$id=$row->absen;
						$nodaftar=$row->nodaftar;
						$nodaftarulang=$row->nodaftarulang;
						$nama=balikin($row->nama);
						$tem_lahir=$row->tem_lahir;
						$jurusan1=$row->jurusan1;
						$tgl=$row->tgl;
						$bln=$row->bln;
						$tahun=$row->tahun;
						$alamat=$row->alamat;
						$hp=$row->hp;
						$nisn=$row->nisn;
						$nik=$row->nik;
						$asal_sek=$row->asal_sek;
						$jkel=$row->jkel;
						$gelombang=$row->gelombang;
						?>
						  <tr >
						  <td class="ttl" align="center"><?php echo $no;?></td>
							<td class="ul" align="center"><?php echo "19/NU/".$nodaftar;?></td>
							<td class="ul" align="center"><?php echo "'".$nodaftarulang;?></td>
							<td class="ul"><?php echo $nama;?></td>
							<td class="ul"><?php echo $tem_lahir.", ".$tgl."-".$bln."-".$tahun;?></td>
							<td class="ul"><?php echo $jkel;?></td>
							<td class="ul"><?php echo $alamat;?></td>
							<td class="ul"><?php echo "'".$hp;?></td>
							<td class="ul"><?php echo "'".$nisn;?></td>
							<td class="ul"><?php echo "'".$nik;?></td>
							<td class="ul"><?php echo $asal_sek;?></td>
							<td class="ul"><?php echo $jurusan1;?></td>
							<td align="center" class="ul"><strong><?php echo $gelombang;?></strong></td>
						  </tr>
						  <?php $no++;}?>
					</tbody>
		</table>
	<?php
	}
	public function ajax_edit($id)
	{
		$data = $this->siswa->get_by_id($id);
		echo json_encode($data);
	}

	public function ajax_add()
	{
		$this->_validate();
		$hariini = date("Y-m-d");
		$data = array(
				'absen' => $this->input->post('absen'),
				'password' => md5($this->input->post('absen')),
				'NM_PEGAWAI' => $this->input->post('nama'),
				'ALAMAT' => $this->input->post('alamat'),
				'NO_HP' => $this->input->post('nohp'),
				'KD_JENIS_KETENAGAAN' => $this->input->post('kd_jenis'),
				'SEN' => $this->input->post('senin'),
				'SEL' => $this->input->post('selasa'),
				'RAB' => $this->input->post('rabu'),
				'KAM' => $this->input->post('kamis'),
				'JUM' => $this->input->post('jumat'),
				'SAB' => $this->input->post('sabtu'),
				'MIN' => $this->input->post('minggu'),
				'jenispegawai' => $this->input->post('jenispegawai'),
			);

		$insert = $this->siswa->save($data);

		echo json_encode(array("status" => TRUE));
	}
	public function settingjam()
	{


				$sen= $this->input->post('senin');
				$sel=$this->input->post('selasa');
				$rab= $this->input->post('rabu');
				$kam= $this->input->post('kamis');
				$jum= $this->input->post('jumat');
				$sab= $this->input->post('sabtu');
				$min= $this->input->post('minggu');
			$this->db->query("UPDATE web_siswa SET SEN='$sen',SEL='$sel',RAB='$rab',KAM='$kam',JUM='$jum',SAB='$sab',MIN='$min' WHERE 1");

		echo json_encode(array("status" => TRUE));
	}
	public function ajax_update()
	{
		$this->_validate();
		$data = array(
				'absen' => $this->input->post('absen'),
				'NM_PEGAWAI' => $this->input->post('nama'),
				'ALAMAT' => $this->input->post('alamat'),
				'NO_HP' => $this->input->post('nohp'),
				'KD_JENIS_KETENAGAAN' => $this->input->post('kd_jenis'),
				'SEN' => $this->input->post('senin'),
				'SEL' => $this->input->post('selasa'),
				'RAB' => $this->input->post('rabu'),
				'KAM' => $this->input->post('kamis'),
				'JUM' => $this->input->post('jumat'),
				'SAB' => $this->input->post('sabtu'),
				'MIN' => $this->input->post('minggu'),
				'jenispegawai' => $this->input->post('jenispegawai'),
			);

		$this->siswa->update(array('NIP' => $this->input->post('id')), $data);
		echo json_encode(array("status" => TRUE));
	}
	public function du_update()
	{
		$data = array(
				'nodaftarulang' => $this->input->post('nodaftarulang'),
			);

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


	public function ajax_bulk_delete()
    {
        $list_id = $this->input->post('id');
        foreach ($list_id as $id) {
            $this->siswa->delete_by_id($id);
        }
        echo json_encode(array("status" => TRUE));
    }

	public function kirim_nama()
	{
		$result = $this->db->query("SELECT ip FROM web_komp WHERE publish='Y'");
		$Key="0";
		$hariini = date("Y-m-d");
		foreach ($result->result() as $ros) {
			$Connect = @fsockopen($ros->ip, "80", $errno, $errstr, 1);
			if($Connect){
				$ceknama=$this->db->query("SELECT NM_PEGAWAI as A,absen FROM web_siswa");
					foreach ($ceknama->result() as $baris) {
						$id=$baris->absen;
						$nama=$baris->A;
						$Connect = @fsockopen($ros->ip, "80", $errno, $errstr, 1);
						$soap_request="<SetUserInfo><ArgComKey Xsi:type=\"xsd:integer\">".$Key."</ArgComKey><Arg><PIN>".$id."</PIN><Name>".$nama."</Name></Arg></SetUserInfo>";
						$newLine="\r\n";
						fputs($Connect, "POST /iWsService HTTP/1.0".$newLine);
						fputs($Connect, "Content-Type: text/xml".$newLine);
						fputs($Connect, "Content-Length: ".strlen($soap_request).$newLine.$newLine);
						fputs($Connect, $soap_request.$newLine);
						$buffer="";
						while($Response=fgets($Connect, 1024)){
							$buffer=$buffer.$Response;
						}
						$buffer=Parse_Data($buffer,"<Information>","</Information>");
					}
			}
		}
		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('absen') == '')
		{
			$data['inputerror'][] = 'absen';
			$data['error_string'][] = 'Kode Absen wajib diisi';
			$data['status'] = FALSE;
		} elseif($this->input->post('id') == '') {
			$cek1=$this->db->query("SELECT absen FROM web_siswa WHERE absen='".$this->input->post('absen')."'");
			$hasilcek1=$cek1->num_rows();
			if ($hasilcek1 <> 0) {
				$data['inputerror'][] = 'absen';
				$data['error_string'][] = 'Absen sudah ada';
				$data['status'] = FALSE;
			}
		}

		if($this->input->post('nama') == '')
		{
			$data['inputerror'][] = 'nama';
			$data['error_string'][] = 'Nama wajib diisi';
			$data['status'] = FALSE;
		}
		if($this->input->post('kd_jenis') == '')
		{
			$data['inputerror'][] = 'kd_jenis';
			$data['error_string'][] = 'Kelompok wajib dipilih';
			$data['status'] = FALSE;
		}
		if($data['status'] === FALSE)
		{
			echo json_encode($data);
			exit();
		}
	}

}
