<?php
namespace Pratik\Controllers;
use CodeIgniter\Controller;
use Pratik\Models\Pratik_Model;
class Datatable extends Controller
{
	public $db ;
	public $session ;
	public $model ;
    function __construct()
	{
		defined('PRTK') or die('Pratik Aktif Değil');
        $this->db = \Config\Database::connect();
        $this->session = \Config\Services::session();
		$this->request = \Config\Services::request();
        $this->model = new Pratik_Model();
    }
	public function index()
	{
		echo 'index';
	}
	public function get_datatable()
	{
		$result = array( "draw"=> isset( $_GET['draw'] ) ?
				intval( $_GET['draw'] ) :0,
						  "recordsTotal"=> 0,
						  "recordsFiltered"=> 0,
						  "data"=> array()
						);
		if(!isset($_GET['f']) )
		{
			die();
		}
		if ( !method_exists($this, 'get_datatable_for'.$_GET['f'])) {
			
			$this->get_datatable_for($_GET['f']);
		} else {
			$template = $this->request->getPostGet('t');
			$this->{'get_datatable_for'.$_GET['f']}($template);		
		}
	}	
	public function get_count_fordatatable( $table, $fields, $id_fields=array(), $filters=array() )
	{
		// kayıt sayısı	
		$builder = $this->db->table($table);
		$builder->select($fields);
		
		$where = $this->where_string($table, $fields, $id_fields, $filters );
		if($where!='')$builder->where($where);
		$query = $builder->get();
		//$res	= $query->getResult();
		//echo $query->numrows;
		if($query)
		{
			return $query->resultID->num_rows;
		} else {
			return 0;
		}
		
		// kayıt sayısı		
	}
	public function where_string($table, $fields, $id_fields, $filters)
	{
		//idli fieldler için idye göre süzme oluşturmak
		$get_field = 'name'; //id hangi alana göre aranacak
		$likes = array();
		if(isset($_GET['search']) && $_GET['search']['value'] != '' )
		{
					
			foreach($fields as $field)
			{
				
				$likes[] = array($field =>$_GET['search']['value'] );
			}
						
		}
		//idli fieldler için idye göre süzme oluşturmak
		
		$where['like'] = array();
		$where['and'] = array();
		$result = '';
		foreach($likes as $like)
		{  
			foreach($like as $field=>$value)
			{  
				$where['like'][] = $field." LIKE '%".$value."%'";
			}
		}
		
		foreach($filters as $filter)
		{  
			foreach($filter as $field=>$value)
			{  
				$where['and'][] = "$field = '".$value."'";
			}
		}
		$flike= implode(' OR ', $where['like']);
		$fand = implode(' AND ',$where['and']);
		
		if( $flike=='' && $fand=='' )
		{
			$result = '' ;
		} else if( $fand!=''  && $flike=='') {
			$result = $fand ;
		} else if( $flike!='' && $fand=='' ) {
			$result = $flike;			
		} else {
			$result = $fand.' AND ('.$flike.')';
		}
		return $result;
	}
	public function getQueryDatatables( $table, $fields, &$id_fields, &$recordsTotal,$orders=false, $filters=array() )
	{
		//$table='products';
		$state = $_GET['s']??1;
		$extraFilter = $_GET['extraFilter']??false;
		if($extraFilter)
		{
			$parts = explode('=',$extraFilter);
			if( count($parts) >1 && $parts[1]!=0 )
			{
				$filters[] = array($parts[0]=>$parts[1]);
			}
		}
		$id_fields = array('owner', 'parent');
		//$filters = array();
		if($state !='*') $filters[] = array( 'state' => $state);		
		//if($parent) 
		//$filters[] = array( 'ATAKODU' => '0');	
		$recordsTotal = $this->get_count_fordatatable($table,$fields,$id_fields,$filters);
		//$filters = array();
		$builder = $this->db->table($table);
		$builder->select($fields);
		//limit 
		if ( isset($_GET['start']) && $_GET['length'] != -1 ) 
		{
			$builder->limit(intval($_GET['length']),intval($_GET['start']));
		}	
		//order
		if ( isset( $_GET['order'] ) && $_GET['order'][0]['column'] >0 ) 
		{
			$builder->orderBy( $fields[$_GET['order'][0]['column']-1], $_GET['order'][0]['dir']);
		} elseif($orders) {
		foreach($orders as $order)
			{
				$builder->orderBy($order);
			}
		}
		$where = $this->where_string($table, $fields, $id_fields, $filters );
		if($where!='')$builder->where($where);
		return $builder->get();
	}
	
