<?php
 /**
  * Model for clients_docs table
  *
  * This is the model for clients_docs 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_docs_m - Model
  *
  * Model for clients_docs table.
  */
class Clients_docs_m extends MY_Model
{
	 /** @var string This is the database table for this model. */
	var $table = "clients_docs";
	 /** @var int This is private var to use on this class. */
	private $category_id;
	 /** @var int This is private var to use on this class. */
	private $client_id;

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

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

		return $this->get_all();
	}

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

	/**
	  * Set private var category_id.
	  *
	  * @param int $category_id Category ID
	  *
	  * @return int
	  */
	public function set_category_id($category_id)
	{
		$this->category_id = $category_id;
	}

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

	/**
	  * This callback runs before save 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
	  */
	protected function _before_save($id, &$data)
	{
		$data['admin_id']	= $this->session->userdata('manager');
		$data['updated_at']	= date('Y-m-d H:i:s');
	}

	/**
	  * 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);
		if($data['push'])
		{
			$this->load->model('clients_m');

			$client				= $this->clients_m->get_one($data['client_id']);

			push_send($client['external_id'], lang("app_title") . ': ' . $data['name']);
		}
	}

	/**
	  * 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)
		{
			$checkcategory		= $this->$model->get_one($id);
			if($checkcategory['category_id'] != null && $checkcategory['category_id'] != "")
			{
				$this->load->model('clients_categories_m');

				$checkinvoice		= $this->clients_categories_m->get_one($checkcategory['category_id']);
				if($checkinvoice['isinvoice'] == "1" && $checkinvoice['category_name'] == "Invoice")
				{
					$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 {
				$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']['category_id'] != null && $data['values']['category_id'] != "")
			{
				$this->load->model('clients_categories_m');

				$checkinvoice = $this->clients_categories_m->get_one($data['values']['category_id']);
				if($checkinvoice['isinvoice'] == "1" && $checkinvoice['category_name'] == "Invoice")
				{
					$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;
		}
	}

	/**
	  * Insert a new row into the table. Returns newly created ID.
	  *
	  * @param int $client_id Client ID
	  * @param int $category_id Category ID
	  * @param string $docname Document name
	  * @param string $orginaldocname Original document name
	  *
	  * @return int
	  */
	function setinvoice($client_id, $category_id, $docname, $orginaldocname)
	{
		$this->db->insert("clients_docs", array(
			'client_id'			=> $client_id,
			'category_id'		=> $category_id,
			'order'				=> 0,
			'doc'				=> '/'.$docname,
			'name'				=> $orginaldocname,
			'description'		=> 'invoice'.date('m-d-Y'),
		));

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

	/**
	  * Fetch a single record based on the primary key. Return an array
	  *
	  * @param int $id ID
	  *
	  * @return array
	  */
	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());
	}

	/**
	  * Retrieve number of rows found on database.
	  *
	  * @param int $doc_ID ID
	  * @param int $client_id Client ID
	  *
	  * @return array
	  */
	function checkclientdocbydocid_userid($doc_ID, $client_id)
	{
		return $this->db->where('doc_id', $doc_ID)
			->where('client_id', $client_id)
			->get($this->table)
			->num_rows();
	}

	/**
	  * 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 setclientdocument($data)
	{
		$this->db->insert($this->table, $data);

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

	/**
	  * Updated a record based on the primary value. Return affected rows
	  *
	  * @param int $doc_ID ID
	  * @param int $client_id Client ID
	  * @param array $data Post Data
	  *
	  * @return int
	  */
	function updateclientdocument($doc_ID, $client_id, $data)
	{
		$this->db->where('doc_id', $doc_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 $doc_ID ID
	  * @param int $client_id Client ID
	  *
	  * @return int
	  */
	function deleteclientdocument($doc_ID, $client_id)
	{
		$this->db->where('doc_id', $doc_ID)
			->where('client_id', $client_id)
			->delete($this->table);

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