<?php
namespace Pratik\Models;
use \CodeIgniter\Database\ConnectionInterface;
use \Config\Database;
class Pratik_Model  extends \CodeIgniter\Model
{
	protected $db ;
	protected $session ;
    function __construct()
	{
		$this->db = \Config\Database::connect();
		//$this->session = \Config\Services::session()->start();
    }	
    public function setupModule($table, $settings, $withmeta=false)
	{
		$this->setupTable($table, $settings);
		$fields= array();
		$fields['id'] = array('type'=>'INT', 'constraint'=>11, 'auto_increment'=>TRUE, 'unique'=>TRUE );
		$fields['owner'] = array('type'=>'INT', 'constraint'=>11);
		$fields['group'] = array('type'=>'VARCHAR', 'constraint'=>32);
		$fields['key'] = array('type'=>'VARCHAR', 'constraint'=>32);
		$fields['lang'] = array('type'=>'VARCHAR', 'constraint'=>5);
		$fields['val'] = array('type'=>'TEXT');
		$fields['sort'] = array('type'=>'INT', 'constraint'=>11);
		$fields['state'] = array('type'=>'BOOLEAN');
		
		$fields= array();
		$fields['id'] = array('type'=>'INT', 'constraint'=>11, 'auto_increment'=>TRUE, 'unique'=>TRUE );
		$fields['owner'] = array('type'=>'INT', 'constraint'=>11);
		$fields['key'] = array('type'=>'VARCHAR', 'constraint'=>35);
		$fields['lang'] = array('type'=>'VARCHAR', 'constraint'=>5);
		$fields['val'] = array('type'=>'TEXT');
		
		$forge = \Config\Database::forge();
		$forge->addField($fields);
		$forge->createTable($table.'_values', true);
		
		if($withmeta)
		{
			$forge->addKey('owner', TRUE);
			$forge->addKey('group', TRUE);
			$forge->addKey('lang', TRUE);
			$forge->addKey('key', TRUE);
			$forge->addField($fields);
			$forge->createTable($table.'_metas', true);
		}


	
	}
    public function setupTable($table, $settings)
	{
		foreach($settings as $key=>$setting)
		{
			unset($field);
			if($setting['dbtype']=='none') continue;
			$field['type'] = isset($setting['dbtype'])?$setting['dbtype']:'VARCHAR';
			$field['constraint'] = isset($setting['lenght'])?$setting['lenght']:'254';
			if(isset($setting['unique'])) $field['unique'] = TRUE;
			if(isset($setting['default'])) $field['default'] = $setting['default'];
			if(isset($setting['is_key'])) $forge->addKey($key, TRUE);
			$fields[$key] = $field;
			
		}
		$fields['id'] = array('type'=>'INT', 'constraint'=>11, 'auto_increment'=>TRUE, 'unique'=>TRUE );
		$fields['state'] = array('type'=>' BOOLEAN');
		$forge = \Config\Database::forge();
		$forge->addField($fields);
		$forge->addKey('id', TRUE);
		$forge->createTable($table, true);
		print_r($forge);
	}
	
    public function runSqls($sqls)
	{
		foreach($sqls as $sql)
		{
			$this->db->query($sql);
		}
	}
    public function deleteTable($table)
	{

		if($table)

		{

			$forge = \Config\Database::forge();

			$forge->dropTable($table);
		}

	}

