<?php
 /**
  * Model for clients_categories table
  *
  * This is the model for clients_categories table extended from MY_Model.
  *
  * @author Innoxess Spain, S.L. <hola@innoxess.es>
  * @copyright 2015-2018 Innoxess Spain, S.L.
  * @package  Application
  * @subpackage Models
  *
  */
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 /**
  * Class Clients_categories_m - Model
  *
  * Model for clients_categories table.
  */
class Clients_categories_m extends MY_Model
{
	 /** @var string This is the database table for this model. */
	var $table = "clients_categories";
	 /** @var int This is private var to use on this class. */
	private $parent_id;
	 /** @var int This is private var to use on this class. */
	private $client_id;

	/**
	  * Constructor
	  */
	function __construct()
	{
		parent::__construct();
	}

	/**
	  * Make a multidimensional array with information about docs.
	  *
	  * @param int $client_id Client ID.
	  *
	  * @return array
	  */
	public function get_tree($client_id)
	{
		$this->load->model('clients_docs_m');

		$tree				= $this->_get_tree($client_id, NULL);
		$docs				= $this->clients_docs_m->get_by_category_id($client_id, NULL);
		foreach($docs as $kdoc=>$doc)
		{
			$docs[$kdoc]['id']	= 'dc_'.$docs[$kdoc]['id'];
			unset(
				$docs[$kdoc]['category_id'],
				$docs[$kdoc]['client_id'],
				$docs[$kdoc]['image'],
				$docs[$kdoc]['order'],
				$docs[$kdoc]['doc']
			);
		}

		if(!empty($docs))
		{
			$tree['docs']		= $docs;
		}

		return $tree;
	}
	/**
	  * Make a multidimensional array with information about docs.
	  *
	  * @param int $client_id Client ID.
	  * @param int|null $parent_id Parent ID
	  *
	  * @return array
	  */
	private function _get_tree($client_id, $parent_id=NULL)
	{
		$tree				= $this->get_by_parent($client_id, $parent_id);
		foreach($tree as $key => $item)
		{
			$tree[$key]['id']	= 'cc_'.$tree[$key]['id'];
			unset(
				$tree[$key]['parent_id'],
				$tree[$key]['client_id'],
				$tree[$key]['image'],
				$tree[$key]['order']
			);
			$childs				= $this->_get_tree($client_id, $item['id']);
			if(!empty($childs))
			{
				$tree[$key]['childs'] = $childs;
			}
			$docs				= $this->clients_docs_m->get_by_category_id($client_id, $item['id']);
			foreach($docs as $kdoc => $doc)
			{
				$docs[$kdoc]['id']	= 'dc_'.$docs[$kdoc]['id'];
				unset(
					$docs[$kdoc]['category_id'],
					$docs[$kdoc]['client_id'],
					$docs[$kdoc]['image'],
					$docs[$kdoc]['order'],
					$docs[$kdoc]['doc']
				);
			}

			if(!empty($docs))
			{
				$tree[$key]['docs'] = $docs;
			}
		}

		return $tree;
	}

	/**
	  * Fetch all the records in the table filtered by Client ID & Parent ID
	  *
	  * @param int $client_id Client ID.
	  * @param int|null $parent_id Parent ID
	  *
	  * @return array
	  */
	public function get_by_parent($client_id, $parent_id=NULL)
	{
		if($parent_id==NULL)
		{
			$this->db->where('parent_id IS null');
		} else {
			$this->db->where('parent_id', $parent_id);
		}
		$this->db->where('client_id', $client_id)
			->order_by('order');

		return $this->get_all();
	}

	/**
	  * Set private var parent_id.
	  *
	  * @param int|null $parent_id Parent ID
	  */
	function set_parent_id($parent_id)
	{
		$this->parent_id = $parent_id;
	}

	/**
	  * Set private var client_id.
	  *
	  * @param int|null $client_id Client ID
	  */
	function set_client_id($client_id)
	{
		$this->client_id = $client_id;
	}

	/**
	  * Check if private var parent_id is setter & private var client_id is setter to concat on data array.
	  *
	  * @param array $data Post Array
	  */
	private function save_model_data(&$data)
	{
		if(isset($this->parent_id) && !isset($data['parent_id']))
		{
			$data['parent_id'] = $this->parent_id;
		}
		if(isset($this->client_id) && !isset($data['client_id']))
		{
			$data['client_id'] = $this->client_id;
		}
	}

	/**
	  * This callback runs before the insert of the crud.
	  * The callback takes as a 1st parameter the post array.
	  * With this opportunity you can add or unset some post variables.
	  *
	  * @param array $data Array
	  */
	function _before_insert(&$data)
	{
		$this->save_model_data($data);
	}

	/**
	  * This callback runs before the update of the crud.
	  * The callback takes as a 1st parameter the primary key value and as 2nd the post array.
	  * With this opportunity you can add or unset some post variables.
	  *
	  * @param int $id Primary key
	  * @param array $data Array
	  */
	function _before_update($id, &$data)
	{
		$this->save_model_data($data);
	}

