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

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

	/**
	  * This callback runs on the read_table method.
	  * With this opportunity you can implement other database instructions like join.
	  *
	  */
	function _callback_table()
	{
		$this->db->join('admin', 'LOWER('.$this->table.'.admin_id)=LOWER(admin.id)', 'LEFT');
	}

	/**
	  * 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)
	{
		if(isset($data['password']) && empty($data['password']))
		{
			unset($data['password']);
		}
		if(isset($data['password']))
		{
			$data['password']	= md5($data['password']);
		}
		
		if($this->table == "users")
		{
			$this->cust_save_data_copy = $data;
			unset($data['business_partner']);
			$data['admin_id']	= $this->session->userdata('manager');
			$data['updated_at']	= date('Y-m-d H:i:s');
		}

		$this->save_data_copy = $data;
	}

	/**
	  * 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 == "users")
		{
			$this->load->model("users_bpartner_m");

			$this->users_bpartner_m->custom_insert_data($id, $this->cust_save_data_copy['business_partner']);
		}
	}

	/**
	  * This callback runs before the delete of the crud.
	  * The callback takes as a 1st parameter the primary key value.
	  * With this opportunity you can do other actions before delete.
	  *
	  * @param int $id Primary key
	  */
	function _before_delete($id)
	{
		if($this->table == "users")
		{
			$this->load->model("users_bpartner_m");

			$this->users_bpartner_m->custom_delete_data($id);
		}
	}
}
