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

class Log extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('log_model','logg');
		$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/log',$data);
	}
	public function balikin($str){
		$search = array ("'xpsijix'");
		$replace = array ("'");
		$str = preg_replace($search,$replace,$str);
		return $str;
	}
	public function ajax_list()
	{
		$list = $this->logg->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 $logg) {
			$no++;
			$row = array();
			$row[] = $no;
			$row[] = '<a class="btn btn-white btn-primary btn-sm" href="javascript:void(0)" title="Edit Log" onclick="edit_log('."'".$logg->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_log('."'".$logg->id."'".')"><i class="glyphicon glyphicon-trash"></i></a>';

			$row[] = $logg->tgl;
			$row[] = $logg->jam;
			$fotoabsen=$logg->nip.date("Ymd",strtotime($logg->tgl)).'.jpg';
			$ceksiswa=$this->db->query("SELECT * FROM web_siswa WHERE absen='".$logg->nip."'");
			foreach ($ceksiswa->result() as $baris) {
				$namasiswa=balikin($baris->NM_PEGAWAI);
				$kodekelas=$baris->KD_JENIS_KETENAGAAN;
				$foto=$baris->filex1;
			}
			$row[] = '<img src="'.base_url().'upload/profil/'.$foto.'" height="100">';
			$row[] = $namasiswa;
			$cekkelas=$this->db->query("SELECT * FROM web_kelas WHERE kode='".$kodekelas."'");
			foreach ($cekkelas->result() as $baris) {
				$namakelas=$baris->nama;
			}
			$row[] =$namakelas;
			$row[] = $logg->komp;
			$cekstatus=$this->db->query("SELECT * FROM web_status WHERE kd_jenis='".$logg->status."'");
			foreach ($cekstatus->result() as $baris) {
				$namastatus=$baris->status;
			}
			$row[] =$namastatus;
			if ($logg->status == 1){
				$row[] = '<img src="'.base_url().'upload/selfie/masuk/'.$fotoabsen.'" height="100">';
			} elseif ($logg->status == 2) {
				$row[] = '<img src="'.base_url().'upload/selfie/pulang/'.$fotoabsen.'" height="100">';
			} elseif ($logg->status == 7) {
				$row[] = '<img src="'.base_url().'upload/selfie/wfh/'.$fotoabsen.'" height="100">';
			}
			$row[] = $logg->ket;
			$data[] = $row;
		}

			$output = array(
						"draw" => $_POST['draw'],
						"recordsTotal" => $this->logg->count_all(),
						"recordsFiltered" => $this->logg->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->logg->get_by_id($id);
		echo json_encode($data);
	}
	public function ajax_add()
	{
		$this->_validate();
		//$hariini = date("Y-m-d");
		//$jamini=date("H:i:s");
		if ($this->input->post('tglabsen') =="") {
			$hariini = date("Y-m-d");
		} else {
			$hariini=$this->input->post('tglabsen');
		}
		if ($this->input->post('jamabsen') =="") {
			$jamini=date("H:i:s");
		} else {
			$jamini=$this->input->post('jamabsen');
		}
		
		$data = array(
				'tgl' => $hariini,
				'jam' => $jamini,
				'nip' => $this->input->post('kikd'),
				'status' => $this->input->post('status'),
				'ket' => $this->input->post('ket'),
			);
		$cekstatus=$this->db->query("SELECT * FROM web_siswa WHERE absen='".$this->input->post('kikd')."'");
			foreach ($cekstatus->result() as $baris) {
				$namastatus=$baris->NM_PEGAWAI;
				$nomerhp=$baris->NO_HP;
			}
		$pesane=$namastatus." Telah absen tanggal ".$hariini." pukul ".$jamini." ";
		//kirimtelegram2($nomerhp,$pesane);
		$insert = $this->logg->save($data);

		echo json_encode(array("status" => TRUE));
	}
	public function ajax_update()
	{
		$this->_validate();
		if ($this->input->post('tglabsen') =="") {
			$hariini = date("Y-m-d");
		} else {
			$hariini=$this->input->post('tglabsen');
		}
		if ($this->input->post('jamabsen') =="") {
			$jamini=date("H:i:s");
		} else {
			$jamini=$this->input->post('jamabsen');
		}
		$data = array(
				'tgl' => $hariini,
				'jam' => $jamini,
				'nip' => $this->input->post('kikd'),
				'status' => $this->input->post('status'),
				'ket' => $this->input->post('ket'),
			);

		$this->logg->update(array('id' => $this->input->post('id')), $data);
		echo json_encode(array("status" => TRUE));
	}
	public function ajax_delete($id)
	{
		$logg = $this->logg->get_by_id($id);
		$this->logg->delete_by_id($id);
		echo json_encode(array("status" => TRUE));
	}
	public function tarik_data() {
		$result=$this->db->query("SELECT * FROM web_setting WHERE id='1'");
		foreach ($result->result() as $baris)  {
		$jam_masuk=$baris->jam_masuk;
		$batas_jam=$baris->batas_jam;
		$jam_pulang=$baris->jam_pulang;
		}
		$minimal=$jam_masuk;
		$waktu_masuk=$batas_jam;
		$jam_pulang=$jam_pulang;
		$result = $this->db->query("SELECT ip FROM web_komp WHERE publish='Y'");
		$Key="0";
		$hariini = date("Y-m-d");
		//echo $waktu_masuk;
		foreach ($result->result() as $ros) {
			$Connect = @fsockopen($ros->ip, "80", $errno, $errstr, 1);
			if($Connect){
					$soap_request="<GetAttLog><ArgComKey xsi:type=\"xsd:integer\">".$Key."</ArgComKey><Arg><PIN xsi:type=\"xsd:integer\">All</PIN></Arg></GetAttLog>";
					$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,"<GetAttLogResponse>","</GetAttLogResponse>");
				$buffer=explode("\r\n",$buffer);
				for($a=0;$a<count($buffer);$a++){
					$data=Parse_Data($buffer[$a],"<Row>","</Row>");
					$PIN=Parse_Data($data,"<PIN>","</PIN>");
					$DateTime=Parse_Data($data,"<DateTime>","</DateTime>");
					$Verified=Parse_Data($data,"<Verified>","</Verified>");
					$Status=Parse_Data($data,"<Status>","</Status>");
					$ceknama=$this->db->query("SELECT nip,NM_PEGAWAI as A,KD_JENIS_KETENAGAAN as B,NOMOR_INDUK as C,NOMOR_INDUk_BARU as D,NO_hp as hp,absen FROM web_siswa WHERE absen LIKE '$PIN'");
					foreach ($ceknama->result() as $baris) {
						$nipq=$baris->absen;
						$namapegawai=$baris->A;
					}
					$DateTime=trim($DateTime);
					$aa=explode(' ',$DateTime);
					unset($error,$st,$kett,$telat,$tepat_waktu);
					if (!empty($namapegawai)) {
						$tgl=$aa[0];
						$jam=$aa[1];
						$ip=$ros->ip;
						$cek1=$this->db->query("SELECT status,jam,ket FROM web_absen WHERE tgl='$tgl' AND nip='$nipq' AND status=1");
						$hasilcek1=$cek1->num_rows();
						if ($hasilcek1 ==0) {
							if ($jam <= $waktu_masuk) {
								$st=1;
								$awal=explode(':',$minimal);
								$akhir=explode(':',$jam);
								$dj=$akhir[0]-$awal[0];
								$dm=$akhir[1]-$awal[1];
								$ds=$akhir[2]-$awal[2];
								if ($dj>=0) {
									$telat=($dj>0) ? "$dj jam ":" ";
									$telat.=($dm>0) ? "$dm menit ": " ";
									$telat .=($ds>0) ? "$ds detik ": " ";
								} else {
									$tepat_waktu="selamat pagi, anda datang tepat waktu";
								}
								if ($telat) { $keterangan="Anda terlambat $telat"; $kett="terlambat $telat";}
								if ($tepat_waktu) { $keterangan=$tepat_waktu; $kett="tepat waktu";}
								$this->db->query("REPLACE INTO web_absen(tgl,jam,nip,status,komp,ket) VALUES('$tgl','$jam','$nipq','$st','$ip','$kett')");
							}
						}
						$cek2=$this->db->query("SELECT status,jam,ket FROM web_absen WHERE tgl='$tgl' AND nip='$nipq' AND status=2");
						$hasilcek2=$cek2->num_rows();
						if ($hasilcek2 ==0) {
							if ($jam >= $jam_pulang) {
								$st=2;
								$this->db->query("REPLACE INTO web_absen(tgl,jam,nip,status,komp,ket) VALUES('$tgl','$jam','$nipq','$st','$ip','$kett')");
							}
						}
					}
				}
			}
		}
		$this->db->query("DELETE FROM `web_absen` WHERE tgl ='0000-00-00'");
		echo json_encode(array("status" => TRUE));
	}
	public function hapus_data()
	{
		$result = $this->db->query("SELECT ip FROM web_komp WHERE publish='Y'");
		$Key="0";
		$hariini = date("Y-m-d");
		foreach ($result->result() as $ros) {
			$Connect2 = @fsockopen($ros->ip, "80", $errno, $errstr, 1);
			if($Connect2){
				$soap_request="<ClearData><ArgComKey xsi:type=\"xsd:integer\">".$Key."</ArgComKey><Arg><Value xsi:type=\"xsd:integer\">3</Value></Arg></ClearData>";
				$newLine="\r\n";
				fputs($Connect2, "POST /iWsService HTTP/1.0".$newLine);
				fputs($Connect2, "Content-Type: text/xml".$newLine);
				fputs($Connect2, "Content-Length: ".strlen($soap_request).$newLine.$newLine);
				fputs($Connect2, $soap_request.$newLine);
				$buffer="";
			}
		}
		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($data['status'] === FALSE)
		{
			echo json_encode($data);
			exit();
		}
	}

}
