<?php namespace App\Http\Controllers\Compta_old;

use Auth\AuthController;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Plan;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use View;
use DB;


class BilansController extends Controller {
    private $menu='old_compta';
    private $submenu='compta_old_bilans';
    private $menu_home='comptabilite';

    public function index($categ="R")
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        $exercice=date('Y')-1;

        $plans=Plan::all();
        $plans_categ=Plan::where("categ","=",$categ)->get();
            
        $t_bilan_actif=array();
        $t_bilan_passif=array();
        foreach($plans_categ as $plan_categ) {
            $categ_bilan=$plan_categ->categ_bilan;
            if($categ_bilan!="") {
                $actif=($categ_bilan=="A");
                $passif=($categ_bilan=="P");
                $solde=$plan_categ->getSoldeCalc($exercice);

                //ACTIF
                if($actif) {
                    //$brut=-$brut;
                    $amort_prec=0;$amort=0;
                    $amortissement=$plan_categ->amort;
                    $plan_amortissement=Plan::where("numcpt","=",$amortissement)->first();

                    // Precedante
                    if($plan_amortissement) $amort_prec=$plan_amortissement->getSoldeCalc($exercice-1);
                    $netprec=(-$plan_categ->getSoldeCalc($exercice-1))-$amort_prec;

                    // En cours
                    if($plan_amortissement) $amort=$plan_amortissement->getSoldeCalc($exercice);
                    $net=$solde-$amort;

                    $value=$plan_categ->numcpt.";";
                    $value.=$plan_categ->nomcpt.";";
                    $value.=$netprec.";";
                    $value.=$solde.";";
                    $value.=$amort.";";
                    $value.=$solde-$amort.";";
                    $t_bilan_actif[$plan_categ->numcpt]=$value;
                } 

                //PASSIF
                if($passif) {
                    // Precedante
                    $netprec=($plan_categ->getSoldeCalc($exercice-1));
                    // En cours
                    $value=$plan_categ->numcpt.";";
                    $value.=$plan_categ->nomcpt.";";
                    $value.=$netprec.";";
                    $value.=$solde.";";
                    $t_bilan_passif[$plan_categ->numcpt]=$value;
                }
            }
        }


        return View::make('compta_old.bilan.index', [ 
            'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,
            'exercice'=>$exercice,
            'plans'=>$plans,
            't_bilan_actif'=>$t_bilan_actif,
            't_bilan_passif'=>$t_bilan_passif,
            'categ'=>$categ
        ]);
    }



}