<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DB;
use PDF;

class ApprovisionnementController extends Controller
{
    //
	function VoirSuppressiondetail ($id) {

        $detail= DB::table('ligne_appro_vendable')->where('id',$id)->first();
        return [

            'detail' => $detail,
        ];
    }
    public function consulter($id)
	{
		if(session('user')== null) {
            return redirect('/');
        }
        
		$detail=DB::table('ligne_appro_vendable')->where('appro_id',$id)->get();
		$total=DB::table('ligne_appro_vendable')->where('appro_id',$id)->get()->sum('montligne');

		return view('appro/detail', [
			'detail'=> $detail,
			'total'=> $total,
		]);
	}
	function supprimerdetail () {

        $id=request('id');
		$appro= DB::table('ligne_appro_vendable')->where('id', $id)->first()->appro_id;
		DB::table('ligne_appro_vendable')->where('id', $id)->delete();
		
		
	return redirect()->route('consultation_appro',['id'=>$appro])->with('status', 'Suppression effectuée avec succes');
    }
	//Modifier
	function modifappro($id) {
        if(session('user')== null) {
            return redirect('/');
        }
        $fournisseurs = DB::table('fournisseur')->get();
        $produits = DB::table('produit_vendable')->get();
        $cat = DB::table('categorie')->get();
        $magasin = DB::table('magasin')->orderBydesc('id')->get();
        $depot = DB::table('depot')->orderBydesc('id')->get();
        $ligne_appro = DB::table('ligne_appro_vendable')->where('appro_id',$id)->get();
		$appro = DB::table('appro_vendable')->where('id',$id)->first();
        return view('appro/modifier',[
            'fournisseurs' => $fournisseurs,
            'produits' => $produits,
            'magasin' => $magasin,
            'depot' => $depot,
            'cat' => $cat,
            'ligne_appro' => $ligne_appro,
            'appro' => $appro,
        ]);
    }

    function voirvalider ($id) {

        $appro= DB::table('appro_vendable')->where('id',$id)->first();
        return [
            'appro' => $appro,
        ];
    }
    
