<?php
/**
 * Define a Fiche employé
 * @author Administrateur PRINCIPAL
 * @category Plugin
 * @license MIT
 */
class Employee extends Entity{

	public $id;
	public $photo; //Photo (Image)
	public $birthName; //Nom de naissance (Texte)
	public $name; //Nom marital (Texte)
	public $firstname; //Prénom (Texte)
	public $job; //Poste (Liste configurable)
	public $jobDescription; //Rôle/Missions (Texte enrichis)
	public $manager; //Responsable (Employee)
	public $account; //Responsable (Utilisateur)
	public $workplace; //Lieu de travail (Adresse)
	public $hardware; //Mise a disposition de matériel (Liste configurable)
	public $comment; //Comment (Wysiwyg)
	public $state; //Etat (Texte)


	protected $TABLE_NAME = 'employee';
	public $entityLabel = 'Fiche employé';
	public $fields = array(
		'id' => array('type'=>'key', 'label' => 'Identifiant'),
		'birthName' => array('type'=>'text', 'label' => 'Nom de naissance'),
		'name' => array('type'=>'text', 'label' => 'Nom marital'),
		'firstname' => array('type'=>'text', 'label' => 'Prénom'),
		'job' => array('type'=>'dictionary', 'label' => 'Poste'),
		'jobDescription' => array('type'=>'wysiwyg', 'label' => 'Rôle/Missions'),
		'manager' => array('type'=>'integer','label' => 'Responsable','link'=>'plugin/employee/Employee.class.php'),
		'account' => array('type'=>'user','label' => 'Compte lié'),
		'workplace' => array('type'=>'address', 'label' => 'Lieu de travail'),
		'hardware' => array('type'=>'longstring', 'label' => 'Mise a disposition de matériel'),
		'comment' => array('type'=>'wysiwyg', 'label' => 'Information sur le recrutement'),
		'state' => array('type'=>'text', 'label' => 'Etat'),
	);



	public function picture(){
		$pictures = glob(File::dir().'employee/employee/'.$this->id.'/photo.*');
		return !empty($pictures) ? $pictures[0] : '';
	}

	//Surchage de toArray pour prendre en compte le fullName et les initials régulierement utilisé en toArray
    public function toArray($decoded=false) {
        $fields = parent::toArray($decoded);
        $fields['fullName'] = $this->fullName();
        if($decoded){
            $fields['fullName'] = html_entity_decode($fields['fullName']);
        }
        return $fields;
    }

    public function fullName(){
        return ucfirst(mb_strtolower($this->firstname)).' '.mb_strtoupper($this->name);
    }

    //managers récursifs de l'employé ciblé
    public static function managers($employee){
    	$alloweds  = array();
    	$alloweds[] = $employee;
		if(!empty($employee->manager) && $employee->manager!=$employee->id){
			$alloweds = array_merge($alloweds,self::managers(Employee::getById($employee->manager)));
		}
		return $alloweds;
    }

    //suboordonés récursifs de l'employé ciblé
    public static function subordinates($employee,$employees = null,$recursive = true){
    	$subordinates = array();
    	if(!isset($employee) || empty($employee->id)) return $subordinates;
    	if(!isset($employees)){
    		$employees = array();
    		foreach(self::loadAll() as $item){
    			if(!isset($employees[$item->manager])) $employees[$item->manager] = array();
    			$employees[$item->manager][$item->id] = $item;
    		}
    	}

    	$currentSubordinates = isset($employees[$employee->id]) ? $employees[$employee->id] : array();

		foreach($currentSubordinates as $subordinate){
			$subordinates[$subordinate->id] = $subordinate;
			if($recursive) $subordinates = array_merge($subordinates,self::subordinates($subordinate,$employees));
		}

		return $subordinates;
    }

    public function can($targetEmployee,$crud){

    	//Droits de visibilité sur la fiche :
		// - L'admin configure dans tous les cas
		// - Le créateur de la fiche si pas de manager renseigné
		// - Le manager si renseigné
		$user = User::byLogin($this->account);
		if($user->can('employee','configure')) return true;
		if(!$user->can('employee',$crud)) return false;

		$hierarchy = array();
		foreach(Employee::subordinates($this) as $subordinate){
			$subordinatesIds[] = $subordinate->id;
		}
		$subordinatesIds[] = $this->id;
		if(empty($targetEmployee->manager) && $targetEmployee->creator==$user->login) return true;
		if(!in_array($targetEmployee->manager,$subordinatesIds)) return false;
		return true;
    }

    public function currentContract(){
    	require_once(__DIR__.SLASH.'EmployeeContract.class.php');
    	require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
    	$contract = new EmployeeContract();

    	$contracts = EmployeeContract::staticQuery('SELECT main.*,'.EmployeeWorkTime::joinString('wt').','.Dictionary::joinString('ty').' FROM {{table}} main
    		LEFT JOIN '.EmployeeWorkTime::tableName().' wt ON main.worktime = wt.id
    		LEFT JOIN '.Dictionary::tableName().' ty ON main.type = ty.id
    		WHERE (main.`end` IS NULL OR main.`end` = "" OR  main.`end` > ?) AND main.employee=? LIMIT 1',array(time(),$this->id),true,1);

    	if(isset($contracts[0])) $contract = $contracts[0];

    	return $contract;
    }

    public function photo(){

    	if(count(glob(File::dir().SLASH.'employee'.SLASH.'employee'.SLASH.$this->id.SLASH.'photo.*')) ==0 ) return 'img/default-avatar.png';
		return  'action.php?action=employee_employee_photo&type=download&path='.base64_encode('employee/employee/'.$this->id.'/photo.*');
    }

	//Colonnes indexées
	public $indexes = array();

}
?>