	//yeni usul
	public function get_datatable_for($module)
	{
		$fields= explode(';',$_GET['tr']);
		$id_fields='';
		$recordsTotal=0;
		$query = $this->getQueryDatatables($module,$fields, $id_fields, $recordsTotal);
		$rows=array();
		$state = $_GET['s']??1;
		if($query)
		{
			$result = $query->getResult('array');
			foreach ($result as $row)
			{
				$buttons = '<ul class="icons-list icons-list-extended text-nowrap">';
				$buttons .= '<li><a href="'.getSubUrl($module.'/edit?id='.$row['id'],1).'" data-popup="tooltip" title="" data-original-title="Call"><i class="icon-pencil7 text-teal"></i></a></li>';
				$buttons .= '</ul>';
				$actions = '<div class="">'.$buttons.'</div>';
				$tr = array('');
				foreach($fields as $field)
				{
					$value = isset($row[$field])?$row[$field]:'';
					if($field=='image' || $field == 'resim')
					{
						$value = getImg($value,30,30,'img-circle');
					}
					$tr[] = '<span class="'.sanitize($value,24).'">'.$value.'</span>';
				}
				$tr[] 	= $actions;
				$rows[] = $tr;
			}
		}
		$result = array( "draw"=> isset( $_GET['draw'] ) ?
				intval( $_GET['draw'] ) :
				0,
						  "recordsTotal"=> $recordsTotal,
						  "recordsFiltered"=> $recordsTotal,
						  "data"=> $rows
						);
		echo json_encode($result);
		
		die('');
	}
	
	public function get_datatable_forusers()
	{
		$fields= explode(';',$_GET['tr']);
		$id_fields='';
		$recordsTotal=0;
		$query = $this->getQueryDatatables('users',$fields, $id_fields, $recordsTotal);
		$rows=array();
		$state = $_GET['s']??1;
		if($query)
		{
			$result = $query->getResult('array');
			foreach ($result as $row)
			{
				$buttons = '';
				if($state==0)
				{
					$buttons = '<a class="confirm" href="'.getSubUrl('users/confirm?id='.$row['id'],1).'" message="'.$row['name'].' '.$row['surname'].' Onaylansın mı?">Confirm</a>';
				} elseif($state==1) {
					$buttons = '<a class="confirm" href="'.getSubUrl('users/delete?id='.$row['id'],1).'" message="'.$row['name'].' '.$row['surname'].' Silinsin mi?">Delete</a>';					
				}
				$actions = '<div class="">
							<a href="'.getSubUrl('users/edit?id='.$row['id'],1).'" >Edit</a>'.$buttons.'
							</div>';
				$tr = array('');
				$row['image'] = getImg($row['image'],40,40);
				foreach($fields as $field)
				{
					$tr[] = isset($row[$field])?$row[$field]:'';
				}
				$tr[] 	= $actions;
				$rows[] = $tr;
			}
		}
		$result = array( "draw"=> isset( $_GET['draw'] ) ?
				intval( $_GET['draw'] ) :
				0,
						  "recordsTotal"=> $recordsTotal,
						  "recordsFiltered"=> $recordsTotal,
						  "data"=> $rows
						);
		echo json_encode($result);
		
		die('');
	}