    public function emptyTable($table)
	{

		if($table)

		{

			$builder = $this->db->table($table);

			$builder->truncate();

		}

	}

		
    public function saveBasic($table, $data, $settings=false, $lang='tr_TR')
	{
		$return= array('id'=>'','error'=>false);
		$multivalues = array();
		if(!$settings)
		{
			return false;
		}
		foreach($settings as $key => $setting)
		{
			$value = isset($data[$key])?$data[$key]:'';
			if(is_array($value))
			{
				$multivalues[$key] = $value;
				$value = current($value);
			}
			if(isset($setting['dbtype']) && $setting['dbtype']!='none')$values[$key] = $value;
		}

		$builder = $this->db->table($table);
		$builder2 = $this->db->table($table.'_values');
		$query  = $builder->getWhere(['id' => $values['id'] ], 1);
		if($query && $values['id']>0)
		{
				$builder->set($values);
				$builder->where('id', $values['id']);
				$query = $builder->replace ();	
				$return['id'] = $values['id'];
			
		} else {
				if($values['id']==0 || empty($values['id']) )
				{
					unset($values['id']);
					$builder->set($values);
					$query = $builder->insert();
					if($query)
					{
						$return['id'] =  $this->db->insertID();			
					} else {
						$return['id'] =  false;							
					}
				} else {
					$return['id'] =  false;
				}
		}
		//$ret = $this->getTableRows($table);		
		if($return['id'])
		{
			foreach($multivalues as $multikey => $multivalue)
			{
				
				$builder2->delete(array('owner' => $return['id'], 'key'=>$multikey, 'lang'=>$lang));
				$row['owner'] = $return['id'];
				$row['key'] = $multikey;
				$row['lang'] = $lang;
				foreach($multivalue as $mval)
				{
					$row['val'] = is_array($mval)?current($mval):$mval;
					$builder2->set($row);
					$builder2->insert();				
					
				}
			}
		}
		$return['error'] = $this->db->error();
		return $return;
	}
    public function getBasic($table, $id,  $settings=false, $filter='', $withelem=false)
	{
		if(!$settings)
		{
			return false;
		}
		$id = (int)$id;
		$where =  'id='.$id;;
		if($filter!='') 
		{
			$where = 'id='.$id.' AND '.$filter;
		} 
		$builder = $this->db->table($table);
		$builder2 = $this->db->table($table.'_values');
		$builder2->select('val');
		$query = $builder->where('id='.$id.' AND '.$where)->get();	
		if(!$query)
		{
			$error = $this->db->error();
			echo 'Veri tabanı Hatası: '.$error['code'].'<br>'.$error['message'];
			die();
		}
		$rows = $query->getResultArray();		
		if(!empty($rows)){
			
			foreach($settings as $key => $setting)
			{
				$vals= isset($rows[0][$key])?$rows[0][$key]:'';
				if($setting['type']=='multifield')
				{
					$vals=array();
					$fields = explode(',',$setting['fields']);
					foreach($fields as $field)
					{
						$vals[$field]= isset($rows[0][$field])?$rows[0][$field]:'';
					}
				} elseif(isset($setting['multiple'])) {
					
					$query2  = $builder2->getWhere(['owner' => $id, 'key'=>$key ]);
					if($query2)
					{
						$vals=array();
						$rows2 = $query2->getResultArray();
						foreach($rows2 as $row2)
						{
							$vals[] = $row2['val'];
						}
					}
				
				}
				
				if($withelem)
				{
					$settings[$key]['val'] = $vals;
					$result[$key] = $settings[$key];
				} else {
					$result[$key] = $vals;
				}
	
			}
	
		}  elseif($id==0) {
			foreach($settings as $key => $setting)
			{
				if($withelem)
				{
					$settings[$key]['val'] = '';
					$result[$key] = $settings[$key];
				} else {
					$result[$key] = '';
				}
				
			}
		} else {
			return false;
		}
		return $result;
	}	
    public function saveMetas($owner, $table, $data, $settings=false, $lang='tr_TR', $group='meta')
	{
		if(!$settings)
		{
			return false;
		}
		
		$builder = $this->db->table($table.'_metas');
		$builder2 = $this->db->table($table.'_values');
		foreach($settings as $key => $setting)
		{
			$meta['owner'] = $owner;
			$meta['key'] = $key;
			$meta['group'] = $group;
			$meta['lang'] = $lang;
			$values['owner'] = $owner;
			$values['key'] = $key;
			$values['lang'] = $lang;
			$val='';
			if(isset($data[$key]))//meta tanımlı ise
			{
				if(is_array($data[$key]))
				{				
					$val=current($data[$key]);
					$builder2->delete(array('owner' => $owner, 'key'=>$key, 'lang'=>$lang)); 
					foreach($data[$key] as $dat)
					{
						$values['val'] = is_array($dat)?current($dat):$dat;
						$builder2->set($values);
						$builder2->insert();				
					}
				
				} else {
					$val = $data[$key];
				}
			}			
			$meta['val']=$val;
			$builder->set($meta);
			$builder->replace();
		}
		return true;
	}
    public function getMetas($owner, $table, $where='', $settings=false, $lang='tr_TR', $group='meta', $withelem=false)
	{
		if(!$settings)
		{
			return false;
		}
		$builder = $this->db->table($table.'_metas');
		
		$wheres['owner'] = $owner;
		$wheres['lang'] = $lang;
		if($where!='') $builder->where($where);
		$builder->where($wheres);
		$query = $builder->get();
		if(!$query) return $settings;
		$rows = $query->getResultArray();
		if($rows){
			
			foreach($settings as $key => $setting)
			{
				$val=array();
				if(isset($setting['multiple'])) //multiple value
				{
					$builder2 = $this->db->table($table.'_values');		
					if($where!='') $builder2->where($where);
					$builder2->where($wheres);
					$query2 = $builder2->get();		
					if($query2)
					{
						$rows2 = $query2->getResultArray();
						foreach($rows2 as $row2)
						{
							if(($row2['key'] == $key ))
							{
								$val[] = $row2['val'];
							}
						}
						
					}
					
				}
				if(!isset($setting['multiple']) || !count($val))//multiple değilse
				{
					foreach($rows as $row)
					{
						if(($row['key'] == $key ))
						{
							$val[] = $row['val'];break;
						}
					}
					
				}
					
				if(!count($val)) $val[]='';
				if($withelem)
				{
					$settings[$key]['val'] = $val;
					$result[$key] = $settings[$key];
				} else {
					$result[$key] = $val;
				}
	
			}
	
		}  else {
			return $settings;
		}
		return $result;
		
	}
    public function getTableValue($table, $where='', $keys='*', $limit=1, $start=0, $onlycount=false, $orderby=false )
	{
		$builder = $this->db->table($table);
		$builder->select($keys);
		if($limit!=0) $builder->limit($limit, $start);
		if($where!='')$builder->where($where);
		if($onlycount)
		{		
			return $builder->countAllResults();
		}

		if($orderby && is_string($orderby))
		{
			$builder->orderby($orderby);
		}
		$query = $builder->get();
		if(!$query) return false;
		$rows = $query->getResultArray();
		if($rows)
		{
			if($limit==1)
			{
				if($keys!='*' && count(explode(',',$keys))==1)
				{
					return $rows[0][$keys];
					
				} else {
					return $rows[0];					
				}
				
			} else {
				return $rows;				
			}
		} else {
			return false;
		}
	}
    public function getTableRow($table, $where)
	{
		return $this->getTableValue($table, $where, '*', 1, 0);
	}
    public function getTableRows($table, $where='', $limit=0, $start=0, $orderby=false)
	{
		return $this->getTableValue($table, $where, '*', $limit, $start, false, $orderby);
	}
    public function getTableRowsCount($table, $where='', $limit=0, $start=0)
	{
		if($where=='')
		{
			$builder = $this->db->table($table);
			return $builder->countAll(); 
		}
		return $this->getTableValue($table, $where, '*', $limit, $start, true);
	}
    public function setTableValue($table, $id, $key, $value, $where='')
	{
		$builder = $this->db->table($table);
		$builder->where('id', $id);
		if($where!='')$builder->where($where);
		$values =array($key => $value);
		$query = $builder->update($values);
		return $query;
	}
    public function getTableSum($table, $where='', $field='id', $limit=false, $start=0 )
	{
		$builder = $this->db->table($table);
		if($limit!=0) $builder->limit($limit, $start);
		if($where!='')$builder->where($where);

		$query = $builder->selectSum($field)->get();
		if(!$query) return false;

		$rows = $query->getResultArray();
		if($rows)
		{
			return $rows[0][$field];
		}
	}
	public function deleteTableRow($table, $id, $where='')
	{
		$builder = $this->db->table($table);
		$builder->where('id', $id);
		if($where!='')$builder->where($where);
		$query = $builder->delete();
		return $query;
		
	}

}