    function valider () {

        $id=request('id');
		$todayyy = date('Y-m-d');
		$today2 = date('Y-m-d');
		$today=date('Y-m-d');

            DB::table('appro_vendable')->where('id', $id)->update(
                [
                    'etat' => "Validée",
                ]
            );

            DB::table('ligne_appro_vendable')->where('appro_id', $id)->update(
                [
                    'etat' => "Validée",
                ]
            );
        $appro =  DB::table('appro_vendable')->where('id', $id)->first();
        $ligne = DB::table('ligne_appro_vendable')->where('appro_id', $id)->get();
		$fou = DB::table('appro_vendable')->where('id', $id)->first()->fournisseur_id;
		$ref = DB::table('appro_vendable')->where('id', $id)->first()->numero;
		$lh = DB::table('appro_vendable')->where('id', $id)->first()->montant;
		//$magasin = DB::table('appro_vendable')->where('id', $id)->first()->magasin_id;
        foreach($ligne as $lignes){
            //$qtesto = DB::table('produit_vendable')->where('id', $lignes->produit_id)->first()->stock_general;
            //$qtesto = DB::table('produit_vendable')->where('id', $lignes->produit_id)->first()->stock_magasin;
            $qteval = $lignes->qte;
			if ($appro->depot_id > 0){
			   $verif = DB::table('magasin_general')->where('produit_id', $lignes->produit_id)->where('depot_id', $appro->depot_id)->get()->count();
			   if ($verif>0){
			       $sm = DB::table('magasin_general')->where('produit_id', $lignes->produit_id)->where('depot_id', $appro->depot_id)->orderBydesc('id')->take(1)->first()->apres;
			   }else{
			       $sm = 0;
			   }
				DB::table('magasin_general')->insert(
                    [
                        'date' => $lignes->date,
                        'produit_id' => $lignes->produit_id,
                        'qte' => $qteval,
                        'type_operation' => 'Appro',
						'en_stock' => $sm,
						'apres' => ($sm + $qteval),
						'depot_id' => $appro->depot_id,
						//'stock_general' => ($qtesto + $qteval),
                    ]
                );
			} else {
				$verif = DB::table('stock_magasin')->where('produit_id', $lignes->produit_id)->where('magasin_id', $appro->magasin_id)->get()->count();
    			if ($verif>0){
    				$sm = DB::table('stock_magasin')->where('produit_id', $lignes->produit_id)->where('magasin_id', $appro->magasin_id)->orderBydesc('id')->take(1)->first()->apres;
    			}else{
    			    $sm = 0;
    			}
    				DB::table('stock_magasin')->insert(
                        [
                            'date' => $lignes->date,
                            'produit_id' => $lignes->produit_id,
                            'qte' => $qteval,
                            'type_operation' => 'Appro',
    						'en_stock' => $sm,
    						'apres' => ($sm + $qteval),
    						'magasin_id' => $appro->magasin_id,
    						'appro_id' => $id,
    						'user_id' => session('user')->id,
                        ]
                    );
    			}
                    DB::table('produit_vendable')->where('id', $lignes->produit_id)->update(
                        [
                            'pr' => $lignes->pa,
                            //'stock_general' => ($qtesto + $qteval),
                        ]
                    );
        			
                }
				$solde = DB::table('transaction_fournisseur')->where('fournisseur_id', $fou)->get()->count();
				if ($solde > 0){
					$solde_compte = DB::table('transaction_fournisseur')->where('fournisseur_id', $fou)->orderBydesc('id')->take(1)->first()->solde_compte;
					$ss = $solde_compte + $lh;
				}else{
					$solde_compte = 0;
					$ss = $lh;
				}
				
				DB::table('transaction_fournisseur')->insert(
                    [
                        'date' => $todayyy,
                        'libelle' => 'Achat '.$ref,
                        'montant' => $lh,
						'solde_initial' => $solde_compte,
						'solde_compte' => $ss,
						'type' => 'Crédit',
						'fournisseur_id' => $fou,
						'appro_id' => $id,
                    ]
                );

        return redirect()->route('nouveau_appro')->with('status', 'Validation effectuée avec succès');
	}