	public function get_datatable_forucretler()
	{
		$fields= explode(';',$_GET['tr']);
		$fields[]='parabirimi';
		$id_fields='';
		$recordsTotal=0;
		$query = $this->getQueryDatatables('ucretler',$fields, $id_fields, $recordsTotal);
		$rows=array();
		$state = $_GET['s']??1;
		array_pop($fields);
		if($query)
		{
			$result = $query->getResult('array');
			foreach ($result as $row)
			{
				$buttons = '<ul class="icons-list icons-list-extended text-nowrap">';
				$buttons .= '<li><a href="'.getSubUrl('ucretler/edit?id='.$row['id'],1).'" data-popup="tooltip" title="" data-original-title="Call"><i class="icon-pencil7 text-teal"></i></a></li>';
				/*if($state==0)
				{
					$buttons .= '<li><a href="'.getSubUrl('ucretler/confirm?id='.$row['id']).'" data-popup="tooltip" title="" data-toggle="modal" data-target="#call" data-original-title="Call"><i class="icon-checkmark-circle2 text-success"></i></a></li>';
				} elseif($state==1) {
					$buttons .= '<li><a href="'.getSubUrl('ucretler/delete?id='.$row['id']).'" data-popup="tooltip" title="" data-toggle="modal" data-target="#call" data-original-title="Call"><i class="icon-cancel-circle2 text-danger"></i></a></li>';
				}*/
				$buttons .= '</ul>';
				$actions = '<div class="">
							'.$buttons.'
							</div>';
				$tr = array('');
				$row['ucret'] .= ' '.$row['parabirimi'];
				foreach($fields as $field)
				{
					$tr[] = isset($row[$field])?$row[$field]:'';
				}
				$tr[] 	= $actions;
				$rows[] = $tr;
			}
		}
		$result = array( "draw"=> isset( $_GET['draw'] ) ?
				intval( $_GET['draw'] ) :
				0,
						  "recordsTotal"=> $recordsTotal,
						  "recordsFiltered"=> $recordsTotal,
						  "data"=> $rows
						);
		echo json_encode($result);
		
		die('');
	}
	public function get_datatable_forindirimler()
	{
		$fields= explode(';',$_GET['tr']);
		$id_fields='';
		$recordsTotal=0;
		$query = $this->getQueryDatatables('indirimler',$fields, $id_fields, $recordsTotal);
		$rows=array();
		$state = $_GET['s']??1;
		if($query)
		{
			$result = $query->getResult('array');
			foreach ($result as $row)
			{
				$row['tip'] = t_($row['tip']);
				$buttons = '<ul class="icons-list icons-list-extended text-nowrap">';
				$buttons .= '<li><a href="'.getSubUrl('indirimler/edit?id='.$row['id'],1).'" data-popup="tooltip" title=""  data-original-title="Call"><i class="icon-pencil7 text-teal"></i></a></li>';
				/*if($state==0)
				{
					$buttons .= '<li><a href="'.getSubUrl('ucretler/confirm?id='.$row['id']).'" data-popup="tooltip" title="" data-toggle="modal" data-target="#call" data-original-title="Call"><i class="icon-checkmark-circle2 text-success"></i></i></a></li>';
				} elseif($state==1) {
					$buttons .= '<li><a href="'.getSubUrl('ucretler/delete?id='.$row['id']).'" data-popup="tooltip" title="" data-toggle="modal" data-target="#call" data-original-title="Call"><i class="icon-cancel-circle2 text-danger"></i></a></li>';
				}*/
				$buttons .= '</ul>';
				$actions = '<div class="">
							'.$buttons.'
							</div>';
				$tr = array('');
				foreach($fields as $field)
				{
					$tr[] = isset($row[$field])?$row[$field]:'';
				}
				$tr[] 	= $actions;
				$rows[] = $tr;
			}
		}
		$result = array( "draw"=> isset( $_GET['draw'] ) ?
				intval( $_GET['draw'] ) :
				0,
						  "recordsTotal"=> $recordsTotal,
						  "recordsFiltered"=> $recordsTotal,
						  "data"=> $rows
						);
		echo json_encode($result);
		
		die('');
	}
	public function get_datatable_forokullar()
	{
		$fields= explode(';',$_GET['tr']);
		$id_fields='';
		$recordsTotal=0;
		$query = $this->getQueryDatatables('okullar',$fields, $id_fields, $recordsTotal);
		$rows=array();
		$state = $_GET['s']??1;
		if($query)
		{
			$result = $query->getResult('array');
			foreach ($result as $row)
			{
				$row['city'] = $this->model->getTableValue('cities', 'id='.(int)$row['city'], 'name', 1);
				$row['district'] = $this->model->getTableValue('districts', 'id='.(int)$row['district'], 'name', 1);
				$buttons = '<ul class="icons-list icons-list-extended text-nowrap">';
				$buttons .= '<li><a href="'.getSubUrl('okullar/edit?id='.$row['id'],1).'" data-popup="tooltip" title=""  data-original-title="Call"><i class="icon-pencil7 text-teal"></i></a></li>';
				/*if($state==0)
				{
					$buttons .= '<li><a href="'.getSubUrl('ucretler/confirm?id='.$row['id']).'" data-popup="tooltip" title="" data-toggle="modal" data-target="#call" data-original-title="Call"><i class="icon-checkmark-circle2 text-success"></i></i></a></li>';
				} elseif($state==1) {
					$buttons .= '<li><a href="'.getSubUrl('ucretler/delete?id='.$row['id']).'" data-popup="tooltip" title="" data-toggle="modal" data-target="#call" data-original-title="Call"><i class="icon-cancel-circle2 text-danger"></i></a></li>';
				}*/
				$buttons .= '</ul>';
				$actions = '<div class="">
							'.$buttons.'
							</div>';
				$tr = array('');
				foreach($fields as $field)
				{
					$tr[] = isset($row[$field])?$row[$field]:'';
				}
				$tr[] 	= $actions;
				$rows[] = $tr;
			}
		}
		$result = array( "draw"=> isset( $_GET['draw'] ) ?
				intval( $_GET['draw'] ) :
				0,
						  "recordsTotal"=> $recordsTotal,
						  "recordsFiltered"=> $recordsTotal,
						  "data"=> $rows
						);
		echo json_encode($result);
		
		die('');
	}
	
}