	/**
	  * Help delete method to return layout view for delete section of crud or to process submit for delete section.
	  *
	  * @param string $id Primary key value
	  * @param string $back Segment url passed to base_url helper used to back when click on cancel button on delete section
	  * @param string $target Segment url passed to base_url helper used to go when click on submit button on delete section
	  * @param string $ok -
	  * @param true|false $wrap -
	  *
	  * @return mixed
	  */
	function _delete($id, $back='', $target='', $ok=NULL, $wrap=TRUE)
	{
		if($ok==NULL)
		{
			$ok					= $back;
		}
		$model				= $this->model;
		$items				= $this->_get_items('delete');

		$this->_set_rules($items);

		$data				= array();
		if($this->form_validation->run() == TRUE)
		{
			$checkinvoice		= $this->$model->get_one($id);
			if($checkinvoice['isinvoice'] == "1")
			{
				$data['id']			= $id;
				$data['msg']		= 'You are not allow to delete it.';
			} else {
				$delete_id			= $this->$model->delete($id);
				$data['id']			= $delete_id;
				if($delete_id <= 0)
				{
					$data['msg']		= 'Ha ocurrido un error pongase en contacto con el administrador';
				} else {
					$data['msg']		= 'Borrado correctamente';
				}
			}
		} else {
			$data['values']		= $this->$model->get_one($id);
			if($data['values']['isinvoice'] == "1")
			{
				$this->delete_msg = "You are not allow to delete it.";
				$data['disabledelete'] = true;
			}
			$data['fields']		= $this->_get_fields($items, $data['values']);
			$data['icon']		= $this->icon;
			$data['back']		= $back;
			$data['wrap']		= $wrap;
			$data['target']		= $target;

			$this->_delete_msg($data);
		}

		if(isset($data['id']))
		{
			redirect($ok);
		} else {
			return $data;
		}
	}

	/**
	  * Fetch a single record based on the Client ID. Return an primary key value
	  *
	  * @param int $client_id Client ID
	  *
	  * @return int
	  */
	public function getinvoice($client_id)
	{
		$query				= $this->db->where('client_id',$client_id)
							->where('category_name','Invoice')
							->where('isinvoice',1)
							->get('clients_categories');

		if($query->num_rows() > 0)
		{
			$categorydata		= $query->row_array();

			return $categorydata['id'];
		} else {
			return '0';
		}
	}

	/**
	  * Insert a new row into the table with isinvoice column setter to 1 or update if exist data for provided Client ID param.
	  *
	  * @param int $client_id Client ID
	  *
	  * @return int
	  */
	public function createinvoice($client_id)
	{
		$query				= $this->db->where('client_id',$client_id)
							->where('category_name','Invoice')
							->where('isinvoice',1)
							->get('clients_categories');

		if($query->num_rows() > 0)
		{
			$categorydata		= $query->row_array();

			return $categorydata['id'];
		} else {
			$query				= $this->db->where('client_id',$client_id)
								->where('category_name','Invoice')
								->get('clients_categories');

			if($query->num_rows() > 0)
			{
				$category			= $query->row_array();

				$this->db->where('id', $category['id'])
					->update('clients_categories', [
						"isinvoice"			=> "1"
					]);

				return $category['id'];
			} else {
				$this->db->insert("clients_categories", [
					'client_id'			=> $client_id,
					'category_name'		=> 'Invoice',
					'isinvoice'			=> 1,
					'order'				=> 0
				]);

				return $this->db->insert_id();
			}
		}
	}

	/**
	  * Set isinvoice to 0 if exist data for provided Client ID param
	  *
	  * @param int $client_id Client ID
	  *
	  * @return int
	  */
	public function deactivateinvoice($client_id)
	{
		$query				= $this->db->where('client_id', $client_id)
							->where('category_name', 'Invoice')
							->where('isinvoice', 1)
							->get('clients_categories');

		if($query->num_rows() > 0)
		{
			$category			= $query->row_array();

			$this->db->where('id', $category['id'])
				->update('clients_categories', [
					"isinvoice"			=> "0"
				]);

			return $category['id'];
		} else {
			return '0';
		}
	}

	/**
	  * Fetch a single record based on the primary key. Return an array
	  *
	  * @param int $id ID
	  *
	  * @return array
	  */
	public function get_custom_one($id)
	{

		$query				= $this->db->join('admin', 'admin.id = '.$this->table.'.admin_id', 'left outer')
							->select($this->table.'.*, admin.user as user, '.$this->table.'.'.$this->primary_key.' AS '.$this->primary_key)
							->where($this->table.'.'.$this->primary_key, $id)
							->get($this->table);

		return $this->_get_virtuals($id, $query->row_array());
	}

	/**
	  * Fetch a single record based on Category ID. Return an array
	  *
	  * @param int $cat_ID ID
	  *
	  * @return array
	  */
	function getidbycategoryid($cat_ID)
	{
		$query				= $this->db->where('cat_id', $cat_ID)
							->get($this->table);

		return $query->row_array();
	}

	/**
	  * Insert a new row into the table. $data should be an associative array of data to be inserted. Returns newly created ID.
	  *
	  * @param array $data Post data
	  *
	  * @return int
	  */
	function setclientcategories($data)
	{
		$this->db->insert($this->table, $data);

		return $this->db->insert_id();
	}

	/**
	  * Updated a record based on the primary value.
	  *
	  * @param int $cat_ID ID
	  * @param int $client_id Client ID
	  * @param array $data Post data
	  *
	  * @return int
	  */
	function updateclientcategories($cat_ID, $client_id, $data)
	{
		$this->db->where('cat_id', $cat_ID)
			->where('client_id', $client_id)
			->update($this->table, $data);

		return $this->db->affected_rows();
	}

	/**
	  * Delete a row from the table by the primary value
	  *
	  * @param int $cat_ID ID
	  * @param int $client_id Client ID
	  *
	  * @return int
	  */
	function deleteclientcategories($cat_ID, $client_id)
	{
		$this->db->where('cat_id', $cat_ID)
			->where('client_id', $client_id)
			->delete($this->table);

		return $this->db->affected_rows();
	}
}