    function nouveau() {
		if(session('user')== null) {
            return redirect('/');
        }
       
        $fournisseurs = DB::table('fournisseur')->get();
        $produits = DB::table('produit_vendable')->orderby('designation','asc')->get();
		$categorie=DB::table('categorie')->get();
        $appros = DB::table('appro_vendable')->where('etat_transfert','En cours')->orderBy('etat','ASC')->get();
        $magasin = DB::table('magasin')->orderBydesc('id')->get();
        $depot = DB::table('depot')->orderBydesc('id')->get();

        return view('appro/nouveau',[

            'fournisseur' => $fournisseurs,
            'produit' => $produits,
            'appro' => $appros,
            'magasin' => $magasin,
            'depot' => $depot,
			'cat'=> $categorie,
        ]);
    }
    
	
	function listedesappro() {
       if(session('user')== null) {
            return redirect('/');
        }
        $fournisseurs = DB::table('fournisseur')->get();
        //$produits = DB::table('produit_vendable')->get();
        $appros = DB::table('appro_vendable')->where('etat', 'Validée')->orderBydesc('id')->get();
        $total = DB::table('appro_vendable')->where('etat', 'Validée')->get()->sum('montant');
        //$magasin = DB::table('magasin')->orderBydesc('id')->get();

        return view('appro/liste',[

            'fournisseur' => $fournisseurs,
            //'produit' => $produits,
            'appro' => $appros,
            'total' => $total,
            //'magasin' => $magasin,
        ]);
    }
	public function recherche() {
		$date_debut = request('date_debut');
		$fou = request('fou');
        $date_debut= explode('/', $date_debut);
        $date_debut= array_reverse($date_debut);
        $date_debut= implode('-', $date_debut);

        $date_fin = request('date_fin');
        $date_fin= explode('/', $date_fin);
        $date_fin= array_reverse($date_fin);
        $date_fin= implode('-', $date_fin);
		
				session(['date_debut'=> $date_debut]);
				session(['date_fin'=> $date_fin]);
				session(['fou'=> $fou]);
		
		 if($date_fin > $date_debut || $date_fin == $date_debut){
			if ($fou==0){
				$appro = DB::table('appro_vendable')->whereBetween('date_appro', [$date_debut,$date_fin])->get();
				$approcount=DB::table('appro_vendable')->whereBetween('date_appro', [$date_debut,$date_fin])->get()->count();
				$total = DB::table('appro_vendable')->where('etat', 'Validée')->whereBetween('date_appro', [$date_debut,$date_fin])->get()->sum('montant');
			} else {
				$appro = DB::table('appro_vendable')->where('fournisseur_id', $fou)->whereBetween('date_appro', [$date_debut,$date_fin])->get();
				$approcount=DB::table('appro_vendable')->where('fournisseur_id', $fou)->whereBetween('date_appro', [$date_debut,$date_fin])->get()->count();
				$total = DB::table('appro_vendable')->where('fournisseur_id', $fou)->where('etat', 'Validée')->whereBetween('date_appro', [$date_debut,$date_fin])->get()->sum('montant');
			}
			$fournisseur = DB::table('fournisseur')->orderBydesc('id')->get();
			return view('appro/liste-appro-recherche',[
            'appro' => $appro,
            'fou' => $fou,
            'fournisseur' => $fournisseur,
            'approcount' => $approcount,
            'date_debut' => $date_debut,
            'date_fin' => $date_fin,
            'total' => $total,
        ]);	
		 } else 
		 {
			return redirect()->route('liste-des-appro')->with('error', 'La date de fin ne doit pas dépasser la date de début!');
		 }
	}
	
	//FACTURE Appro
	
	function factureappro($id)
    {

		$appro = DB::table('appro_vendable')->where('id',$id)->first();
		$ligne = DB::table('ligne_appro_vendable')->where('appro_id',$id)->get();
		$lignem = DB::table('ligne_appro_vendable')->where('appro_id',$id)->where('etat','Validée')->sum('montligne');
        $pdf = PDF::loadView('/appro/facture', [
            'ligne' => $ligne,
			'appro' => $appro,
			'lignem' => $lignem,
		]);
		
        return $pdf->stream();
    }

