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

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

	/**
	  * Fetch all the records in the table filtered by ID
	  *
	  * @param int $id ID
	  *
	  * @return array
	  */
	function get_by_business_partner_id($id)
	{
		return $this->db->select('id, CONCAT(name, " ", surname) as name', false)
				->where('clients.partner_id', $id)
				->get('clients')
				->result_array();
	}

	/**
	  * Insert a new rows & delete deprecateds
	  *
	  * @param int $id User ID
	  * @param array $bpartarray Business partners array
	  *
	  * @return true
	  */
	function custom_insert_data($id, $bpartarray)
	{
		$query				= $this->db->select('business_partner')
							->from($this->table)
							->where('user_id', $id )
							->get();
		$results 			= $query->result_array();
		
		if(count($results) > 0)
		{
			$user_bpartners		= [];
			
			foreach($results as $data)
			{
				array_push($user_bpartners, $data['business_partner']);
			}
			
			if(!$bpartarray)
			{
				$bpartarray			= [];
			}
			
			$diff_ids			= array_intersect($user_bpartners, $bpartarray);

			$new_insert_ids		= array_diff($bpartarray, $diff_ids);
			$del_insert_ids		= array_diff($user_bpartners, $diff_ids);
			
			if(count($del_insert_ids) > 0)
			{	
				foreach($del_insert_ids as $value)
				{
					$this->db->where('business_partner', $value)
						->delete($this->table);
				}
			}

			if(count($new_insert_ids) > 0)
			{
				foreach($new_insert_ids as $value)
				{
					$this->db->insert($this->table, ["user_id" => $id, "business_partner" => $value]);
				}
			}
		} else {
			foreach($bpartarray as $value){
				
				$this->db->insert($this->table, ["user_id" => $id, "business_partner" => $value]);
			}
		}		

		return true;
	}

	/**
	  * Delete a row from the table by the primary value
	  *
	  * @param int $id User ID
	  *
	  * @return true
	  */
	function custom_delete_data($id)
	{
		$this->db->where('user_id', $id)->delete($this->table);

		return true;
	}
}
