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

class update extends CI_Model {
	function exe_script($sql){
		try {

			$counter = intval($this->nativesession->get('counter'));
			$update_progress = intval($this->nativesession->get('update_progress'));
			if($counter>=10){
				$update_progress++;
				$this->nativesession->set('update_progress', $update_progress);
				session_write_close();
				session_start();
				$this->nativesession->set('counter', 0);
				session_write_close();
				session_start();

			}else{
				$counter++;
				$this->nativesession->set('counter', ($counter));
				session_write_close();
				session_start();
			}
			return $this->db->query($sql);
		} catch (Exception $e) {
			return FALSE;
		}
	}

	function update_data($params,$data,$table_name){
		try {
			return $this->db->update($table_name, $data, $params);
		} catch (Exception $e) {
			return FALSE;
		}
	}

	function delete_data($params,$data,$table_name){
		try {
			foreach ($params as $param) {
				$this->db->where($param['column'],$param['value']);
			}
			$this->db->delete($table_name,$data);
		} catch (Exception $e) {
			
		}
	}

	function replace_data($table_name,$data){
		try {
			return $this->db->replace($table_name, $data);
		} catch (Exception $e) {
			return FALSE;
		}
	}

	function isColumnExist($table_name,$column_name){
		try {
			$result = $this->db->query('
				SELECT COLUMN_NAME AS colname
			    FROM information_schema.columns 
			    WHERE TABLE_NAME = "'.$table_name.'"
			    AND COLUMN_NAME = "'.$column_name.'" AND TABLE_SCHEMA = "'.$this->db->database.'" 
			    GROUP BY column_name;
				');
			if($result->num_rows>0){
				return $result->row()->colname;
			}else{
				return '';
			}
		} catch (Exception $e) {
			return FALSE;
		}
	}

	function isKeyExist($table_name,$key_name){
		try {
			$result = $this->db->query('
				SELECT count(*)  AS counter
				FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS  
			    WHERE TABLE_NAME = "'.$table_name.'"
			    AND CONSTRAINT_NAME = "'.$key_name.'" AND CONSTRAINT_SCHEMA = "'.$this->db->database.'";');
			if($result->num_rows>0){
				if($result->row()->counter>0){
					return TRUE;
				}
			}else{
				return '';
			}
		} catch (Exception $e) {
			return FALSE;
		}
	}

	function isTableExist($table_name){
		try {
			return $this->db->table_exists($table_name);
		} catch (Exception $e) {
			return FALSE;
		}
	}

	function isValueExist($query){
		try {
			$result = $this->db->query($query);
			if($result->num_rows>0){
				return $result->row();
			}else{
				return '';
			}
		} catch (Exception $e) {
			log_message('error', $e);
		}
	}

}