    function enregistrer(Request $request)
    {

        $fournisseur=request('fournisseur');
        $stockage=request('stockage');
        $magasin_id=request('magasin_id');
        $depot_id=request('depot_id');
        $dateappro=implode('-', array_reverse(explode('/', request('dateappro'))));
        $approvision=collect(request('approvision'))->chunk(4);

            DB::table('appro_vendable')->insert(
                [
                    'fournisseur_id' => $fournisseur,
                    'magasin_id' => $magasin_id,
                    'depot_id' => $depot_id,
                    'date_appro' => $dateappro,
                    'stockage' => $stockage,
                    'etat' => "Proforma",
					'user_id' => session('user')->id,
                ]
            );

            $idLastappro = DB::table('appro_vendable')->get()->last()->id;

            $id2= strlen($idLastappro);

            if ($id2==1){

                DB::table('appro_vendable')->where('id', $idLastappro)->update(
                    [
                        'numero' => 'APPRO-000'.$idLastappro,
                    ]
                );

            } elseif ($id2==2){

                DB::table('appro_vendable')->where('id', $idLastappro)->update(
                    [
                        'numero' => 'APPRO-00'.$idLastappro,
                    ]
                );

            } elseif ($id2==3){

                DB::table('appro_vendable')->where('id', $idLastappro)->update(
                    [
                        'numero' => 'APPRO-0'.$idLastappro,
                    ]
                );

            } else {

                DB::table('appro_vendable')->where('id', $idLastappro)->update(
                    [
                        'numero' => 'APPRO-'.$idLastappro,
                    ]
                );
            }

        $i=0;

        foreach ($approvision as $key=> $approvisions){

            $qtesto =  DB::table('produit_vendable')->where('id', $approvisions[1 +$i])->first()->stock_magasin;
            //$categorie_id =  DB::table('produit_vendable')->where('id', $approvisions[0 +$i])->first()->categorie_id;

            DB::table('ligne_appro_vendable')->insert(
                [
                    'appro_id' => $idLastappro,
                    'fournisseur_id' => $idLastappro,
                    'etat' => "Proforma",
                    'produit_id' => $approvisions[1 +$i],
                    'categorie_id' => $approvisions[0 +$i],
                    'qte' => $approvisions[2 +$i],
                    'pa' => $approvisions[3 +$i],
                    'montligne' => ($approvisions[2 +$i] * $approvisions[3 +$i]),
					'date' => $dateappro,
					'en_stock' => $qtesto,
                    'apres' => ($qtesto + $approvisions[2 +$i]),
					'user_id' => session('user')->id,
                ]
            );

            $i += count($approvisions->toArray());

        }

            $message = [
                "title" => 'Succès',
                "type" => 'success',
                "response" => 'Enregistrement effectué avec succès !',
            ];

            return $message;
    }
	function modifapprop($id)
    {

        $fournisseur=request('fournisseur');
        $magasin=request('magasin');
        $dateappro=implode('-', array_reverse(explode('/', request('dateappro'))));
        $approvision=collect(request('approvision'))->chunk(3);

		$supl = DB::table('ligne_appro_vendable')->where('appro_id', $id)->delete();
		
		DB::table('appro_vendable')->where('id', $id)->update(
                [
                    'fournisseur_id' => $fournisseur,
                    'magasin_id' => $magasin,
                    'date_appro' => $dateappro,
                    'etat' => "Proforma",
                   
                ]
            );
			$idLastappro = DB::table('appro_vendable')->where('id', $id)->first()->id;

		$i=0;
        foreach ($approvision as $key=> $approvisions){

            $qtesto =  DB::table('produit_vendable')->where('id', $approvisions[0 +$i])->first()->stock_general;

            DB::table('ligne_appro_vendable')->insert(
                [
                    'appro_id' => $idLastappro,
					'magasin_id' => $magasin,
                    'fournisseur_id' => $idLastappro,
                    'etat' => "Proforma",
                    'produit_id' => $approvisions[0 +$i],
                    'qte' => $approvisions[1 +$i],
                    'pa' => $approvisions[2 +$i],
                    'montligne' => ($approvisions[1 +$i] * $approvisions[2 +$i]),
					'date' => $dateappro,
					'en_stock' => $qtesto,
                    'apres' => ($qtesto + $approvisions[1 +$i]),
                ]
            );

            $i += count($approvisions->toArray());

        }

            $message = [
                "title" => 'Succès',
                "type" => 'success',
                "response" => 'Modification effectuée avec succès !',
            ];
            return $message;

    }
	
//ENREGISTREMENT DEPENSE
	function enregistrer3(Request $request)
    {
        $montant=request('montant');
        $nature=request('nature');
        $note=request('note');
        $today=date('Y-m-d');
		$dated=implode('-', array_reverse(explode('/', request('dated'))));
		if ($nature == "Appro caisse" || $nature == "Retour en caisse" ){
			$typeoperation = "Crédit";
			$nature1 = "Appro caisse";
			$nature22 = 0;
		} else {
			$typeoperation = "Débit";
			$nature1 = DB::table('typedepense')->where('id', $nature)->first()->libelle; 
			$nature22 =$nature;
		}
		
		DB::table('caisse_depense')->insert(
                [
                    'date' => $dated,
                    'nature' => $nature1,
                    'depense_id' => $nature22,
                    'typeoperation' => $typeoperation,
                    'montant' => $montant,
					'note' => $note,
					'user_id' => session('user')->id,
                ]
            );		
				$message = [
				"title" => 'Succès',
				"type" => 'success',
				"response" => 'Succès de l\'enregistrement',
			];
			return $message;
	}
	public function voir(){
      
        if(session('user')== null) {
            return redirect('/');
        }
		
		$fou= DB::table('fournisseur')->orderBy('nom')->get();
		$depense= DB::table('caisse_depense')->orderBydesc('id')->get();
		$typedepense = DB::table('typedepense')->orderBy('libelle','asc')->get(); 
		return view('solde/nouveau',[
		
		'fou' => $fou,
		'depense' => $depense,
		'typedepense' => $typedepense,

	]);
	}
	public function rechdepensepost(){
      
        if(session('user')== null) {
            return redirect('/');
        }
		$magasin_id= request('magasin_id');
		$date_debut= implode('-', array_reverse(explode('/', request('date_debut'))));
		$date_fin= implode('-', array_reverse(explode('/', request('date_fin'))));
		$magasin = DB::table('magasin')->get();
		if($date_fin > $date_debut || $date_fin == $date_debut){
		$depense= DB::table('caisse_depense')->where('magasin_id', $magasin_id)->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('date')->get();
		$tot = DB::table('caisse_depense')->where('magasin_id', $magasin_id)->whereBetween('date', [$date_debut,$date_fin])->sum('montant');
		return view('solde/depenserech',[
		'depense' => $depense,
		'magasin' => $magasin,
		'mag_id' => $magasin_id,
		'date_debut' => $date_debut,
		'date_fin' => $date_fin,
		'tot' => $tot,
	]);
	} else{
		return redirect()->route('caisse')->with('error', 'La date de début doit être suppérieure à la date finale sélectionnée');
	}}
	/*public function voirdep($id){
		$depense= DB::table('caisse_depense')->where('id', $id)->first();
		return [
		'depense' => $depense,
	];
	}
	public function suppdep(){
		$id = request('id');
		DB::table('caisse_depense')->where('id', $id)->delete();
		return redirect()->route('caisse')->with('status', 'Suppression effectuée avec succès');
	}*/
	public function voirdep($id){
		$depense= DB::table('caisse_depense')->where('id', $id)->first();
		return [
		'depense' => $depense,
	];
	}
	public function suppdep(){
		$id = request('id');
		DB::table('caisse_depense')->where('id', $id)->delete();
		return redirect()->route('caisse')->with('status', 'Suppression effectuée avec succès');
	}
	public function validerdep(){
		$id = request('id');
		DB::table('caisse_depense')->where('id', $id)->update([
			'etat' => 'Validée'
		]);
		return redirect()->route('caisse')->with('status', 'Validation effectuée avec succès');
	}
	public function annulerdep(){
		$id = request('id');
		DB::table('caisse_depense')->where('id', $id)->update([
			'etat' => 'Annulée'
		]);
		return redirect()->route('caisse')->with('status', 'Enregistrement annulé avec succès');
	}
	public function achatfou($id){
      
        if(session('user')== null) {
            return redirect('/');
        }
		$appro= DB::table('appro_vendable')->where('fournisseur_id',$id)->where('etat','Validée')->get();
		$total= DB::table('appro_vendable')->where('fournisseur_id',$id)->where('etat','Validée')->get()->sum('montant');
		$totalpaie= DB::table('paiement_fou')->where('fournisseur_id',$id)->get()->sum('montant');
		$reste = $total - $totalpaie;
		$fou= DB::table('fournisseur')->where('id',$id)->first()->nom;
	return view('appro/liste-des-appro-fournisseurs',[
		'appro' => $appro,
		'fou' => $fou,
		'total' => $total,
		'totalpaie' => $totalpaie,
		'reste' => $reste,
	]);
	}
	// Fonction supprimer
	function supprimer () {

        $id=request('id');

        DB::table('ligne_appro_vendable')->where('appro_id', $id)->delete();

        DB::table('appro_vendable')->where('id', $id)->delete();

        return redirect()->route('nouveau_appro')->with('status', 'Suppression effectuée avec succes');
    }
	
