<?php
 /**
  * Model for repo_categories table.
  *
  * This is the model for repo_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
  * @category Models
  *
  */
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 /**
  * Class Repo_categories_m - Model
  *
  * Model for repo_categories table.
  */
class Repo_categories_m extends MY_Model
{
	 /** @var string This is the database table for this model. */
	var $table = "repo_categories";

	 /** @var int This is private var to use on this class. */
	private $parent_id;

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

	/**
	  * 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');
	}

	/**
	  * Make an array of categories Ids.
	  *
	  * @param int $cat_id Category id.
	  * @param array|null $ret Array
	  *
	  * @return array
	  */
	public function get_cats_branch($cat_id, &$ret=null)
	{
		if($ret==NULL)
		{
			$ret				= array();
		}

		$ret[]				= $cat_id;
		$cat				= $this->get_one($cat_id);
		if($cat['parent_id'] != NULL)
		{
			$this->get_cats_branch($cat['parent_id'], $ret);
		}

		return $ret;
	}

	/**
	  * Make a multidimensional array with information about docs.
	  *
	  * @param array $cats_ids Array of categories.
	  * @param array $docs_ids Array of documents
	  *
	  * @return array
	  */
	public function get_filtered_tree($cats_ids, $docs_ids)
	{
		$this->load->model('repo_docs_m');

		$tree				= $this->_get_filtered_tree($cats_ids, $docs_ids);
		$docs				= $this->repo_docs_m->get_filtered_by_category_id($docs_ids, NULL);
		foreach($docs as $kdoc=>$doc)
		{
			$docs[$kdoc]['id']	= 'dr_'.$docs[$kdoc]['id'];
			unset(
				$docs[$kdoc]['category_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 array $cats_ids Array of categories.
	  * @param array $docs_ids Array of documents
	  * @param int|null $parent_id Parent ID
	  *
	  * @return array
	  */
	private function _get_filtered_tree($cats_ids, $docs_ids, $parent_id=NULL)
	{
		$tree 				= $this->get_filtered_by_parent($cats_ids, $parent_id);
		foreach($tree as $key => $item)
		{
			$tree[$key]['id']	= 'cr_'.$tree[$key]['id'];
			unset(
				$tree[$key]['parent_id'],
				$tree[$key]['client_id'],
				$tree[$key]['image'],
				$tree[$key]['order']
			);
			$childs				= $this->_get_filtered_tree($cats_ids, $docs_ids, $item['id']);
			if(!empty($childs))
			{
				$tree[$key]['childs'] = $childs;
			}
			$docs				= $this->repo_docs_m->get_filtered_by_category_id($docs_ids, $item['id']);
			foreach($docs as $kdoc => $doc)
			{
				$docs[$kdoc]['id']	= 'dr_'.$docs[$kdoc]['id'];
				unset(
					$docs[$kdoc]['category_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 Array of categories and parent ID
	  *
	  * @param array $cats_ids Array of categories.
	  * @param int|null $parent_id Parent ID
	  *
	  * @return array
	  */
	public function get_filtered_by_parent($cats_ids, $parent_id=NULL)
	{
		if(empty($cats_ids))
		{
			return array();
		}

		$this->db->where_in('id', $cats_ids);
		if($parent_id==NULL)
		{
			$this->db->where('parent_id IS null');
		} else {
			$this->db->where('parent_id', $parent_id);
		}

		return $this->get_all();
	}

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

	/**
	  * Check if private var parent_id is setter to concat on data array.
	  *
	  * @param array $data Post Array
	  */
	private function save_parent_id(&$data)
	{
		if(isset($this->parent_id) && !isset($data['parent_id']))
		{
			$data['parent_id'] = $this->parent_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
	  */
	protected function _before_insert(&$data)
	{
		$this->_default_image($data);
		$this->save_parent_id($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
	  */
	protected function _before_update($id, &$data)
	{
		$this->_default_image($data);
		$this->save_parent_id($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)
		{
			$this->load->model('repo_docs_m');

			$checkrepodoc		= $this->repo_docs_m->get_by_category_id($id);
			if(count($checkrepodoc) > 0)
			{
				$data['id']			= $id;
				$data['msg']		= 'This folder can’t be deleted because has at least one file.';
			} 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 {
			$this->load->model('repo_docs_m');

			$checkrepodoc		= $this->repo_docs_m->get_by_category_id($id);
			if(count($checkrepodoc) > 0)
			{
				$this->delete_msg		= 'This folder can’t be deleted because has at least one file.';
				$data['disabledelete']	= true;
			}

			$data['values']		= $this->$model->get_one($id);
			$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;
		}
	}
	/**
	  * Check on provided array if image key is empty to retrieve from database based on business_partner key.
	  *
	  * @param array $data Post Array
	  */
	private function _default_image(&$data)
	{
		if($data['image'] == '')
		{
			$bp				= $this->db->where('bp_id', $data['business_partner'])
							->get('business_partners')
							->row();
			if(isset($bp->default_image))
			{
				$image			= $bp->default_image;
				@exec('cp '.BASE_UPLOAD.'business_partners'.$image.' '.BASE_UPLOAD.'image_categories'.$image);
				$data['image']		= $image;
			}
		}
	}

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

		if($this->session->userdata('user_role') == 2)
		{
			$this->db->where('business_partner', $this->session->userdata('business_partner'));
		}

		return $this->get_all();
	}

	/**
	  * 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 the primary key. Return an array
	  *
	  * @param int $cat_ID ID
	  *
	  * @return array
	  */
	public 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
	  */
	public function setrepocategories($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 $cat_ID ID
	  * @param int $businesspartnerid Business Partner ID
	  * @param array $data Post Data
	  *
	  * @return int
	  */
	public function updaterepocategories($cat_ID, $businesspartnerid, $data)
	{
		$this->db->where('cat_id', $cat_ID)
			->where('business_partner', $businesspartnerid)
			->update($this->table, $data);

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

	/**
	  * Delete a row from the table by the primary value. Return affected rows
	  *
	  * @param int $cat_ID ID
	  * @param int $businesspartnerid Business Partner ID
	  *
	  * @return int
	  */
	public function deleterepocategories($cat_ID, $businesspartnerid)
	{
		$this->db->where('cat_id', $cat_ID)
			->where('business_partner', $businesspartnerid)
			->delete($this->table);

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