<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DB;
use PDF;

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

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

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

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

        $id=request('id');
		$appro= DB::table('ligne_appro_matiere')->where('id', $id)->first()->appro_matiere_id;
		DB::table('ligne_appro_matiere')->where('id', $id)->delete();
		
		
	return redirect()->route('consultation_appro_matiere',['id'=>$appro])->with('status', 'Suppression effectuée avec succes');
    }
	//Modifier
	function modifappro($id) {
        if(session('user')== null) {
            return redirect('/');
        }
        $fournisseurs = DB::table('fournisseur')->get();
        $matiere = DB::table('matiere')->get();
        $magasin = DB::table('magasin')->orderBydesc('id')->get();
        $ligne_appro = DB::table('ligne_appro_matiere')->where('appro_matiere_id',$id)->get();
		$appro = DB::table('appro_matiere')->where('id',$id)->first();
        return view('appromatiere/modifier',[
            'fournisseurs' => $fournisseurs,
            'produits' => $produits,
            'magasin' => $magasin,
            'ligne_appro' => $ligne_appro,
            'appro' => $appro,
        ]);
    }

    function voirvalider ($id) {

        $appro= DB::table('appro_matiere')->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_matiere')->where('id', $id)->update(
                [
                    'etat' => "Validée",
                ]
            );

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

        $ligne = DB::table('ligne_appro_matiere')->where('appro_matiere_id', $id)->get();
		$fou = DB::table('appro_matiere')->where('id', $id)->first()->fournisseur_id;
		$ref = DB::table('appro_matiere')->where('id', $id)->first()->numero;
		$lh = DB::table('appro_matiere')->where('id', $id)->first()->montant;
		$magasin = DB::table('appro_matiere')->where('id', $id)->first()->magasin_id;
        foreach($ligne as $lignes){

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

            $qteval = $lignes->qte;
			
			$verif = DB::table('stock_matiere')->where('matiere_id', $lignes->matiere_id)->get()->count();
			if ($verif>0){
				$sm = DB::table('stock_matiere')->where('matiere_id', $lignes->matiere_id)->orderBydesc('id')->take(1)->first()->apres;
				DB::table('stock_matiere')->insert(
                    [
                        'date' => $today,
                        'matiere_id' => $lignes->matiere_id,
                        'qte' => $qteval,
                        'type_operation' => 'Appro',
						'en_stock' => $sm,
						'apres' => ($sm + $qteval),
						
                    ]
                );
			} else {
				$sm = 0;
				DB::table('stock_matiere')->insert(
                    [
                        'date' => $today,
                        'matiere_id' => $lignes->matiere_id,
                        'qte' => $qteval,
                        'type_operation' => 'Appro',
						'en_stock' => $sm,
						'apres' => ($sm + $qteval),
						
                    ]
                );
			}
			
            DB::table('matiere')->where('id', $lignes->matiere_id)->update(
                [
                    'stock_general' => ($qtesto + $qteval),
                    //'stock_tous' => ($qtesto + $qteval),
                ]
            );	
        }

        return redirect()->route('appro-matiere')->with('status', 'Validation effectuée avec succes');
	}
	
	function annuler () {

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

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

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

        $ligne = DB::table('ligne_appro_matiere')->where('appro_matiere_id', $id)->get();
		$fou = DB::table('appro_matiere')->where('id', $id)->first()->fournisseur_id;
		$ref = DB::table('appro_matiere')->where('id', $id)->first()->numero;
		$lh = DB::table('appro_matiere')->where('id', $id)->first()->montant;
		$magasin = DB::table('appro_matiere')->where('id', $id)->first()->magasin_id;
        foreach($ligne as $lignes){

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

            $qteval = $lignes->qte;
			
			$verif = DB::table('stock_matiere')->where('matiere_id', $lignes->matiere_id)->get()->count();
			if ($verif>0){
				$sm = DB::table('stock_matiere')->where('matiere_id', $lignes->matiere_id)->orderBydesc('id')->take(1)->first()->apres;
				DB::table('stock_matiere')->insert(
                    [
                        'date' => $today,
                        'matiere_id' => $lignes->matiere_id,
                        'qte' => $qteval,
                        'type_operation' => 'Annulationappro',
						'en_stock' => $sm,
						'apres' => ($sm - $qteval),
						
                    ]
                );
			} else {
				$sm = 0;
				DB::table('stock_matiere')->insert(
                    [
                        'date' => $today,
                        'matiere_id' => $lignes->matiere_id,
                        'qte' => $qteval,
                        'type_operation' => 'Annulationappro',
						'en_stock' => $sm,
						'apres' => ($sm - $qteval),
						
                    ]
                );
			}
			
            DB::table('matiere')->where('id', $lignes->matiere_id)->update(
                [
                    'stock_general' => ($qtesto - $qteval),
                    //'stock_tous' => ($qtesto + $qteval),
                ]
            );	
        }

        return redirect()->route('appro-matiere')->with('status', 'Approvisionnement annulé avec succès');
	}

    function nouveau() {
		if(session('user')== null) {
            return redirect('/');
        }
       
        $fournisseurs = DB::table('fournisseur')->get();
        $matiere = DB::table('matiere')->orderby('designation','asc')->get();
        $appros = DB::table('appro_matiere')->orderBydesc('id') ->limit(5)->get();
        $magasin = DB::table('magasin')->orderBydesc('id')->get();

        return view('appromatiere/nouveau',[

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

        return view('appromatiere/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_matiere')->whereBetween('date_appro', [$date_debut,$date_fin])->get();
				$approcount=DB::table('appro_matiere')->whereBetween('date_appro', [$date_debut,$date_fin])->get()->count();
				$total = DB::table('appro_matiere')->where('etat', 'Validée')->whereBetween('date_appro', [$date_debut,$date_fin])->get()->sum('montant');
			} else {
				$appro = DB::table('appro_matiere')->where('fournisseur_id', $fou)->whereBetween('date_appro', [$date_debut,$date_fin])->get();
				$approcount=DB::table('appro_matiere')->where('fournisseur_id', $fou)->whereBetween('date_appro', [$date_debut,$date_fin])->get()->count();
				$total = DB::table('appro_matiere')->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('appromatiere/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_matiere')->where('id',$id)->first();
		$ligne = DB::table('ligne_appro_matiere')->where('appro_matiere_id',$id)->get();
		$lignem = DB::table('ligne_appro_matiere')->where('appro_matiere_id',$id)->where('etat','Validée')->sum('montligne');
        $pdf = PDF::loadView('/appromatiere/facture', [
            'ligne' => $ligne,
			'appro' => $appro,
			'lignem' => $lignem,
		]);
		
        return $pdf->stream();
    }

    function enregistrer(Request $request)
    {

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

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

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

            $id2= strlen($idLastappro);

            if ($id2==1){

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

            } elseif ($id2==2){

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

            } elseif ($id2==3){

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

            } else {

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

        $i=0;

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

			$qtes =  DB::table('stock_matiere')->where('matiere_id', $approvisions[0 +$i])->get()->count();
			//$nbreencarton =  DB::table('matiere')->where('id', $approvisions[0 +$i])->first()->nbreencarton;
            if ($qtes >0){
			$qtesto =  DB::table('stock_matiere')->where('matiere_id', $approvisions[0 +$i])->orderBydesc('id')->take(1)->first()->apres;
			} else {
				$qtesto = 0;
			}
            DB::table('ligne_appro_matiere')->insert(
                [
                    'appro_matiere_id' => $idLastappro,
					'magasin_id' => $magasin,
                    'fournisseur_id' => $fournisseur,
                    'etat' => "Proforma",
                    'matiere_id' => $approvisions[0 +$i],
                    'qte' => $approvisions[1 +$i] * $approvisions[2 +$i],
                    'nbre_coli' => $approvisions[1 +$i],
                    'contenu' => $approvisions[2 +$i],
                    'pa' => $approvisions[3 +$i],
                    'montligne' => ($approvisions[3 +$i] * $approvisions[1 +$i]),
					'date' => $dateappro,
					'en_stock' => $qtesto,
                    'apres' => $qtesto + ($approvisions[1 +$i] * $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_matiere')->where('appro_matiere_id', $id)->delete();
		
		DB::table('appro_matiere')->where('id', $id)->update(
                [
                    'fournisseur_id' => $fournisseur,
                    'magasin_id' => $magasin,
                    'date_appro' => $dateappro,
                    'etat' => "Proforma",
                   
                ]
            );
			$idLastappro = DB::table('appro_matiere')->where('id', $id)->first()->id;

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

            $qtes =  DB::table('stock_matiere')->where('matiere_id', $approvisions[0 +$i])->get()->count();
            if ($qtes >0){
			$qtesto =  DB::table('stock_matiere')->where('matiere_id', $approvisions[0 +$i])->orderBydesc('id')->take(1)->first()->apres;
			} else {
				$qtesto = 0;
			}
			$nbreencarton =  DB::table('matiere')->where('matiere_id', $approvisions[0 +$i])->first()->nbreencarton;

            DB::table('ligne_appro_matiere')->insert(
                [
                    'appro_matiere_id' => $idLastappro,
					'magasin_id' => $magasin,
                    'fournisseur_id' => $idLastappro,
                    'etat' => "Proforma",
                    'matiere_id' => $approvisions[0 +$i],
                    'qte' => ($approvisions[1 +$i] * $nbreencarton),
                    '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');
		if ($nature== "Ajout de solde"){
			$solde = DB::table('caisse_depense')->where('magasin_id', session('user')->magasin_id)->get()->count();
				if ($solde > 0){
					$solde_final = DB::table('caisse_depense')->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(1)->first()->solde_final;
					$ss = $solde_final + $montant;
				}else{
					$solde_final = 0;
					$ss = $montant;
				}
				DB::table('caisse_depense')->insert(
                [
                    'date' => $today,
                    'nature' => 'Appro',
                    'libelle' => 'Appro',
                    'montant' => $montant,
                    'solde_initial' => $solde_final,
                    'solde_final' => $ss,
					'note' => $note,
					'user_id' => session('user')->id,
					'magasin_id' => session('user')->magasin_id,
                ]
            );		
		} elseif ($nature== "Appro caisse recette"){
			$sold = DB::table('solde')->get()->count();
				if ($sold > 0){
					$solde_final = DB::table('solde')->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(1)->first()->solde;
					$ss = $solde_final + $montant;
				}else{
					$solde_final = 0;
					$ss = $montant;
				}
				DB::table('solde')->insert(
                [
                    'date' => $today,
                    'nature' => 'Appro',
                    'libelle' => 'Appro',
                    'montant' => $montant,
                    'solde_initial' => $solde_final,
                    'solde' => $ss,
					'notes' => $note,
					'user_id' => session('user')->id,
					'magasin_id' => session('user')->magasin_id,
                ]
            );		
		}

		else {
			
			$fournisseur=request('fournisseur');
			$nom=DB::table('fournisseur')->where('id', $fournisseur)->first()->nom;
			   
			 if( $montant > "100000" ){
				 
				$sold = DB::table('banque')->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->get()->count();
				if ($sold>0){
					$solde_final = DB::table('banque')->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(1)->first()->solde;
					if ($montant > $solde_final){
						$message = [
						"title" => 'Erreur',
						"type" => 'error',
						"response" => 'Le solde de la banque est insuffisant pour réaliser cette opération',
						];
						return $message;
					} else {
					$ss = $solde_final - $montant;
				   
		            DB::table('banque')->insert(
                   [
                    'date' => $today,
                    'nature' => 'Décaissement',
                    'libelle' => 'Paiement fournisseur '.$nom,
                    'montant' => $montant,
                    'solde_initial' => $solde_final,
                    'solde' => $ss,
                    'notes' => $note,
					'four_id' => $fournisseur,
					'user_id' => session('user')->id,
					'magasin_id' => session('user')->magasin_id,
                ]
                      );
				}} else{
					$message = [
                "title" => 'Erreur',
                "type" => 'error',
                "response" => 'La banque est vide, veuillez l\'approvisionner s\'il vous plaît ! .',
                ];
                return $message;
				}
				
			 } else {
				 
				 $solde = DB::table('caisse_depense')->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->get()->count();
				 if ($solde > 0){
					$solde_final = DB::table('caisse_depense')->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(1)->first()->solde_final;
				 if ($montant > $solde_final ){
						$message = [
							"title" => 'Erreur',
							"type" => 'error',
							"response" => 'Le solde de la caisse dépense est insuffisant pour réaliser cette opération !',
						];
						return $message;
				 } else { 
					 $ss = $solde_final - $montant;
		              DB::table('caisse_depense')->insert(
						[
							'date' => $today,
							'nature' => 'Décaissement',
							'libelle' => 'Paiement fournisseur '.$nom,
							'montant' => $montant,
							'solde_initial' => $solde_final,
							'solde_final' => $ss,
							'note' => $note,
							'four_id' => $fournisseur,
							'user_id' => session('user')->id,
							'magasin_id' => session('user')->magasin_id,
						]
					   ); 
				 }
				  
				} else {
							$message = [
							"title" => 'Erreur',
							"type" => 'error',
							"response" => 'La caisse dépense est vide, veuillez l\'approvisionner !',
						];
						return $message;
					}
				 
				 
			 }
		}
		$message = [
                "title" => 'success',
                "type" => 'success',
                "response" => 'Enregistrement succès !',
            ];
            return $message;
			 
    }
	public function voir(){
      
        if(session('user')== null) {
            return redirect('/');
        }
		
		$fou= DB::table('fournisseur')->orderBy('nom')->get();
		
		return view('solde/nouveau',[
		
		'fou' => $fou,

	]);
	}
	public function achatfou($id){
      
        if(session('user')== null) {
            return redirect('/');
        }
		$appro= DB::table('appro_matiere')->where('fournisseur_id',$id)->where('etat','Validée')->get();
		$total= DB::table('appro_matiere')->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_matiere')->where('appro_matiere_id', $id)->delete();

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

        return redirect()->route('appro-matiere')->with('status', 'Suppression effectuée avec succes');
      

    }

}