	//TRANSFERER VERS UN DEPOT
	
	    function transferer () {

        $id=request('id');
        $magasin=request('depot_id');
		$todayyy = date('Y-m-d');
		$today2 = date('Y-m-d');
		$today=date('Y-m-d');

        $fou_id = DB::table('appro_vendable')->where('id', $id)->first()->fournisseur_id;
        $fou_pays = DB::table('fournisseur')->where('id', $fou_id)->first()->pays;
		
		/*if ($fou_pays == "CHINE"){
			$magasin = 1;
		} else {
			$magasin = 2;
		}*/
		
		DB::table('transfertdepot')->insert(
            [
                'date' => $today2,
                'magasin_id' => $magasin,
                'etat' => "En cours",
                'user_id' => session('user')->id,
            ]
        );

        $idLasttranfert = DB::table('transfertdepot')->get()->last()->id;
		$idLastetat = DB::table('transfertdepot')->get()->last()->etat;
		$idLast= strlen($idLasttranfert);
		
		if ($idLast==1){
            DB::table('transfertdepot')->where('id', $idLasttranfert)->update(
                [
                    'numero' => 'TRANSFERT-'.'000'.$idLasttranfert,
                ]
            );
        } elseif ($idLast==2){
    
            DB::table('transfertdepot')->where('id', $idLasttranfert)->update(
                [
                    'numero' => 'TRANSFERT-'.'00'.$idLasttranfert,
                ]
            );
        } elseif ($idLast==3){
            DB::table('transfertdepot')->where('id', $idLasttranfert)->update(
                [
                    'numero' => 'TRANSFERT-'.'0'.$idLasttranfert,
                ]
            );
        } else {
            DB::table('transfertdepot')->where('id', $idLasttranfert)->update(
                [
                    'numero' => 'TRANSFERT-'.$idLasttranfert,
                ]
            );
        }
        $ligne = DB::table('ligne_appro_vendable')->where('appro_id', $id)->get();
		/*
		$fou = DB::table('appro_vendable')->where('id', $id)->first()->fournisseur_id;
		$ref = DB::table('appro_vendable')->where('id', $id)->first()->numero;
		$lh = DB::table('appro_vendable')->where('id', $id)->first()->montant;
		//$magasin = DB::table('appro_vendable')->where('id', $id)->first()->magasin_id;
		
		*/
		
		
		
        foreach($ligne as $lignes){

            //$qtesto = DB::table('produit_vendable')->where('id', $lignes->produit_id)->first()->stock_general;
            $qtesto = DB::table('produit_vendable')->where('id', $lignes->produit_id)->first()->stock_magasin;

            $qteval = $lignes->qte;
			
			DB::table('ligne_transfertdepot')->insert(
						[
								'transfert_id' => $idLasttranfert,
								'produit_id' => $lignes->produit_id,
								'qte' => $lignes->qte,
								'etat' => $idLastetat,    
								'magasin_id' => $magasin, 
								'user_id' => session('user')->id,
								'date' => $today2,
								
						]
					);
				}
				
				DB::table('appro_vendable')->where('id', $id)->update(
					[
						'etat_transfert' => "Validée",
					]
				);
				
				return redirect()->route('nouveau_transfertdepot')->with('status', 'Transfert validé avec succès !');
		}

}
