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

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

	/**
	  * Helper for get_one method to concat extra information for return
	  *
	  * @param int $id ID for primary key
	  * @param array $data Array
	  */
	function _get_virtuals($id, $data)
	{
		$users				= $this->db->select('c.id, CONCAT(c.name, " ", c.surname) as name, IF(dau.id > 0, "checked", "") as checked', false)
							->where('partner_id', $data['business_partner'])
							->join('docs_assignment_users as dau', 'c.id = dau.user_id AND dau.docs_assignment_id = '.$id, 'left')
							->get('clients as c')
							->result_array();
		$documents			= $this->db->select('rd.id, rd.name, IF(dard.id > 0, "checked", "") as checked', false)
							->where('business_partner', $data['business_partner'])
							->join('docs_assignment_repo_docs as dard', 'rd.id = dard.repo_doc_id AND dard.docs_assignment_id = '.$id, 'left')
							->get('repo_docs as rd')
							->result_array();

		return array_merge($data, array(
			'users'				=> $users,
			'documents'			=> $documents
		));
	}

	/**
	  * This callback runs on the read_table method.
	  * With this opportunity you can implement other database instructions like join.
	  *
	  */
	function _callback_table()
	{
		if($this->session->userdata('user_role') == 2)
		{
			$this->db->where($this->table.'.business_partner', $this->session->userdata('business_partner'));
		}
	}

	/**
	  * 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
	  */
	function _before_save($id, &$data)
	{
		$this->cust_save_data_copy = $data;
		unset(
			$data['users'],
			$data['documents']
		);
		if($this->table == "docs_assignment" && $this->session->userdata['user_role'] == 2)
		{
			$data['business_partner'] = $this->session->userdata['business_partner'];
		}
	}

	/**
	  * This callback runs after the insert/update of the crud.
	  * The callback takes as a 1st parameter the primary key value.
	  * With this opportunity you can do other actions after insert/update.
	  *
	  * @param int $id Primary key
	  */
	function _after_save($id)
	{
		if($this->table == "docs_assignment")
		{
			$this->set_repo_docs_to_assingment($id, $this->cust_save_data_copy['documents']);
			$this->set_users_to_assingment($id, $this->cust_save_data_copy['users']);
		}
	}

	/**
	  * Fetch all the records in the table filtered by Business partner
	  *
	  * @param int $bp Business Partner
	  *
	  * @return array
	  */
	function get_by_business_partner($bp)
	{
		$this->db->where('business_partner', $bp);

		return $this->get_all();
	}

	/**
	  * Insert a new rows & delete deprecateds
	  *
	  * @param int $id ID
	  * @param array $documents Array of Document IDs
	  *
	  * @return true
	  */
	function set_repo_docs_to_assingment($id, $documents)
	{
		$results			= $this->db->select('repo_doc_id')
							->where('docs_assignment_id', $id)
							->get('docs_assignment_repo_docs')
							->result_array();

		if(count($results) > 0){
			
			$documents_ids		= [];
			
			foreach($results as $data)
			{
				array_push($documents_ids, $data['repo_doc_id']);
			}
			
			if(!$documents)
			{
				$documents			= [];
			}
			
			$diff_ids			= array_intersect($documents_ids, $documents);
			$new_insert_ids		= array_diff($documents, $diff_ids);
			$del_insert_ids		= array_diff($documents_ids, $diff_ids);
			
			if(count($del_insert_ids) > 0)
			{	
				foreach($del_insert_ids as $value)
				{
					$this->db->where('repo_doc_id', $value)
						->where('docs_assignment_id', $id)
						->delete("docs_assignment_repo_docs");
				}
			}
			if(count($new_insert_ids) > 0)
			{
				foreach($new_insert_ids as $value)
				{
					$this->db->insert("docs_assignment_repo_docs", ["docs_assignment_id" => $id, "repo_doc_id" => $value]);
				}
			}
			
		} else {
			foreach($documents as $value)
			{
				$this->db->insert("docs_assignment_repo_docs", ["docs_assignment_id" => $id, "repo_doc_id" => $value]);
			}
		}
	
		return true;
	}

	/**
	  * Insert a new rows & delete deprecateds
	  *
	  * @param int $id ID
	  * @param array $users Array of User IDs
	  *
	  * @return true
	  */
	function set_users_to_assingment($id, $users)
	{
		$results			= $this->db->select('user_id')
							->where('docs_assignment_id', $id)
							->get('docs_assignment_users')
							->result_array();

		if(count($results) > 0)
		{
			$users_ids			= [];
			foreach($results as $data)
			{
				array_push($users_ids, $data['user_id']);
			}

			if(!$users)
			{
				$users = [];
			}

			$diff_ids			= array_intersect($users_ids, $users);
			$new_insert_ids		= array_diff($users, $diff_ids);
			$del_insert_ids		= array_diff($users_ids, $diff_ids);

			if(count($del_insert_ids) > 0)
			{	
				foreach($del_insert_ids as $value)
				{
					$this->db->where('user_id', $value)
						->where('docs_assignment_id', $id)
						->delete("docs_assignment_users");
				}
			}
			if(count($new_insert_ids) > 0)
			{
				foreach($new_insert_ids as $value)
				{
					$this->db->insert("docs_assignment_users", ["docs_assignment_id" => $id, "user_id" => $value]);
				}
			}
			
		} else {
			foreach($users as $value)
			{
				$this->db->insert("docs_assignment_users", ["docs_assignment_id" => $id, "user_id" => $value]);
			}
		}	
	
		return true;
	}
}	
