<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DB;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use App\Http\Controllers\Logs;
use Illuminate\Support\Facades\Auth;

class Banque extends Model {
	
	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'banques';

    
        /* Conjoint */
    public function getActifAttribute()
    {
        $nbliens=0;
        $nbliens  = $this->NbBeneficiaires;
        if($nbliens==0) $nbliens  += $this->NbEmployeurs;
        if($nbliens==0) $nbliens  += $this->NbVersements;
        //if($nbliens==0) $nbliens  += intval(DB::table('creanciers')->where('bqcle_creancier', '=', $this->id)->count());
        return ($nbliens==0);
    }


    public function getNbBeneficiairesAttribute()
    {
        $nb=0;
        $nb  = intval(DB::table('beneficiaires_banques')->where('banque_id', '=', $this->id)->count());
        return $nb;
    }

    public function getNbEmployeursAttribute()
    {
        $nb=0;
        $nb  = intval(DB::table('employeurs')->where('banque_id', '=', $this->id)->count());
        return $nb;
    }

    public function getNbVersementsAttribute()
    {
        $nb=0;
        $nb  += intval(DB::table('versem')->where('bqcleunik', '=', $this->id)->count());
        $nb  += intval(DB::table('versem_b')->where('bqcleunik', '=', $this->id)->count());
        $nb  += intval(DB::table('versem_h')->where('bqcleunik', '=', $this->id)->count());
        $nb  += intval(DB::table('versem_hg')->where('bqcleunik', '=', $this->id)->count());
        return $nb;
    }

        /* Conjoint */ 
    public function getNbTiersAttribute()
    {
        $nbliens=0;
        $nbliens  = intval(DB::table('beneficiaires')->where('banque_id', '=', $this->id)->count());
        return ($nbliens==0);
    }

    //LOG
     public function log_transaction($url,$operation) {
        $log=new Logs;
        $values="";
        $t_values=$this->getAttributes();
        foreach($t_values as $nom=>$value) $values.=(($values=="")?"":";").$nom."=>".$value; 
        $log->addlog(['url'=>$url,'table'=>$this->table ,'operation'=>$operation,'values'=>$values]);
    }


    /**
     * Fiche Supprimable ?
     */
    public function getcanDeleteAttribute()
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if (!$user->can("BQE_SUP") && !$user->HasRole("ADMINISTRATEUR")) return true;

        if($this->NbBeneficiaires>0) return false;
        if($this->NbVersements>0) return false;


        return true;
    }

}
