<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Classes\ChiffreEnLettre;
use DB;
use PDF;

class VenteController extends Controller
{

	function VoirSuppressionvente ($id) {

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

            'ven' => $ven,
        ];
    }

    function supprimervente () {
        $id=request('id');
		DB::table('ligne_vente')->where('vente_id', $id)->delete();
		DB::table('ligne_taxe')->where('vente_id', $id)->delete();
		DB::table('vente')->where('id', $id)->delete();
        return redirect()->route('vente-code')->with('status', 'Suppression effectuée avec succès');
    }


	function VoirSuppressionversgerant ($id) {

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

            'vers' => $vers,
        ];
    }

    function supprimerversgerant () {

		$id=request('id');

		$montvers = DB::table('versement_gerant')->where('id', $id)->first()->mont_verse;

	   
		$lastsoldeid = DB::table('banque')->get()->last()->id;

		$lastmontsolde = DB::table('banque')->get()->last()->solde;

		$lastmontsoldeini = DB::table('banque')->get()->last()->solde_initial;

		

		DB::table('banque')->where('id', $lastsoldeid)->update(
			[
				'solde' => ( $lastmontsolde - $montvers ),
				'solde_initial' => ( $lastmontsoldeini - $montvers ),

			]
		);

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


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

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

	public function validerversgerant()
	{
        if(session('user')== null) {
            return redirect('/');
        }
		$versement=DB::table('versement_gerant')->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->get();
		return view('vente/valider_versement_gerant', [
			'versement'=> $versement,
		]);
	}


	function VoirSuppressionvers ($id) {

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

            'vers' => $vers,
        ];
    }

    function supprimervers () {

		$id=request('id');
		
		$idclo = DB::table('versement_caisier')->where('id', $id)->first()->clo_id;

		$montvers = DB::table('versement_caisier')->where('id', $id)->first()->mont_verse;


        DB::table('cloture')->where('id', $idclo)->update(
					[
						'etat' => "Versement non effectué",

					]
				);

	   
		$lastsoldeid = DB::table('solde')->get()->last()->id;

		$lastmontsolde = DB::table('solde')->get()->last()->solde;

		$lastmontsoldeini = DB::table('solde')->get()->last()->solde_initial;

		

		DB::table('solde')->where('id', $lastsoldeid)->update(
			[
				'solde' => ( $lastmontsolde - $montvers ),
				'solde_initial' => ( $lastmontsoldeini - $montvers ),

			]
		);

		DB::table('solde')->where('cloture_id', $idclo)->delete();

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

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

        return redirect()->route('liste-des-versements')->with('status', 'Suppression effectuée avec succes');
	}
	

	function enregistrerversgerant (Request $request){

		$montvers= request("montvers");
		$numbord= request("numbord");
        $datevers= implode('-', array_reverse(explode('/', request('datevers'))));
		
		$heure = date('H:i');
		$today = date('Y-m-d');

		$veri = DB::table('versement_gerant')->where('num_bordereau', $numbord)->where('magasin_id', session('user')->magasin_id)->first();
		     
		if($veri){
			$message = [
				"title" => 'Error',
				"type" => 'error',
				"response" => 'Cet enregistrement existe déjà !',
			];

			return $message;

		}else{
	
				DB::table('versement_gerant')->insert(
	
					[   
						'mont_verse' => $montvers,
						'num_bordereau' => $numbord,
						'date' => $datevers,
						'user_id' => session('user')->id,
						'magasin_id' => session('user')->magasin_id,
					]
				);
				
	
				$lasteversid = DB::table('versement_gerant')->get()->last()->id;

				$lastemont = DB::table('versement_gerant')->get()->last()->mont_verse;
	
				$lastedate = DB::table('versement_gerant')->get()->last()->date;
			
				
				//VERIFICATION ET RECUPERATION DU SOLDE DE LA CAISSE RECETTE
				$so = DB::table('solde')->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(1)->first()->solde;
				$sss = $so - $montvers;
						
				DB::table('solde')->insert(
						[
							'libelle' => 'Décaissement pour versement à la banque',
							'montant' => $montvers,
							'nature' => 'Décaissement pour versement à la banque',
							'date' => $today,
							'solde' => $sss,
							'solde_initial' => $so,
							'user_id' => session('user')->id,
							'magasin_id' => session('user')->magasin_id,
						]
					);
				
				//VERIFICATION ET RECUPERATION DU SOLDE DE LA BANQUE
				$solde = DB::table('banque')->where('magasin_id', session('user')->magasin_id)->get()->count();
					if ($solde > 0){
						$soldef = DB::table('banque')->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(1)->first()->solde;
						$ss = $soldef + $lastemont;
					}else{
						$soldef = 0;
						$ss = 0 + $lastemont;
					}
				//FIN VERIFICATION DE LA BANQUE
					
					DB::table('banque')->insert(
						[
							'libelle' => 'Dépôt des versement des ventes à la banque',
							'montant' => $lastemont,
							'nature' => 'Dépôt',
							'date' => $lastedate,
							'solde' => $ss,
							'solde_initial' => $soldef,
							'vers_id' => $lasteversid,
							'user_id' => session('user')->id,
							'magasin_id' => session('user')->magasin_id,
		
						]
					);
		
				
						$message = [
							"title" => 'success',
							"type" => 'success',
							"response" => 'Enregistrement effectué avec succès !',
						];
				
						return $message; 

		}

	}

	function enregistrervers (Request $request, $id){

		$montavers= request("montavers");
        $datevers= implode('-', array_reverse(explode('/', request('datevers'))));
		$notes= request("notes");
		$heure = date('H:i');
		$verse=collect(request('verse'))->chunk(2);
		$datevente = DB::table('cloture')->where('id', $id)->first()->date;
		$today = date('Y-m-d');
		$veri = DB::table('versement_caisier')->where('mont_a_verser', $montavers)->where('date', $datevers)->where('clo_id', $id)->first();
		     
		if($veri){
			$message = [
				"title" => 'Error',
				"type" => 'error',
				"response" => 'Cet enregistrement existe déjà !',
			];

			return $message;

		}else{
	
				DB::table('versement_caisier')->insert(
	
					[   
						'mont_a_verser' => $montavers,
						'notes' => $notes,
						'date' => $datevers,
						'clo_id' => $id,
						'user_id' => session('user')->id,
						'magasin_id' => session('user')->magasin_id,
					]
				);
				
				$lastid = DB::table('versement_caisier')->get()->last()->id;

				$lastemontavers = DB::table('versement_caisier')->get()->last()->mont_a_verser;

				$i=0;

                foreach ($verse as $key=> $verses){
		
					DB::table('ligne_versement')->insert(
						[
							'date' => $today,
							'versement_id' => $lastid,
							'billet' => $verses[0 +$i],
							'nbre' => $verses[1 +$i],
							'montligne' => ($verses[0 +$i] * $verses[1 +$i]) ,
							'user_id' => session('user')->id,
							'magasin_id' => session('user')->magasin_id,
						]
					);
		
					$i += count($verses->toArray());
		
				}

				$sommontligne =  DB::table('ligne_versement')->where('versement_id', $lastid)->get()->sum('montligne');

				DB::table('versement_caisier')->where('id', $lastid)->update(
                    [
						'ecart' => ( $sommontligne - $lastemontavers ),
						'mont_verse' => $sommontligne,
                    ]
                );
				
				$lastedate = DB::table('versement_caisier')->get()->last()->date;

				$lastecart = DB::table('versement_caisier')->get()->last()->ecart;
		
				if($lastecart == "0"){
		
					DB::table('cloture')->where('id', $id)->update(
						[
							'etat' => "Versement effectué",
							'heure_versement' => $heure,
							'date_versement' => $lastedate,
							'user_id_validation' => session('user')->id,
						]
					);
				}else{
		
					DB::table('cloture')->where('id', $id)->update(
						[
							//'etat' => "Versement effectué avec écart" ,
							'etat' => "Versement effectué" ,
							'heure_versement' => $heure,
							'date_versement' => $lastedate,
							'user_id_validation' => session('user')->id,
						]
					);
				}

				$lastemont = DB::table('versement_caisier')->get()->last()->mont_verse;
				$magasin_id = DB::table('versement_caisier')->get()->last()->magasin_id;
			
				$solde = DB::table('solde')->where('magasin_id', $magasin_id)->get()->count();
				$soldeg = DB::table('solde')->get()->count();
				if ($soldeg > 0){
					$soldeg1 = DB::table('solde')->orderBydesc('id')->take(1)->first()->solde_general;
				}else{
					$soldeg1 = 0;
				}
					if ($solde > 0){
						$soldef = DB::table('solde')->where('magasin_id', $magasin_id)->orderBydesc('id')->take(1)->first()->solde;
						$ss = $soldef + $lastemont;
						$ssg = $soldeg1 + $lastemont;
					}else{
						$soldef = 0;
						$ss = 0 + $lastemont;
						$ssg = $soldeg1 + $lastemont;
					}
					$nom_mag = DB::table('magasin')->where('id', $magasin_id)->first()->nom;
					DB::table('solde')->insert(
						[
							'libelle' => 'Versement ventes du '.$datevente.' /Magasin:'.$nom_mag,
							'montant' => $lastemont,
							'nature' => 'Recette',
							'date' => $lastedate,
							'solde' => $ss,
							'solde_initial' => $soldef,
							'cloture_id' => $id,
							'magasin_id' => $magasin_id,
							'solde_general' => $ssg,
							'user_id' => session('user')->id,
		
						]
					);
		
						$message = [
							"title" => 'success',
							"type" => 'success',
							"response" => 'Enregistrement effectué avec succès !',
						];
				
						return $message; 
		}

	}
	
	public function listevers()
	{
        if(session('user')== null) {
            return redirect('/');
		}
		if (session('user')->roles=="Admin"){
			$versement=DB::table('versement_caisier')->orderBydesc('id')->get();
			$averser = DB::table('versement_caisier')->get()->sum('mont_a_verser');
			$montverse = DB::table('versement_caisier')->get()->sum('mont_verse');
			$ecart = DB::table('versement_caisier')->get()->sum('ecart');
		} else {
		$versement=DB::table('versement_caisier')->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->get();
		$averser = DB::table('versement_caisier')->where('magasin_id', session('user')->magasin_id)->get()->sum('mont_a_verser');
		$montverse = DB::table('versement_caisier')->where('magasin_id', session('user')->magasin_id)->get()->sum('mont_verse');
		$ecart = DB::table('versement_caisier')->where('magasin_id', session('user')->magasin_id)->get()->sum('ecart');
		}
		$magasin=DB::table('magasin')->get();
		return view('vente/liste_versement', [

			'versement'=> $versement,
			'averser'=> $averser,
			'montverse'=> $montverse,
			'ecart'=> $ecart,
			'magasin'=> $magasin,
		]);
	}
	public function vpm()
	{
        if(session('user')== null) {
            return redirect('/');
		}
		$date_debut = request('date_debut');
		$magasin = request('magasin');
        $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(['magasin'=> $magasin]);
		
		if($date_fin > $date_debut || $date_fin == $date_debut){
		if ($magasin==0){
			$versement=DB::table('versement_caisier')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
			$averser = DB::table('versement_caisier')->whereBetween('date', [$date_debut,$date_fin])->get()->sum('mont_a_verser');
			$montverse = DB::table('versement_caisier')->whereBetween('date', [$date_debut,$date_fin])->get()->sum('mont_verse');
			$ecart = DB::table('versement_caisier')->whereBetween('date', [$date_debut,$date_fin])->get()->sum('ecart');
		} else {
			$versement=DB::table('versement_caisier')->where('magasin_id', $magasin)->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
			$averser = DB::table('versement_caisier')->where('magasin_id', $magasin)->whereBetween('date', [$date_debut,$date_fin])->get()->sum('mont_a_verser');
			$montverse = DB::table('versement_caisier')->where('magasin_id', $magasin)->whereBetween('date', [$date_debut,$date_fin])->get()->sum('mont_verse');
			$ecart = DB::table('versement_caisier')->where('magasin_id', $magasin)->whereBetween('date', [$date_debut,$date_fin])->get()->sum('ecart');
		}
		$magasin1=DB::table('magasin')->get();
		return view('vente/liste_versement_rech', [

			'versement'=> $versement,
			'averser'=> $averser,
			'montverse'=> $montverse,
			'ecart'=> $ecart,
			'magasin1'=> $magasin1,
			'magasin'=> $magasin,
			'date_debut'=> $date_debut,
			'date_fin'=> $date_fin,
		]);
	} else {
		return redirect()->route('liste_versement')->with('error', 'La date de début doit être suppérieure à la date finale sélectionné');
	}
	}

	public function validervers($id)
	{
        if(session('user')== null) {
            return redirect('/');
        }

		$cloture=DB::table('cloture')->where('id',$id)->first();

		$versement=DB::table('versement_caisier')->orderBydesc('id')->get();
		
		return view('vente/valider_versement', [

			'cloture'=> $cloture,
			'versement'=> $versement,
		]);
	}


	public function consulter($id)
	{
        if(session('user')== null) {
            return redirect('/');
        }

		$detail=DB::table('ligne_vente')->where('vente_id',$id)->get();
		$totqte = DB::table('ligne_vente')->where('vente_id',$id)->get()->sum('qte');
		$totml = DB::table('ligne_vente')->where('vente_id',$id)->get()->sum('montligne');
		return view('vente/detail', [
			'detail'=> $detail,
			'totqte'=> $totqte,
			'totml'=> $totml,
		]);
	}

	function voirvalider ($id) {

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

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

        $vente= DB::table('vente')->where('id',$id)->first();
        return [
            'vent' => $vente,
        ];
	}

	function voirsuppresion ($id) {

        $detailvente= DB::table('ligne_vente')->where('id',$id)->first();
        return [
            'detailvente' => $detailvente,
        ];
	}


	function supprimerdetail () {

		$id=request('id');
		
		$idvente = DB::table('ligne_vente')->where('id', $id)->first()->vente_id;
		$total_taux = DB::table('vente')->where('id', $idvente)->first()->total_taux;

        DB::table('ligne_vente')->where('id', $id)->delete();
        DB::table('ligne_taxe')->where('vente_id', $idvente)->delete();
		
		$verif  = DB::table('ligne_vente')->where('vente_id', $idvente)->get()->count();
		if ($verif > 0){
			$mht = DB::table('ligne_vente')->where('vente_id', $idvente)->get()->sum('montligne');
			$rem2 = DB::table('vente')->where('id', $idvente)->first()->remise;
			$mtremise = $rem2;
			$mht1 = $mht - $mtremise;
			DB::table('vente')->where('id', $idvente)->update(
						[
							'montant_ht' => $mht,
							'remise' => $rem2,
							'montant_remise' => $mtremise,
							'net_com' => $mht1,
						]
					);
					
			//$tau = DB::table('taxes')->get();
			$nc = DB::table('vente')->where('id', $idvente)->first()->net_com;
			/*$today = date('Y-m-d'); 
			foreach($tau as $taux){
				DB::table('ligne_taxe')->insert(
						[
							'vente_id' => $idvente,
							'taux' => $taux->taux,
							'montligne' => $nc * $taux->taux,
						]
					);
			}
			$sumtaux = DB::table('ligne_taxe')->where('vente_id', $idvente)->get()->sum('montligne');
			$ttc = $sumtaux + $nc;*/
			if ($total_taux > 0){
			$tau = DB::table('taxes')->get();
				foreach($tau as $taux){
				DB::table('ligne_taxe')->insert(
						[
							'vente_id' => $idvente,
							'taux' => $taux->taux,
							'montligne' => $nc * $taux->taux,
						]
					);
				}
				$sumtaux = DB::table('ligne_taxe')->where('vente_id', $idvente)->get()->sum('montligne');
				$ttc = $sumtaux + $nc;
			} else {
				$sumtaux = 0;
				$ttc = $nc;
			}
			DB::table('vente')->where('id', $idvente)->update(
						[
							'total_taux' => $sumtaux,
							'montant' => $ttc,
						]
					);
		} else {
			DB::table('vente')->where('id', $idvente)->delete();
		}
        return redirect()->route('ligne-vente', ['id' => $idvente])->with('status', 'Suppression effectuée avec succes');
    }

	
	function valider () {

		$id=request('id');	
		$montantr=request('montantr');	
		$smt = DB::table('ligne_vente')->where('vente_id', $id)->get()->sum('montligne');
		$smt = DB::table('vente')->where('id', $id)->first()->montant;
		if ($smt > $montantr){
			return redirect()->route('vente-code')->with('error', 'Facture non validée car le montant donné par le client est inférieure au solde de la facture !');
		} else {
		$relica = $montantr - $smt;
		DB::table('vente')->where('id', $id)->update(
			[
				'etat' => "Validée",
				'montant_donne' => $montantr,
				'relicat' => $relica,
			]
		);
		DB::table('ligne_vente')->where('vente_id', $id)->update(
			[
				'etat' => "Validée",
			]
		);

		$vo = DB::table('ligne_vente')->where('vente_id', $id)->where('etat','Validée')->get();

		$today = DB::table('vente')->where('id', $id)->first()->date; 
        

		foreach($vo as $vos){
					
					$sg = DB::table('produit_vendable')->where('id', $vos->produit_id)->first()->stock_general;
					$qtestoc = DB::table('stock_magasin')->where('produit_id', $vos->produit_id)->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->get()->count();
					if ($qtestoc > 0){
					    $qtesto = DB::table('stock_magasin')->where('produit_id', $vos->produit_id)->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(1)->first()->apres;
					} else {
					    $qtesto = 0;
					}
					$qteval = $vos->qte;
		
					DB::table('produit_vendable')->where('id', $vos->produit_id)->update(
						[
							'stock_general' => ($sg - $qteval),
						]
					);
					DB::table('stock_magasin')->insert(
							[
								'date' => $today,
								'produit_id' => $vos->produit_id,
								'qte' => $qteval,
								'type_operation' => 'Vente',
								'en_stock' => $qtesto,
								'apres' => ($qtesto - $qteval),
								'stock_general' => ($sg - $qteval),
								'magasin_id' => session('user')->magasin_id,
								'user_id' => session('user')->id,
								'vente_id' => $id,
							]
						);
						//BENEF
						/*$tmontligne = DB::table('stock_magasin')->where('produit_id', $vos->produit_id)->whereIn('type_operation',['Inventaire','TransfertRecu','Production'])->where('etat', 'Validée')->get()->sum('montligne');
						$tqte = DB::table('stock_magasin')->where('produit_id', $vos->produit_id)->whereIn('type_operation',['Inventaire','TransfertRecu','Production'])->where('etat', 'Validée')->get()->sum('qte');
						if ($tqte >0){
						$pru = $tmontligne/$tqte;
						} else {
						    	$pru = 0;
						}*/
						$pru = DB::table('produit_vendable')->where('id', $vos->produit_id)->first()->pr;
						$pv = DB::table('ligne_vente')->where('produit_id', $vos->produit_id)->where('vente_id', $id)->first()->pv;
						//$remise = DB::table('ligne_vente')->where('produit_id', $vos->produit_id)->where('vente_id', $id)->first()->remise;
						$benef = ($pv - $pru) * $qteval;
						DB::table('ligne_vente')->where('vente_id', $id)->where('produit_id', $vos->produit_id)->update(
							[
								'benef' => $benef,
							]
						);
						$sv = DB::table('produit_vendable')->where('id',  $vos->produit_id)->first()->totvendu;
						DB::table('produit_vendable')->where('id',  $vos->produit_id)->update(
							[
								'totvendu' => $sv + $qteval,
							]
						);
			}
			$vt = DB::table('vente')->where('id', $id)->first();
						DB::table('solde')->insert(
							[
								'date' => $vt->date,
								'nature' => 'Vente',
								'montant' => $vt->montant,
								'vente_id' => $vt->id,
								'user_id' => session('user')->id,
							]
						);
			return redirect()->route('vente-code')->with('status', 'Vente validée avec succès !');
		//return redirect()->route('factureVente',['id'=>$id]);
		}
	}
	
	//VALIDER 2
	function valider2 () {

		$id=request('id');	

		$numtick = DB::table('vente')->where('id', $id)->first()->num_ticket;

		if($numtick){

			$somm = DB::table('vente')->where('id', $id)->first()->montant;
			
			$sommdu = DB::table('ligne_vente')->where('vente_id', $id)->get()->sum('montligne');

            if( $somm == 0){

				DB::table('vente')->where('id', $id)->update(
					[
						'etat' => "Validée",
					]
				);
				DB::table('ligne_vente')->where('vente_id', $id)->update(
					[
						'etat' => "Validée",
					]
				);
				$ligneticket = DB::table('ligne_vente_ticket')->where('ref', $numtick)->first()->id;
				DB::table('ligne_vente_ticket')->where('id', $ligneticket)->update(
					[
						'etat' => "Utilisé",
					]
				);
	
			$vo = DB::table('ligne_vente')->where('vente_id', $id)->where('etat','Validée')->get();

			$today = date('Y-m-d'); 

			foreach($vo as $vos){
				
				

				$idproduit = $vos->produitvendable_id;

				$idcat = DB::table('produit_vendable_fini')->where('id', $vos->produit_id)->first()->cat_id;

				if( $idcat =="4" ){

					$qtesto = DB::table('produit_vendable_fini')->where('id', $vos->produit_id)->first()->stock_gene;

					$qtestomag = DB::table('produit_vendable')->where('id', $idproduit)->first()->stock_general;
	
					$qteval = $vos->qte;
		
					DB::table('produit_vendable_fini')->where('id', $vos->produit_id)->update(
						[
							'stock_gene' => ($qtesto - $qteval),
						]
					);
	
					DB::table('stock_resto')->insert(
							[
								'date' => $today,
								'produit_id' => $vos->produit_id,
								'nbre' => $qteval,
								'type_operation' => 'Vente',
								'en_stock' => $qtesto,
								'apres' => ($qtesto - $qteval),
								'pv_id' => $idproduit,
							]
						);

				}else{

					$qtesto = DB::table('produit_vendable_fini')->where('id', $vos->produit_id)->first()->stock_gene;

					$qteval = $vos->qte;
		
					DB::table('produit_vendable_fini')->where('id', $vos->produit_id)->update(
						[
							'stock_gene' => ($qtesto - $qteval),
						]
					);
					DB::table('stock_resto')->insert(
							[
								'date' => $today,
								'produit_id' => $vos->produit_id,
								'nbre' => $qteval,
								'type_operation' => 'Vente',
								'en_stock' => $qtesto,
								'apres' => ($qtesto - $qteval),
								'pv_id' => $idproduit,
							]
						);

				}
				
			}
		   
			return redirect()->route('toutes-les-ventes')->with('status', 'Vente validée avec succès !');

			}else{

             return redirect()->route('toutes-les-ventes')->with('error', 'Le montant de cette vente ne peut pas dépasser la somme de la subvention et du ticket');

			}


		}else{

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

		$vo = DB::table('ligne_vente')->where('vente_id', $id)->where('etat','Validée')->get();

		$today = date('Y-m-d'); 


		foreach($vo as $vos){

				$idproduit = $vos->produitvendable_id;

				$idcat = DB::table('produit_vendable_fini')->where('id', $vos->produit_id)->first()->cat_id;

				if( $idcat =="4" ){

					$qtesto = DB::table('produit_vendable_fini')->where('id', $vos->produit_id)->first()->stock_gene;

					$qtestomag = DB::table('produit_vendable')->where('id', $idproduit)->first()->stock_general;
	
					$qteval = $vos->qte;
		
					DB::table('produit_vendable_fini')->where('id', $vos->produit_id)->update(
						[
							'stock_gene' => ($qtesto - $qteval),
						]
					);
					DB::table('stock_resto')->insert(
							[
								'date' => $today,
								'produit_id' => $vos->produit_id,
								'nbre' => $qteval,
								'type_operation' => 'Vente',
								'en_stock' => $qtesto,
								'apres' => ($qtesto - $qteval),
								'pv_id' => $idproduit,
							]
						);

				}else{

					$qtesto = DB::table('produit_vendable_fini')->where('id', $vos->produit_id)->first()->stock_gene;

					$qteval = $vos->qte;
		
					DB::table('produit_vendable_fini')->where('id', $vos->produit_id)->update(
						[
							'stock_gene' => ($qtesto - $qteval),
						]
					);
					DB::table('stock_resto')->insert(
							[
								'date' => $today,
								'produit_id' => $vos->produit_id,
								'nbre' => $qteval,
								'type_operation' => 'Vente',
								'en_stock' => $qtesto,
								'apres' => ($qtesto - $qteval),
								'pv_id' => $idproduit,
							]
						);

				}
				
			}
	   
		return redirect()->route('toutes-les-ventes')->with('status', 'Vente validée avec succès !');

		}

        
	}
	
	function annuler () {

        $id=request('id');
		
        DB::table('vente')->where('id', $id)->update(
            [
                'etat' => "Annulée",
            ]
        );
		DB::table('ligne_vente')->where('vente_id', $id)->update(
            [
                'etat' => "Annulée",
            ]
        );
		$numero = DB::table('vente')->where('id', $id)->first()->numero;
		$magasin_id = DB::table('vente')->where('id', $id)->first()->magasin_id;
		$vo = DB::table('ligne_vente')->where('vente_id', $id)->get();
		$today = date('Y-m-d'); 

			foreach($vo as $vos){
				
				$sg = DB::table('produit_vendable')->where('id', $vos->produit_id)->first()->stock_general;
				$qtesto = DB::table('stock_magasin')->where('produit_id', $vos->produit_id)->where('magasin_id', $magasin_id)->orderBydesc('id')->take(1)->first()->apres;
				//$idproduit = DB::table('produit_vendable')->where('id', $vos->produit_id)->first()->pv_id;
				$qteval = $vos->qte;
		
					DB::table('produit_vendable')->where('id', $vos->produit_id)->update(
						[
							'stock_general' => ($qtesto + $qteval),
						]
					);
					DB::table('stock_magasin')->insert(
							[
								'date' => $today,
								'produit_id' => $vos->produit_id,
								'qte' => $qteval,
								'type_operation' => 'Annulationvente',
								'en_stock' => $qtesto,
								'apres' => ($qtesto + $qteval),
								'notes' => "Facture vente ".$numero." annulée.",
								'user_id' => session('user')->id,
								'vente_id' => $id,
								'magasin_id' => session('user')->magasin_id,
								'etat' => 'Annulée',
							]
						);
						DB::table('stock_magasin')->where('vente_id',  $id)->update(
							[
								'etat' => 'Annulée',
							]
						);
						$sv = DB::table('produit_vendable')->where('id',  $vos->produit_id)->first()->totvendu;
						DB::table('produit_vendable')->where('id',  $vos->produit_id)->update(
							[
								'totvendu' => $sv - $qteval,
							]
						);
				
	}
                    //	$vt = DB::table('vente')->where('id', $id)->first();
						DB::table('solde')->where('vente_id',$id)->update(
							[
								'etat' => 'Annulée',
							]
						);
	return redirect()->route('toutes-les-ventes')->with('status', 'Facture annulée avec succes');
	}
		
		function voirsup ($id) {

        $ventes= DB::table('vente')->where('id',$id)->first();
        return [
            'ventes' => $ventes,
        ];
	}
	function sup () {

        $id=request('id');

        $vo = DB::table('ligne_vente')->where('vente_id', $id)->where('etat','Proforma')->delete();
        $vo2 = DB::table('vente')->where('id', $id)->delete();

        return redirect()->route('nouvelleVente')->with('status', 'Facture supprimée avec succès');
    }

    public function vente(){
		
        if(session('user')== null) {
            return redirect('/');
        }
		
		$produit=DB::table('produit_vendable')->orderby('designation','asc')->get();
		$client=DB::table('client')->take(1)->get();
		$remise=DB::table('remise')->where('magasin_id', session('user')->magasin_id)->where('etat', 'Actif')->orderbydesc('id')->get();
		$categorie=DB::table('categorie')->get();
		if (session('user')->roles=="Caissier"){
		$ventes = DB::table('vente')->where('etat2', 'En cours')->where('user_id', session('user')->id)->orderBydesc('id')->take(50)->get();
		}elseif (session('user')->roles=="Validateur" || session('user')->roles=="Gérant"){
		$ventes = DB::table('vente')->where('etat2', 'En cours')->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(50)->get(); 
		}else{
		 $ventes = DB::table('vente')->where('etat2', 'En cours')->orderBydesc('id')->take(50)->get();    
		}
		return view('vente/nouveau', [
			'produit'=> $produit,
			'ventes'=> $ventes,
			'client'=> $client,
			'cat'=> $categorie,
			'remise'=> $remise,
		]);
	}
	//Get compte Where compte
	function get_product($search)
	{

		$compte = DB::table('produit_vendable')->where('designation','like','%'.$search)
						->get();
		return $compte;
	}
	public function ventecode(){
		
        if(session('user')== null) {
            return redirect('/');
        }
		
		$produit=DB::table('produit_vendable')->orderby('designation','asc')->get();
		//$client=DB::table('client')->take(1)->get();
		//$remise=DB::table('remise')->where('magasin_id', session('user')->magasin_id)->where('etat', 'Actif')->orderbydesc('id')->get();
		//$categorie=DB::table('categorie')->get();
		$ventes = DB::table('vente')->where('etat2', 'En cours')->orderBydesc('id')->get();
		return view('vente/nouveau2', [
			'produit'=> $produit,
			'ventes'=> $ventes,
			//'client'=> $client,
			//'cat'=> $categorie,
			//'remise'=> $remise,
		]);
	}
	function enregistrer2()
    {

		//$dat = date('d/m/Y');
		$dat=request('datet');
        $hour = date('H:i:s');

		$today = implode('-', array_reverse(explode('/', $dat)));
		$todayyy = date('Y-m-d'); 
		$typevente=request('typevente');
		$rem=request('remise');
		$nomcli=request('nomcli');
		$contact=request('contact');
		$taxes=request('taxes');
		if ($rem==0){
			$remise=0;
		} else{
			$remise= $rem;
		}
		$peps=collect(request('peps'))->chunk(2);
		if ($peps != ""){
		DB::table('vente')->insert(
				[
					'date' => $today,
					'heure' => $hour,
					'type_vente' => $typevente,
					'remise' => $remise,
					'nomcli' => $nomcli,
					'contact' => $contact,
					'user_id' => session('user')->id,
					'magasin_id' => session('user')->magasin_id,
				]
			);

			$idLastvente = DB::table('vente')->get()->last()->id;
			$idLast= strlen($idLastvente);
	
			if ($idLast==1){
				DB::table('vente')->where('id', $idLastvente)->update(
					[
						'numero' => '000'.$idLastvente,
					]
				);
			} elseif ($idLast==2){
		
				DB::table('vente')->where('id', $idLastvente)->update(
					[
						'numero' => '00'.$idLastvente,
					]
				);
			} elseif ($idLast==3){
				DB::table('vente')->where('id', $idLastvente)->update(
					[
						'numero' => '0'.$idLastvente,
					]
				);
			} else {
				DB::table('vente')->where('id', $idLastvente)->update(
					[
						'numero' => $idLastvente,
					]
				);
			}
	
			$i=0;
			
	foreach ($peps as $key=> $pep){
				$pidc =  DB::table('produit_vendable')->where('code', $pep[0 +$i])->get()->count();
				 if ($pidc == 0){
					$message = [
                        "title" => 'Attention',
                        "type" => 'error',
                        "response" => 'Produit inexistant sous ce code : '.$pep[0 +$i],
                    ];
                    return $message;
				} else {
					$pid =  DB::table('produit_vendable')->where('code', $pep[0 +$i])->first()->id;
				}
				
				$desi =  DB::table('produit_vendable')->where('id', $pid)->first()->desi;
				$qtestoc =  DB::table('stock_magasin')->where('produit_id', $pid)->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->get()->count();
                if ($qtestoc == 0){
					DB::table('vente')->where('id', $idLastvente)->delete();
                    DB::table('ligne_vente')->where('vente_id', $idLastvente)->delete();
					$message = [
                        "title" => 'Erreur de stock',
                        "type" => 'error',
                        "response" => 'Aucun stock de '.$desi.' n\'est disponible dans ce dépôt !',
                    ];
                    return $message;
				} else {
				$qtesto =  DB::table('stock_magasin')->where('produit_id', $pid)->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(1)->first()->apres;
				$categorie_id =  DB::table('produit_vendable')->where('id', $pid)->first()->categorie_id;
                if($qtesto < $pep[1 +$i]){
    
                    DB::table('vente')->where('id', $idLastvente)->delete();
                    DB::table('ligne_vente')->where('vente_id', $idLastvente)->delete();
    
                    $message = [
                        "title" => 'Erreur d\'enregistrement',
                        "type" => 'error',
                        "response" => 'Stock '.' '.$desi.' '.'insuffisant ! Stock restant : '.$qtesto,
                    ];
        
                    return $message;
    
                }else{
				
					DB::table('ligne_vente')->insert(
						[
								'vente_id' => $idLastvente,
								'categorie_id' => $categorie_id,
								'produit_id' => $pid,
								'qte' => $pep[1 +$i],
								'pv' => $pep[2 +$i],
								'montligne' => ($pep[1 +$i] * $pep[2 +$i]),
								'date' => $todayyy, 
								'user_id' => session('user')->id,
								'magasin_id' => session('user')->magasin_id,
						]
					);
						$i += count($pep->toArray()); 
				}  
				}
	}
			$mht = DB::table('ligne_vente')->where('vente_id', $idLastvente)->get()->sum('montligne');
			$rem2 = DB::table('vente')->where('id', $idLastvente)->first()->remise;
			$mtremise = $rem2;
			$mht1 = $mht - $mtremise;
			DB::table('vente')->where('id', $idLastvente)->update(
				[
					'montant_ht' => $mht,
					'remise' => $remise,
					'montant_remise' => $mtremise,
					'net_com' => $mht1,
				]
			);
			$nc = DB::table('vente')->where('id', $idLastvente)->first()->net_com;
			if ($taxes == "Oui"){
				$tau = DB::table('taxes')->get();
					foreach($tau as $taux){
					DB::table('ligne_taxe')->insert(
							[
								'vente_id' => $idLastvente,
								'taux' => $taux->taux,
								'montligne' => $nc * $taux->taux,
							]
						);
					}
					$sumtaux = DB::table('ligne_taxe')->where('vente_id', $idLastvente)->get()->sum('montligne');
					$ttc = $sumtaux + $nc;
				} else {
					$sumtaux = 0;
					$ttc = $nc;
				}
			
			
			$today = date('Y-m-d'); 
			
			DB::table('vente')->where('id', $idLastvente)->update(
						[
							'total_taux' => $sumtaux,
							'montant' => $ttc,
						]
					);
			
		}
	$message = [
				"title" => 'success',
				"type" => 'success',
				"response" => 'Opération effectué avec succes !',
			];
	
			return $message;
	}
	//MODIFICATION
	public function listevente(){

		if(session('user')== null) {
            return redirect('/');
        }
		
		$today= date('Y-m-d');
		$ventes=DB::table('vente')->where('etat2','En cours')->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->get();
		$paiecli=DB::table('paiement_client')->where('etat2', 'Non cloturé')->where('magasin_id', session('user')->magasin_id)->get();
		$consignation=DB::table('consignation')->where('etat', 'Validée')->where('etat2', 'En cours')->where('magasin_id', session('user')->magasin_id)->get();
		$count=DB::table('vente')->where('etat2','En cours')->where('magasin_id', session('user')->magasin_id)->get()->count();
		$count2=DB::table('paiement_client')->where('etat2', 'Non cloturé')->where('magasin_id', session('user')->magasin_id)->get()->count();
		$client=DB::table('client')->orderBydesc('id')->get();
		$dep= DB::table('caisse_depense')->where('etat2','En cours')->where('magasin_id',session('user')->magasin_id)->get();
		
		
		return view('vente/liste', [
			'ventes'=> $ventes,
			'dep'=> $dep,
			'consignation'=> $consignation,
			'paiecli'=> $paiecli,
			'client'=> $client,
			'count'=> $count,
			'count2'=> $count2,
		]);
	}
	public function listevente23(){

		if(session('user')== null) {
            return redirect('/');
        }
		if (session('user')->roles=="Admin"){
			$ventes=DB::table('vente')->orderBydesc('id')->take(100)->get();
			$client=DB::table('client')->orderBydesc('id')->get();
			$magasin=DB::table('magasin')->get();
			$total=DB::table('vente')->where('etat', 'Validée')->sum('montant');
		} else {
			$ventes=DB::table('vente')->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(100)->get();
			$client=DB::table('client')->orderBydesc('id')->get();
			$magasin=DB::table('magasin')->where('id', session('user')->magasin_id)->get();
			$total=DB::table('vente')->where('magasin_id', session('user')->magasin_id)->where('etat', 'Validée')->sum('montant');
		}
		/*$ventes=DB::table('vente')->orderBydesc('id')->get();
		$client=DB::table('client')->orderBydesc('id')->get();
		$magasin=DB::table('magasin')->get();
		$total=DB::table('vente')->where('etat', 'Validée')->sum('montant');*/
		return view('vente/toutes-les-ventes', [
			'ventes'=> $ventes,
			'client'=> $client,
			'magasin'=> $magasin,
			'total'=> $total,
		]);
	}
	public function listevente233(){

		if(session('user')== null) {
            return redirect('/');
        }
		
		$date_debut = request('date_debut');
		$magasin = request('magasin');
        $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(['magasin'=> $magasin]);
		
		if($date_fin > $date_debut || $date_fin == $date_debut){
		if ($magasin==0){
		$ventes=DB::table('vente')->where('etat','Validée')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
		$client=DB::table('client')->orderBydesc('id')->get();
		$magasin1=DB::table('magasin')->get();
		$total=DB::table('vente')->where('etat', 'Validée')->whereBetween('date', [$date_debut,$date_fin])->sum('montant');
		$totalcount= "N/A";
		} else {
				$ventes=DB::table('vente')->where('magasin_id', $magasin)->where('etat','Validée')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
				$client=DB::table('client')->orderBydesc('id')->get();
				$magasin1=DB::table('magasin')->where('id', $magasin)->get();
				$total=DB::table('vente')->where('magasin_id', $magasin)->where('etat', 'Validée')->whereBetween('date', [$date_debut,$date_fin])->sum('montant');
				$totalcount=DB::table('vente')->where('magasin_id', $magasin)->where('etat', 'Validée')->whereBetween('date', [$date_debut,$date_fin])->get()->count();
		}
		return view('vente/toutes-les-ventes-rech', [
			'ventes'=> $ventes,
			'client'=> $client,
			'magasin'=> $magasin,
			'magasin1'=> $magasin1,
			'total'=> $total,
			'totalcount'=> $totalcount,
			'date_debut'=> $date_debut,
			'date_fin'=> $date_fin,
		]);
	} else 
		 {
			return redirect()->route('toutes-les-ventes')->with('error', 'La date de fin ne doit pas dépasser la date de début!');
	}}
	public function listevente233PDF(){

		if(session('user')== null) {
            return redirect('/');
        }
		
		$date_debut = session('date_debut');
		$date_fin = session('date_fin');
		$magasin = session('magasin');
		
		if($date_fin > $date_debut || $date_fin == $date_debut){
		if ($magasin==0){
		$ventes=DB::table('vente')->where('etat','Validée')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
		$client=DB::table('client')->orderBydesc('id')->get();
		$magasin1=DB::table('magasin')->get();
		$total=DB::table('vente')->where('etat', 'Validée')->whereBetween('date', [$date_debut,$date_fin])->sum('montant');
		$totalcount= "N/A";
		} else {
				$ventes=DB::table('vente')->where('magasin_id', $magasin)->where('etat','Validée')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
				$client=DB::table('client')->orderBydesc('id')->get();
				$magasin1=DB::table('magasin')->get();
				$total=DB::table('vente')->where('magasin_id', $magasin)->where('etat', 'Validée')->whereBetween('date', [$date_debut,$date_fin])->sum('montant');
				$totalcount=DB::table('vente')->where('magasin_id', $magasin)->where('etat', 'Validée')->whereBetween('date', [$date_debut,$date_fin])->get()->count();
		}
		$pdf = PDF::loadView('vente/toutes-les-ventes-pdf', [
			'ventes'=> $ventes,
			'client'=> $client,
			'magasin'=> $magasin,
			'magasin1'=> $magasin1,
			'total'=> $total,
			'totalcount'=> $totalcount,
			'date_debut'=> $date_debut,
			'date_fin'=> $date_fin,
		]);
		return $pdf->stream();
	}}
	//RECHERCHE VENTE JOURNALIÈRE
	public function rechventePost(){
		
		if(session('user')== null) {
            return redirect('/');
        }

		$date_debut = request('date_debut');
        $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]);
		
		 if($date_fin > $date_debut || $date_fin == $date_debut){
			 
		$ventes=DB::table('vente')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
		$total=DB::table('vente')->whereBetween('date', [$date_debut,$date_fin])->sum('montant');
		//$ventecount=DB::table('vente')->where('etat','Validée')->get()->count();
		//$client=DB::table('client')->orderBydesc('id')->get();
		$magasin=DB::table('magasin')->get();
		//$nbtick=DB::table('vente')->where('client_id', 2)->whereBetween('date', [$date_debut,$date_fin])->get()->count();
		$pdf = PDF::loadView('vente/liste3', [
			'ventes'=> $ventes,
			'magasin'=> $magasin,
			'total'=> $total,
			//'client'=> $client,
			//'nbtick'=> $nbtick,
			'date_debut'=> $date_debut,
			'date_fin'=> $date_fin,
		]);
		return $pdf->stream();
	} else 
			return redirect()->route('liste-des-ventes-de-la-journee')->with('error', 'La date de fin ne doit pas dépasser la date de début!');
	}
	public function rechventePDF(){

		if(session('user')== null) {
            return redirect('/');
        }
		
		$date_debut = session('date_debut');
		$date_fin = session('date_fin');
		
		 if($date_fin > $date_debut || $date_fin == $date_debut){
			 
		$ventes=DB::table('vente')->where('etat','Validée')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
		$total=DB::table('vente')->whereBetween('date', [$date_debut,$date_fin])->sum('montant');
		//$ventecount=DB::table('vente')->where('etat','Validée')->get()->count();
		$client=DB::table('client')->orderBydesc('id')->get();
		$pdf = PDF::loadView('vente/liste33', [
			'ventes'=> $ventes,
			//'ventecount'=> $ventecount,
			'client'=> $client,
			'total'=> $total,
			'date_debut'=> $date_debut,
			'date_fin'=> $date_fin,
		]);
		return $pdf->stream();
	}}
	public function listevente2(){
		
		if(session('user')== null) {
            return redirect('/');
        }
		
		$today= date('Y-m-d');
		$ventes=DB::table('vente')->orderBydesc('id')->get();
		$total=DB::table('vente')->sum('montant');
		//$ventecount=DB::table('vente')->where('etat','Validée')->get()->count();
		//$client=DB::table('client')->orderBydesc('id')->get();
		$magasin=DB::table('magasin')->get();
		return view('vente/liste2', [
			'ventes'=> $ventes,
			'magasin'=> $magasin,
			'total'=> $total,
			//'client'=> $client,
		]);
	}
	//PAR REPAS
	public function parrepas(){
		
		if(session('user')== null) {
            return redirect('/');
        }
		
		$today= date('Y-m-d');
		$vb_comptant =DB::table('ligne_vente')->where('categorie_id', 4)->where('client_id', 1)->get()->sum('montligne');
		$repas_comptant=DB::table('ligne_vente')->where('categorie_id', '!=', 4)->where('client_id', 1)->sum('montligne');
		
		$vb_credit =DB::table('ligne_vente_client')->where('categorie_id', 4)->get()->sum('montligne');
		$repas_credit=DB::table('ligne_vente_client')->where('categorie_id', '!=', 4)->sum('montligne');
		
		$vb_personnel =DB::table('ligne_vente')->where('categorie_id', 4)->where('client_id', 2)->get()->sum('montligne');
		$repas_personnel=DB::table('ligne_vente')->where('categorie_id', '!=', 4)->where('client_id', 2)->sum('montligne');
		
		$vticket = DB::table('vente_ticket')->get()->sum('montant'); 
		//$total=DB::table('vente')->sum('montant');
		return view('vente/parrepas', [
			'vb_comptant'=> $vb_comptant,
			'repas_comptant'=> $repas_comptant,
			'vb_credit'=> $vb_credit,
			'repas_credit'=> $repas_credit,
			'vb_personnel'=> $vb_personnel,
			'repas_personnel'=> $repas_personnel,
			'vticket'=> $vticket,
		]);
	}
	public function parrepaspdf(){
		
		if(session('user')== null) {
            return redirect('/');
        }

		$date_debut = request('date_debut');
        $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]);
		
		 if($date_fin > $date_debut || $date_fin == $date_debut){
			 
		$vb_comptant =DB::table('ligne_vente')->where('categorie_id', 4)->where('client_id', 1)->whereBetween('date', [$date_debut,$date_fin])->get()->sum('montligne');
		$repas_comptant=DB::table('ligne_vente')->where('categorie_id', '!=', 4)->where('client_id', 1)->whereBetween('date', [$date_debut,$date_fin])->sum('montligne');
		
		$vb_credit =DB::table('ligne_vente_client')->where('categorie_id', 4)->whereBetween('date', [$date_debut,$date_fin])->get()->sum('montligne');
		$repas_credit=DB::table('ligne_vente_client')->where('categorie_id', '!=', 4)->whereBetween('date', [$date_debut,$date_fin])->sum('montligne');
		
		$vb_personnel =DB::table('ligne_vente')->where('categorie_id', 4)->where('client_id', 2)->whereBetween('date', [$date_debut,$date_fin])->get()->sum('montligne');
		$repas_personnel=DB::table('ligne_vente')->where('categorie_id', '!=', 4)->where('client_id', 2)->whereBetween('date', [$date_debut,$date_fin])->sum('montligne');
		
		$vticket = DB::table('vente_ticket')->whereBetween('date', [$date_debut,$date_fin])->get()->sum('montant'); 
		$pdf = PDF::loadView('vente/parrepaspdf', [
			'vb_comptant'=> $vb_comptant,
			'repas_comptant'=> $repas_comptant,
			'vb_credit'=> $vb_credit,
			'repas_credit'=> $repas_credit,
			'vb_personnel'=> $vb_personnel,
			'repas_personnel'=> $repas_personnel,
			'date_debut'=> $date_debut,
			'date_fin'=> $date_fin,
			'vticket'=> $vticket,
		]);
		return $pdf->stream();
	} else 
			return redirect()->route('parrepas')->with('error', 'La date de fin ne doit pas dépasser la date de début!');
	}
	// FIN PAR REPAS
	public function listeventeannulee(){

		if(session('user')== null) {
            return redirect('/');
        }

		$ventes=DB::table('vente')->where('etat', 'Annulée')->orderBydesc('id')->get();
		$ventecount=DB::table('vente')->where('etat', 'Annulée')->get()->count();
		$client=DB::table('client')->orderBydesc('id')->get();
		return view('liste2', [
			'ventes'=> $ventes,
			'ventecount'=> $ventecount,
			'client'=> $client,
		]);
	}

	function facturevente($id)
    {
		if(session('user')== null) {
            return redirect('/');
		}
		
		$vente = DB::table('vente')->where('id',$id)->first();
		$ligne = DB::table('ligne_vente')->where('vente_id',$id)->get();
		$lignetax = DB::table('ligne_taxe')->where('vente_id',$id)->get();
		$tva = DB::table('ligne_taxe')->where('vente_id',$id)->sum('montligne');
		$ligneM = DB::table('ligne_vente')->where('vente_id',$id)->get()->sum('montligne');
		$total_article = DB::table('ligne_vente')->where('vente_id',$id)->sum('qte');
		$montant = $vente->montant;
		$montant=round($montant,0);
		$montant1 = (new \App\Classes\ChiffreEnLettre)->Conversion($montant);
        
        $pdf = \App::make('dompdf.wrapper');
        $pdf = PDF::loadView('/vente/facture_a5', [

            'ligne' => $ligne,
			'vente' => $vente,
			'ligneM' => $ligneM,
			'lignetax' => $lignetax,
			'montant1' => $montant1,
			'total_article' => $total_article,
			'tva' => $tva,
		])->setPaper('A5', 'portrait');
		
        return $pdf->stream();
    }


	function enregistrer()
    {

		//$dat = date('d/m/Y');
		$dat=request('datet');
        $hour = date('H:i:s');
		$today = implode('-', array_reverse(explode('/', $dat)));
		$todayyy = date('Y-m-d'); 
		$typevente=request('typevente');
		$nomcli=request('nomcli');
		$contact=request('contact');
		$remise=request('remise');
		$taxes=request('taxes');
		
		$peps=collect(request('peps'))->chunk(2);
		if ($peps != ""){
		DB::table('vente')->insert(
				[
					'date' => $today,
					'heure' => $hour,
					'type_vente' => $typevente,
					'nomcli' => $nomcli,
					'contact' => $contact,
					'remise' => $remise,
					'user_id' => session('user')->id,
					'nom_user' => session('user')->nom,
					'magasin_id' => session('user')->magasin_id,
				]
			);

			$idLastvente = DB::table('vente')->get()->last()->id;
			$idLast= strlen($idLastvente);
	
			if ($idLast==1){
				DB::table('vente')->where('id', $idLastvente)->update(
					[
						'numero' => '000'.$idLastvente,
					]
				);
			} elseif ($idLast==2){
		
				DB::table('vente')->where('id', $idLastvente)->update(
					[
						'numero' => '00'.$idLastvente,
					]
				);
			} elseif ($idLast==3){
				DB::table('vente')->where('id', $idLastvente)->update(
					[
						'numero' => '0'.$idLastvente,
					]
				);
			} else {
				DB::table('vente')->where('id', $idLastvente)->update(
					[
						'numero' => $idLastvente,
					]
				);
			}
	
			$i=0;
			
	foreach ($peps as $key=> $pep){
				$desi =  DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->desi;
				$pr = DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->pr;
				$qtestoc =  DB::table('stock_magasin')->where('produit_id', $pep[0 +$i])->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->get()->count();
                if ($qtestoc == 0){
					DB::table('vente')->where('id', $idLastvente)->delete();
                    DB::table('ligne_vente')->where('vente_id', $idLastvente)->delete();
					$message = [
                        "title" => 'Erreur de stock',
                        "type" => 'error',
                        "response" => 'Aucun stock de '.$desi.' n\'est disponible dans votre magasin !',
                    ];
                    return $message;
				} else {
				$qtesto =  DB::table('stock_magasin')->where('produit_id', $pep[0 +$i])->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(1)->first()->apres;
				$categorie_id =  DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->categorie_id;
                if($qtesto < $pep[1 +$i]){
    
                    DB::table('vente')->where('id', $idLastvente)->delete();
                    DB::table('ligne_vente')->where('vente_id', $idLastvente)->delete();
    
                    $message = [
                        "title" => 'Erreur d\'enregistrement',
                        "type" => 'error',
                        "response" => 'Stock '.' '.$desi.' '.'insuffisant ! Stock restant : '.$qtesto,
                    ];
        
                    return $message;
    
                }else{
 
					DB::table('ligne_vente')->insert(
						[
								'vente_id' => $idLastvente,
								'categorie_id' => $categorie_id,
								'produit_id' => $pep[0 +$i],
								'qte' => $pep[1 +$i],
								'pv' => $pep[2 +$i],
								'pr' => $pr,
								'montligne' => ($pep[1 +$i] * $pep[2 +$i]),
								'montlignepr' => ($pep[1 +$i] * $pr),
								'date' => $today, 
								'user_id' => session('user')->id,
								'magasin_id' => session('user')->magasin_id,
						]
					);
						$i += count($pep->toArray()); 
				}  
				}
	}
			$mht = DB::table('ligne_vente')->where('vente_id', $idLastvente)->get()->sum('montligne');
			$mht1 = $mht - $remise;
			DB::table('vente')->where('id', $idLastvente)->update(
						[
							'montant_ht' => $mht,
							'remise' => $remise,
							'montant_remise' => $remise,
							'net_com' => $mht1,
						]
					);
					
			$nc = DB::table('vente')->where('id', $idLastvente)->first()->net_com;
			if ($taxes == "Oui"){
				$tau = DB::table('taxes')->get();
					foreach($tau as $taux){
					DB::table('ligne_taxe')->insert(
							[
								'vente_id' => $idLastvente,
								'taux' => $taux->taux,
								'montligne' => $nc * $taux->taux,
							]
						);
					}
					$sumtaux = DB::table('ligne_taxe')->where('vente_id', $idLastvente)->get()->sum('montligne');
					$ttc = $sumtaux + $nc;
				} else {
					$sumtaux = 0;
					$ttc = $nc;
				}
			DB::table('vente')->where('id', $idLastvente)->update(
						[
							'total_taux' => $sumtaux,
							'montant' => $ttc,
						]
					);
			
		}
	$message = [
				"title" => 'success',
				"type" => 'success',
				"response" => 'Opération effectué avec succes !',
			];
	
			return $message;
	}
	
	function enregistrer_bc()
    {
		$dat=request('datet');
        $hour = date('H:i:s');
		$today = implode('-', array_reverse(explode('/', $dat)));
		$todayyy = date('Y-m-d'); 
		//$typevente=request('typevente');
		$nomcli=request('nomcli');
		$contact=request('contact');
		$remise=request('remise');
		$taxes=request('taxes');
		$peps=request('item');
		if (count($peps) > 0 && $peps != null){
		DB::table('vente')->insert(
				[
					'date' => $today,
					'heure' => $hour,
					'type_vente' => 'Détail',
					'nomcli' => $nomcli,
					'contact' => $contact,
					'remise' => $remise,
					'user_id' => session('user')->id,
					'nom_user' => session('user')->nom,
					'magasin_id' => session('user')->magasin_id,
				]
			);

			$idLastvente = DB::table('vente')->get()->last()->id;
			$idLast= strlen($idLastvente);
	
			if ($idLast==1){
				DB::table('vente')->where('id', $idLastvente)->update(
					[
						'numero' => '000'.$idLastvente,
					]
				);
			} elseif ($idLast==2){
		
				DB::table('vente')->where('id', $idLastvente)->update(
					[
						'numero' => '00'.$idLastvente,
					]
				);
			} elseif ($idLast==3){
				DB::table('vente')->where('id', $idLastvente)->update(
					[
						'numero' => '0'.$idLastvente,
					]
				);
			} else {
				DB::table('vente')->where('id', $idLastvente)->update(
					[
						'numero' => $idLastvente,
					]
				);
			}
	
			$i=0;
			
	foreach ($peps as $key=> $pep){
				$desi =  DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->desi;
				$pr = DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->pr;
				if ($pr > 0){
				    $pr = DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->pr;
				}else{
				    $pr = 0;
				}
				$qtestoc =  DB::table('stock_magasin')->where('produit_id', $pep[0 +$i])->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->get()->count();
                /*if ($qtestoc == 0){
					DB::table('vente')->where('id', $idLastvente)->delete();
                    DB::table('ligne_vente')->where('vente_id', $idLastvente)->delete();
					$message = [
                        "title" => 'Erreur de stock',
                        "type" => 'error',
                        "response" => 'Aucun stock de '.$desi.' n\'est disponible dans votre magasin !',
                    ];
                    return $message;
				} else {*/
				//$qtesto =  DB::table('stock_magasin')->where('produit_id', $pep[0 +$i])->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(1)->first()->apres;
				$categorie_id =  DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->categorie_id;
                /*if($qtesto < $pep[1 +$i]){
    
                    DB::table('vente')->where('id', $idLastvente)->delete();
                    DB::table('ligne_vente')->where('vente_id', $idLastvente)->delete();
    
                    $message = [
                        "title" => 'Erreur d\'enregistrement',
                        "type" => 'error',
                        "response" => 'Stock '.' '.$desi.' '.'insuffisant ! Stock restant : '.$qtesto,
                    ];
        
                    return $message;
    
                }else{*/
				
					//if ($typevente=="Détail"){//
						$prix =  DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->prix_detail;
					/*} else {
						$prix =  DB::table('produit_vendable')->where('id', $pep[0+$i])->first()->prix_gros;
					}  */ 
					DB::table('ligne_vente')->insert(
						[
								'vente_id' => $idLastvente,
								'categorie_id' => $categorie_id,
								'produit_id' => $pep[0 +$i],
								'qte' => $pep[1 +$i],
								'pv' => $pep[2 +$i],
								'pr' => $pr,
								'montligne' => ($pep[1 +$i] * $pep[2 +$i]),
								'montlignepr' => ($pep[1 +$i] * $pr),
								'date' => $today, 
								'user_id' => session('user')->id,
								'magasin_id' => session('user')->magasin_id,
						]
					);
				
					$i; 
						
				//}  
				//}
	}
			$mht = DB::table('ligne_vente')->where('vente_id', $idLastvente)->get()->sum('montligne');
			$mht1 = $mht - $remise;
			DB::table('vente')->where('id', $idLastvente)->update(
				[
					'montant_ht' => $mht,
					'remise' => $remise,
					'montant_remise' => $remise,
					'net_com' => $mht1,
				]
			);
					
			$nc = DB::table('vente')->where('id', $idLastvente)->first()->net_com;
			if ($taxes == "Oui"){
				$tau = DB::table('taxes')->get();
					foreach($tau as $taux){
					DB::table('ligne_taxe')->insert(
							[
								'vente_id' => $idLastvente,
								'taux' => $taux->taux,
								'montligne' => $nc * $taux->taux,
							]
						);
					}
					$sumtaux = DB::table('ligne_taxe')->where('vente_id', $idLastvente)->get()->sum('montligne');
					$ttc = $sumtaux + $nc;
				} else {
					$sumtaux = 0;
					$ttc = $nc;
				}
			DB::table('vente')->where('id', $idLastvente)->update(
						[
							'total_taux' => $sumtaux,
							'montant' => $ttc,
						]
					);
			
		}
	/*$message = [
				"title" => 'success',
				"type" => 'success',
				"response" => 'Opération effectué avec succes !',
			];
	
			return $message;*/
			return redirect()->route('vente-code')->with('status', 'Facture enregistrée avec succès !');
	}
    
    //TABLEAU DE BORD
    public function tb()
	{
        if(session('user')== null) {
            return redirect('/');
        }

		$vente= DB::table('vente')->get()->sum('montant');
		$vente2= DB::table('ligne_vente')->where('etat','Validée')->orderBydesc('id')->get();
		$approvisionnement = DB::table('approvisionnement')->get()->sum('montant_appro');
	    $solde = $vente - $approvisionnement;
	    $avenir= DB::table('produit')->get()->sum('avenir');
	    $ben= DB::table('benefice')->get()->sum('montant');
	    

		return view('tableau_de_bord', [
			'vente'=> $vente,
			'vente2'=> $vente2,
			'approvisionnement'=> $approvisionnement,
			'solde'=> $solde,
			'avenir'=> $avenir,
			'ben'=> $ben,
		]);
	}
	//PAIEMENTS CLIENTS
	
	//Paiement
	function pc()
    {

		if(session('user')== null) {
            return redirect('/');
        }

		$paie= DB::table('paiement_hopital')->orderBydesc('id')->get();
	return view('vente/paiement_client', [
		'paie' => $paie,
	]);
    }
	function listev()
    {
		if(session('user')== null) {
            return redirect('/');
        }

		$paie= DB::table('paiement_hopital')->orderBydesc('id')->take(10)->get();
		$total= DB::table('paiement_hopital')->sum('montant');
	return view('vente/liste-des-paiements', [
		'paie' => $paie,
		'total' => $total,
	]);
    }
	function factureph($id)
    {

		if(session('user')== null) {
            return redirect('/');
		}
		
		$paie= DB::table('paiement_hopital')->where('id', $id)->first();
		$pdf = PDF::loadView('vente/facture-paiement-hopital', [
		'paie' => $paie,
	]);
	return $pdf->stream();
    }
	function listevpdf()
    {

		if(session('user')== null) {
            return redirect('/');
		}
		
		$date_debut = session('date_debut');
		$date_fin = session('date_fin');
		$paie= DB::table('paiement_hopital')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
		$total= DB::table('paiement_hopital')->whereBetween('date', [$date_debut,$date_fin])->sum('montant');
		$pdf = PDF::loadView('vente/liste-des-paiements-pdf', [
		'paie' => $paie,
		'total' => $total,
		'date_debut' => $date_debut,
		'date_fin' => $date_fin,
	]);
	return $pdf->stream();
    }
	function rechpaie()
    {

		if(session('user')== null) {
            return redirect('/');
		}
		
		$date_debut = request('date_debut');
        $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]);
		
		 if($date_fin > $date_debut || $date_fin == $date_debut){
	$paie= DB::table('paiement_hopital')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
	$total= DB::table('paiement_hopital')->whereBetween('date', [$date_debut,$date_fin])->sum('montant');
	return view('vente/liste-des-paiements-rech', [
		'paie' => $paie,
		'date_debut' => $date_debut,
		'date_fin' => $date_fin,
		'total' => $total,
	]);
    } else 
		 {
			return redirect()->route('liste-des-paiements')->with('error', 'La date de fin ne doit pas dépasser la date de début!');
}}
	//enreg paimeent
	function enregistrer3(Request $request)
    {
        //$client_id=request('client_id');
        $montant=request('montant');
        $mode=request('mode');
		$note=request('note');
		//$today = date('Y-m-d H:i:s');
        $today2 = date('Y-m-d'); 
		$apayer = DB::table('transaction_hopital')->orderBydesc('id')->take(1)->first()->solde;
		//$apayer = $apayer0 * 500;
		//$client = DB::table('vente')->where('id', $vente_id)->first()->client_id;
		$sommePaiement =  DB::table('paiement_hopital')->get()->sum('montant');
		$total = $sommePaiement + $montant ;
		$reste = $apayer - $montant ;
		
        if( $total >  $apayer ) {
                $message = [
                "title" => 'Erreur',
                "type" => 'error',
                "response" => 'Le montant saisi ne doit pas dépasser le restant à payer :'. ' '. ($apayer - $sommePaiement).' F',
                ];

                return $message;
       } else {
	   if ($mode == "Chèque"){
			DB::table('paiement_hopital')->insert(
                    [
                        'montant' => $montant,
                        'mode' => $mode,
                        'date' => $today2,
                        'note' => $note,
                        'apayer' => $apayer,
                        'reste' => $reste,

                    ]
                );
				$sold = DB::table('banque')->get()->count();
				if ($sold > 0){
					$solde = DB::table('banque')->orderBydesc('id')->take(1)->first()->solde;
					$ss = $solde + $montant;
				}else{
					$solde = 0;
					$ss = 0 + $montant;
				}
                //$client1 = DB::table('client')->where('id', $client_id)->first()->nom;
                DB::table('banque')->insert(
                    [
                        'libelle' => 'Paiement hopital',
                        'montant' => $montant,
                        'nature' => 'Recette',
                        'date' => $today2,
                        'solde' => $ss,
                        'solde_initial' => $solde,

                    ]
                );
				
				$totalcli0 = DB::table('transaction_hopital')->orderBydesc('id')->take(1)->first()->solde;
				$totalcli = $totalcli0;
				$totalcli2 = DB::table('paiement_hopital')->get()->sum('montant');
				$soldo = $totalcli - $montant;
				DB::table('transaction_hopital')->insert(
                    [
                        'date' => $today2,
                        'libelle' => 'Règlement',
                        'montant' => $montant,
						'solde' => $soldo,
						'type' => 'Crédit',
						//'client_id' => $client_id,
                    ]
                );
	   } else {
		   DB::table('paiement_hopital')->insert(
                    [
                        'montant' => $montant,
                        'mode' => $mode,
                        'date' => $today2,
                        'note' => $note,
                        'apayer' => $apayer,
                        'reste' => $reste,

                    ]
                );
				$sold = DB::table('solde')->get()->count();
				if ($sold > 0){
					$solde = DB::table('solde')->orderBydesc('id')->take(1)->first()->solde;
					$ss = $solde + $montant;
				}else{
					$solde = 0;
					$ss = 0 + $montant;
				}
                //$client1 = DB::table('client')->where('id', $client_id)->first()->nom;
                DB::table('solde')->insert(
                    [
                        'libelle' => 'Paiement hopital',
                        'montant' => $montant,
                        'nature' => 'Recette',
                        'date' => $today2,
                        'solde' => $ss,
                        'solde_initial' => $solde,

                    ]
                );
				
				$totalcli0 = DB::table('transaction_hopital')->orderBydesc('id')->take(1)->first()->solde;
				$totalcli = $totalcli0;
				$totalcli2 = DB::table('paiement_hopital')->get()->sum('montant');
				$soldo = $totalcli - $montant;
				DB::table('transaction_hopital')->insert(
                    [
                        'date' => $today2,
                        'libelle' => 'Règlement',
                        'montant' => $montant,
						'solde' => $soldo,
						'type' => 'Crédit',
						//'client_id' => $client_id,
                    ]
                );
	   }
                $message = [
                    "title" => 'success',
                    "type" => 'success',
                    "response" => 'Paiement enregistré avec succes !',
                    //"id" => session('appro_id'),
                ];

                return $message;

       }     
    }
	public function detail($id){

		if(session('user')== null) {
            return redirect('/');
        }

		$paie=DB::table('paiement_client')->where('client_id',$id)->get();
		return view('vente/detailscli', [
			'paie'=> $paie,
		]);
	}
	public function detail2($id){

		if(session('user')== null) {
            return redirect('/');
        }

		$paie=DB::table('paiement_fou')->where('fournisseur_id',$id)->get();
		return view('vente/detailsfou', [
			'paie'=> $paie,
		]);
	}
	function liste3(){

        if(session('user')== null) {
            return redirect('/');
        }
		$ventes=DB::table('vente')->where('etat','Validée')->orderBydesc('id')->get();
		$pdf = PDF::loadView('listeVentePDF', [
			'ventes' => $ventes,
		]);
        return $pdf->stream();
	}
	public function recherche() {

		if(session('user')== null) {
            return redirect('/');
		}
		
		$date_debut = request('date_debut');
		$cli = request('client');
        $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(['cli'=> $cli]);
		
		 if($date_fin > $date_debut || $date_fin == $date_debut){
			 if ($cli==0){
				$ventes=DB::table('vente')->where('etat','Validée')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
				$ventecount=DB::table('vente')->where('etat','Validée')->whereBetween('date', [$date_debut,$date_fin])->get()->count();
			 } else {
			 $ventes=DB::table('vente')->where('client_id',$cli)->where('etat','Validée')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
			 $ventecount=DB::table('vente')->where('client_id',$cli)->where('etat','Validée')->whereBetween('date', [$date_debut,$date_fin])->get()->count();
			 }
			 
			 $client=DB::table('client')->orderBydesc('id')->get();
			return view('liste_venterech',[
            'ventes' => $ventes,
            'date_debut' => $date_debut,
            'date_fin' => $date_fin,
            'client' => $client,
            'cli' => $cli,
            'ventecount' => $ventecount,
        ]);	
		 } else 
		 {
			return redirect()->route('listeVente')->with('error', 'La date de fin ne doit pas dépasser la date de début!');
		 }
	}
	function liste4(){

        if(session('user')== null) {
            return redirect('/');
        }
		$date_debut = session('date_debut');
		$date_fin = session('date_fin');
		$cli = session('cli');
		if($date_fin > $date_debut || $date_fin == $date_debut){
			 if ($cli==0){
				$ventes=DB::table('vente')->where('etat','Validée')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
				$ventecount=DB::table('vente')->where('etat','Validée')->whereBetween('date', [$date_debut,$date_fin])->get()->count();
			 } else {
			 $ventes=DB::table('vente')->where('client_id',$cli)->where('etat','Validée')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
			 $ventecount=DB::table('vente')->where('client_id',$cli)->where('etat','Validée')->whereBetween('date', [$date_debut,$date_fin])->get()->count();
			 }
			 //$approcount = DB::table('paiement_fou')->whereBetween('date', [$date_debut,$date_fin])->get()->count();
			 $client=DB::table('client')->orderBydesc('id')->get();
		$pdf = PDF::loadView('liste_venterechPDF', [
			'ventes' => $ventes,
            'date_debut' => $date_debut,
            'date_fin' => $date_fin,
            'client' => $client,
            'cli' => $cli,
            'ventecount' => $ventecount,
		]);
        return $pdf->stream();
	}else 
		 {
			return redirect()->route('listeVente')->with('error', 'La date de fin ne doit pas dépasser la date de début!');
		 }
	
	}
	//PAIEMENTS CLIENTS
	public function listepaiements(){

		if(session('user')== null) {
            return redirect('/');
		}
		
		$paie=DB::table('paiement_client')->orderBydesc('id')->get();
		$paiecount=DB::table('paiement_client')->get()->count();
		//$ventecount=DB::table('vente')->get()->count();
		$client=DB::table('client')->orderBydesc('id')->get();
		return view('paiement/liste',[
			'paie'=> $paie,
			'client'=> $client,
			'paiecount'=> $paiecount,
		]);
	}
	public function recherchepaie() {

		if(session('user')== null) {
            return redirect('/');
		}
		
		$date_debut = request('date_debut');
		$cli = request('client');
        $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(['cli'=> $cli]);
		
		 if($date_fin > $date_debut || $date_fin == $date_debut){
			 if ($cli==0){
				$paie=DB::table('paiement_client')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
				$paiecount=DB::table('paiement_client')->whereBetween('date', [$date_debut,$date_fin])->get()->count();
			 } else {
			 $paie=DB::table('paiement_client')->where('client_id',$cli)->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
			 $paiecount=DB::table('paiement_client')->where('client_id',$cli)->whereBetween('date', [$date_debut,$date_fin])->get()->count();
			 }
			 
			 $client=DB::table('client')->orderBydesc('id')->get();
			return view('paiement/liste_paie_rech',[
            'paie' => $paie,
            'date_debut' => $date_debut,
            'date_fin' => $date_fin,
            'client' => $client,
            'cli' => $cli,
            'paiecount' => $paiecount,
        ]);	
		 } else 
		 {
			return redirect()->route('liste_des_paiements')->with('error', 'La date de fin ne doit pas dépasser la date de début!');
		 }
	}
	//PDF LISTE DES PAIEMENTS CLIENTS
		function listepdf(){

        if(session('user')== null) {
            return redirect('/');
        }
		$paie = DB::table('paiement_client')->orderBydesc('id')->get();
		$pdf = PDF::loadView('paiement/listePDF', [
			'paie' => $paie,
		]);
        return $pdf->stream();
	}
	//PDF RECHERCHE PAIEMENTS CLIENTS
	function liste44(){

        if(session('user')== null) {
            return redirect('/');
        }
		$date_debut = session('date_debut');
		$date_fin = session('date_fin');
		$cli = session('cli');
		if($date_fin > $date_debut || $date_fin == $date_debut){
			 if ($cli==0){
				$paie=DB::table('paiement_client')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
				$paiecount=DB::table('paiement_client')->whereBetween('date', [$date_debut,$date_fin])->get()->count();
			 } else {
			 $paie=DB::table('paiement_client')->where('client_id',$cli)->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
			 $paiecount=DB::table('paiement_client')->where('client_id',$cli)->whereBetween('date', [$date_debut,$date_fin])->get()->count();
			 }
			 //$approcount = DB::table('paiement_fou')->whereBetween('date', [$date_debut,$date_fin])->get()->count();
			 $client=DB::table('client')->orderBydesc('id')->get();
		$pdf = PDF::loadView('paiement/liste_paie_rechPDF', [
			'paie' => $paie,
            'date_debut' => $date_debut,
            'date_fin' => $date_fin,
            'client' => $client,
            'cli' => $cli,
            'paiecount' => $paiecount,
		]);
        return $pdf->stream();
	}else 
		 {
			return redirect()->route('listeVente')->with('error', 'La date de fin ne doit pas dépasser la date de début!');
		 }
	
	}
	
	//MODIFICATION VENTES
	function modifvente($id) {
        if(session('user')== null) {
            return redirect('/');
        }
        $client = DB::table('client')->get();
        $produit = DB::table('produit_vendable')->orderBy('designation','ASC')->get();
        $vente = DB::table('vente')->where('id',$id)->first();
        $ligne_vente = DB::table('ligne_vente')->where('vente_id',$id)->get();
        return view('vente/modifier',[
            'client' => $client,
            'produit' => $produit,
            'ligne_vente' => $ligne_vente,
            'vente' => $vente,
        ]);
    }
	function modifvente2($id) {
        if(session('user')== null) {
            return redirect('/');
        }
        $client = DB::table('client')->get();
        $produit = DB::table('produit_vendable')->orderBy('designation','ASC')->get();
        $vente = DB::table('vente')->where('id',$id)->first();
		$ventes = DB::table('vente')->where('etat2', 'En cours')->where('user_id', session('user')->id)->orderBydesc('id')->take(50)->get();
        $ligne_vente = DB::table('ligne_vente')->where('vente_id',$id)->get();
        return view('vente/modifier2',[
            'client' => $client,
            'produit' => $produit,
            'ligne_vente' => $ligne_vente,
            'vente' => $vente,
            'ventes' => $ventes,
            'vente_id' => $id,
        ]);
    }
		function modifventev($id)
		{
		    $datet = request('datet');
			$todayyy =implode('-', array_reverse(explode('/', $datet)));
			$supl = DB::table('ligne_vente')->where('vente_id', $id)->delete();
			$sup2 = DB::table('ligne_taxe')->where('vente_id', $id)->delete();
			$typevente=request('typevente');
			$nomcli=request('nomcli');
			$contact=request('contact');
			$taxes=request('taxes');
			$remise=request('remise');
			//$peps=collect(request('peps'))->chunk(3);
			$peps=request('item');

			DB::table('vente')->where('id', $id)->update(
				[
				        'date' => $todayyy,
						'nomcli' => $nomcli,
						'contact' => $contact,
						'remise' => $remise,
						'nom_user' => session('user')->nom,
				]
			);
			$idLastvente = DB::table('vente')->where('id', $id)->first()->id;
			$date = DB::table('vente')->where('id', $id)->first();
			
			$i=0;
			
			foreach ($peps as $key=> $pep){

				$desi =  DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->desi;
				$pr = DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->pr;
				if ($pr > 0){
				    $pr = DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->pr;
				}else{
				    $pr = 0;
				}
					$qtestoc =  DB::table('stock_magasin')->where('produit_id', $pep[0 +$i])->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->get()->count();
					if ($qtestoc ==0){
						$qtesto = 0;
					}else{
					$qtesto =  DB::table('stock_magasin')->where('produit_id', $pep[0 +$i])->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(1)->first()->apres;
					}
					$categorie_id =  DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->categorie_id;
					
					if ($typevente == "Détail"){
					$prix =  DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->prix_detail;
					} else {
						$prix =  DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->prix_gros;
					}
						
						$categorie_id = DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->categorie_id;
						DB::table('ligne_vente')->insert(
							[
									'vente_id' => $id,
									'categorie_id' => $categorie_id,
									'produit_id' => $pep[0 +$i],
									'qte' => $pep[1 +$i],
									'remise' => 0,
									'pv' => $pep[2 +$i],
									'pr' => $pr,
									'montligne' => ($pep[1 +$i] * $pep[2 +$i]),
									'montlignepr' => ($pep[1 +$i] * $pr),
									'date' => $todayyy, 
									'user_id' => session('user')->id,
									'magasin_id' => session('user')->magasin_id,
							]
						);
							$i; 
					}  
				$mht = DB::table('ligne_vente')->where('vente_id', $id)->get()->sum('montligne');
				$mtremise = $remise;
				$mht1 = $mht - $mtremise;
				DB::table('vente')->where('id', $id)->update(
							[
								'montant_ht' => $mht,
								'remise' => $mtremise,
								'montant_remise' => $mtremise,
								'net_com' => $mht1,
							]
						);
						
				$nc = DB::table('vente')->where('id', $id)->first()->net_com;
				/*$today = date('Y-m-d'); 
				foreach($tau as $taux){
					DB::table('ligne_taxe')->insert(
							[
								'vente_id' => $id,
								'taux' => $taux->taux,
								'montligne' => $nc * $taux->taux,
							]
						);
				}
				$sumtaux = DB::table('ligne_taxe')->where('vente_id', $id)->get()->sum('montligne');
				$ttc = $sumtaux + $nc;*/
				if ($taxes == "Oui"){
					$tau = DB::table('taxes')->get();
						foreach($tau as $taux){
						DB::table('ligne_taxe')->insert(
								[
									'vente_id' => $id,
									'taux' => $taux->taux,
									'montligne' => $nc * $taux->taux,
								]
							);
						}
						$sumtaux = DB::table('ligne_taxe')->where('vente_id', $id)->get()->sum('montligne');
						$ttc = $sumtaux + $nc;
					} else {
						$sumtaux = 0;
						$ttc = $nc;
					}
				DB::table('vente')->where('id', $id)->update(
							[
								'total_taux' => $sumtaux,
								'montant' => $ttc,
							]
						);
				return redirect()->route('vente-code')->with('status','Vente modifiée avec succès' );
		}
	//CLOTURER VENTES
	function cloturer () {
		$today = date('Y-m-d');
		$today2 = date('d/m/Y');
		$heure = date('H:i');
		$verif = DB::table('vente')->where('etat','Proforma')->where('magasin_id',session('user')->magasin_id)->get()->count();
		if ($verif > 0){
			return redirect()->route('listeVente')->with('error', 'Attention ! Certaines ventes ne sont pas encore validées !');
		} else {
			$total1 = DB::table('vente')->where('etat', 'Validée')->where('magasin_id',session('user')->magasin_id)->where('etat2', 'En cours')->get()->sum('montant');
			$paiecli = DB::table('paiement_client')->where('etat2', 'Non cloturé')->where('magasin_id',session('user')->magasin_id)->get()->sum('montant');
			$remb = DB::table('remboursement')->where('etat1', 'Validée')->where('etat2', 'Non cloturé')->where('magasin_id',session('user')->magasin_id)->sum('montant');
			//$datevente = DB::table('vente')->where('etat', 'Validée')->where('etat2', 'En cours')->first()->date;
			$ddc = DB::table('stock_magasin')->where('magasin_id', session('user')->magasin_id)->where('type_operation', 'Vente')->where('etat', 'Validée')->get()->count();
			if ($ddc == 0){
				$dd = date('Y-m-d');
			} else {
				$dd = DB::table('stock_magasin')->where('magasin_id', session('user')->magasin_id)->where('type_operation', 'Vente')->where('etat', 'Validée')->orderBydesc('id')->take(1)->first()->date;
			}
			$total = ($total1 + $paiecli) - $remb;
            
            /*$produit = DB::table('produit_vendable')->where('caisseoff', 'Oui')->get();
            $plucked = $produit->pluck('id');
            $lignevente1 = DB::table('ligne_vente')->whereIn('produit_id', $plucked)->where('date', $dd)->where('etat', 'Validée')->where('user_id',session('user')->id)->sum('montligne');
            $lignevente2 = DB::table('ligne_vente_client')->whereIn('produit_id', $plucked)->where('date', $dd)->where('etat', 'Validée')->where('user_id',session('user')->id)->sum('montligne');
            
            $caisseoff = $lignevente1 + $lignevente2;*/
            
            $totaldep = DB::table('caisse_depense')->where('date', $dd)->where('etat', 'Validée')->where('etat2', 'En cours')->where('magasin_id',session('user')->magasin_id)->sum('montant');
            
            $reste = $total - $totaldep;
			DB::table('cloture')->insert(
                    [
                        'libelle' => 'Cloture  du '.$dd,
                        'montant' => $total,
                        'remboursement' => $remb,
                        'caisseoff' => 0,
                        'totaldep' => $totaldep,
                        'reste' => $reste,
                        'date' => $dd,
                        'heure' => $heure,
                        'user_id' => session('user')->id,
                        'magasin_id' => session('user')->magasin_id,

                    ]
                );
				DB::table('vente')->where('etat','Validée')->where('magasin_id',session('user')->magasin_id)->where('etat2','En cours')->update(
                [
                    'etat2' => "Cloturée",
                ]
            );
			DB::table('paiement_client')->where('magasin_id',session('user')->magasin_id)->update(
                [
                    'etat2' => "Cloturée",
                ]
            );
			DB::table('caisse_depense')->where('etat','Validée')->where('etat2','En cours')->where('magasin_id',session('user')->magasin_id)->update(
                [
                    'etat2' => "Cloturée",
                ]
            );
            DB::table('remboursement')->where('etat2','Non cloturé')->where('magasin_id',session('user')->magasin_id)->update(
                [
                    'etat2' => "Cloturée",
                ]
            );
				
		return redirect()->route('listeVente')->with('status', 'Journée cloturée avec succès !');
        }
	}
	
	function validercloture () {

		$id=request('id');	
		$montant=request('montant');
		$remise=request('remise');
		$dat = request('datet');
		$verse = DB::table('versement_caisier')->where('cloture_id', $id)->get()->sum('montant');
		$montantcloture = DB::table('cloture')->where('id', $id)->first()->caisseoff;
		$t=$verse+$montant;
		$today = implode('-', array_reverse(explode('/', $dat)));
		if ($t > $montantcloture){
		    /*$message = [
                "title" => 'Erreur',
                "type" => 'error',
                "response" => 'Le montant saisi ne doit pas dépasser le montant à verser :'. ' '. ($montantcloture - $verse).' F',
                ];
                return $message;*/
			return redirect()->route('liste-des-ventes-cloturees')->with('error', 'Le montant saisi dépasse le  reste à verser !'. ' '. ($montantcloture - $verse).' F');
		} else {
		    
		DB::table('versement_caisier')->insert(
			[
				'montant' => $montant,
				'remise' => $remise,
				'date' => $today,
				'cloture_id' => $id,
				'user_id' => session('user')->id,
				'magasin_id' => session('user')->magasin_id,
			]
		);
		return redirect()->route('liste-des-ventes-cloturees')->with('status', 'Versement effectué avec succès !');
	}}
	
	function voircloture ($id) {

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

            'cloture' => $cloture,
        ];
    }
	
	public function listecloture(){

		if(session('user')== null) {
            return redirect('/');
        }
		if (session('user')->roles == "Admin" || session('user')->roles == "Gérant"){
			$cloture=DB::table('cloture')->where('montant', '>', 0)->orderBydesc('id')->get();
			$total=DB::table('cloture')->where('etat', 'Versement effectué')->sum('montant');
		} else {
		$cloture=DB::table('cloture')->where('montant', '>', 0)->where('user_id', session('user')->id)->orderBydesc('id')->get();
		$total=DB::table('cloture')->where('etat', 'Versement effectué')->where('magasin_id', session('user')->magasin_id)->sum('montant');
		}
		return view('vente/liste-vente-clotures', [
			'cloture'=> $cloture,
			'total'=> $total,
		]);
	}


	function fichecloture($id)
    {
		if(session('user')== null) {
            return redirect('/');
        }

		$cloture = DB::table('cloture')->where('id',$id)->first();
        $pdf = PDF::loadView('/vente/fichecloture', [
            'cloture' => $cloture,
		]);
		
        return $pdf->stream();
    }
	
	public function rechcloturees(){

		if(session('user')== null) {
            return redirect('/');
		}
		
		$date_debut = request('date_debut');
        $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]);
		
		 if($date_fin > $date_debut || $date_fin == $date_debut){
		
		$cloture=DB::table('cloture')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
		$plucked = $cloture->pluck('id');
        $tvers = DB::table('versement_caisier')->whereIn('cloture_id', $plucked)->whereBetween('date', [$date_debut,$date_fin])->sum('montant');
        
		$total=DB::table('cloture')->whereBetween('date', [$date_debut,$date_fin])->sum('montant');
		$caisseoff=DB::table('cloture')->whereBetween('date', [$date_debut,$date_fin])->sum('caisseoff');
		$totaldep=DB::table('cloture')->whereBetween('date', [$date_debut,$date_fin])->sum('totaldep');
		return view('vente/liste-vente-clotures-rech', [
			'cloture'=> $cloture,
			'total'=> $total,
			'caisseoff'=> $caisseoff,
			'totaldep'=> $totaldep,
			'tvers'=> $tvers,
			'date_debut'=> $date_debut,
			'date_fin'=> $date_fin,
		]);
	} else 
		 {
			return redirect()->route('liste-vente-clotures')->with('error', 'La date de fin ne doit pas dépasser la date de début!');
	}}
	//VENTES JOUR PDF
	public function ventejourpdf(){

		if(session('user')== null) {
            return redirect('/');
        }
		
		$date_debut = session('date_debut');
		$date_fin = session('date_fin');
		
		 if($date_fin > $date_debut || $date_fin == $date_debut){
		
		$cloture=DB::table('cloture')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
		$plucked = $cloture->pluck('id');
        $tvers = DB::table('versement_caisier')->whereIn('cloture_id', $plucked)->whereBetween('date', [$date_debut,$date_fin])->sum('montant');
        
		$total=DB::table('cloture')->whereBetween('date', [$date_debut,$date_fin])->sum('montant');
		$caisseoff=DB::table('cloture')->whereBetween('date', [$date_debut,$date_fin])->sum('caisseoff');
		$totaldep=DB::table('cloture')->whereBetween('date', [$date_debut,$date_fin])->sum('totaldep');
		$pdf = PDF::loadView('vente/liste-vente-clotures-pdf', [
		'cloture'=> $cloture,
			'total'=> $total,
			'caisseoff'=> $caisseoff,
			'totaldep'=> $totaldep,
			'tvers'=> $tvers,
			'date_debut'=> $date_debut,
			'date_fin'=> $date_fin,
		]);
		 return $pdf->stream();
	} else 
		 {
			return redirect()->route('liste-vente-clotures')->with('error', 'La date de fin ne doit pas dépasser la date de début!');
	}}
	public function listetransactionpersonnel(){

		if(session('user')== null) {
            return redirect('/');
        }
		
		$th=DB::table('transaction_hopital')->orderBydesc('id')->get();
		$total=DB::table('transaction_hopital')->sum('montant');
		return view('vente/liste-transaction-personnel', [
			'th'=> $th,
			'total'=> $total,
		]);
	}
	function voirvaliderclo ($id) {

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

        $id=request('id');
		$today = date('d/m/Y');
		$today2 = date('Y-m-d');
		$heure = date('H:i');
		$mont = DB::table('cloture')->where('id', $id)->first()->montant;
            DB::table('cloture')->where('id', $id)->update(
                [
                    'etat' => "Versement effectué",
                    'heure_versement' => $heure,
                    'date_versement' => $today2,
                ]
            );
			$solde = DB::table('solde')->get()->count();
				if ($solde > 0){
					$soldef = DB::table('solde')->orderBydesc('id')->take(1)->first()->solde;
					$ss = $soldef + $mont;
				}else{
					$soldef = 0;
					$ss = 0 + $mont;
				}
                //$client1 = DB::table('client')->where('id', $client_id)->first()->nom;
                DB::table('solde')->insert(
                    [
                        'libelle' => 'Versement ventes du '.$today,
                        'montant' => $mont,
                        'nature' => 'Recette',
                        'date' => $today2,
                        'solde' => $ss,
                        'solde_initial' => $soldef,

                    ]
                );
        return redirect()->route('liste-des-ventes-cloturees')->with('status', 'Versement validé avec succès !');
	}
		function transaction(){

			if(session('user')== null) {
				return redirect('/');
			}

			$transaction = DB::table('transaction_hopital')->get();
			return view('vente/transaction',[
            'transaction' => $transaction,
        ]);	
	}
	//SOLDE DE LA CAISSE RECETTE
	function solde(){

		if(session('user')== null) {
            return redirect('/');
        }
	$magasin = DB::table('magasin')->get();
	$solde = DB::table('solde')->where('etat','Validée')->orderBydesc('id')->get();
			return view('solde/liste',[
            'solde' => $solde,
            'magasin' => $magasin,
        ]);	
	}
	//SOLDE DE LA BANQUE
	function banque(){

		if(session('user')== null) {
            return redirect('/');
        }
	$banque = DB::table('banque')->orderBydesc('id')->get();
			return view('solde/banque',[
            'banque' => $banque,
        ]);	
	}
	//RECHERCHE TRANSACTION HOPITAL
		public function transaPost() {

			if(session('user')== null) {
				return redirect('/');
			}

		$date_debut = request('date_debut');
        $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]);
		
		 if($date_fin > $date_debut || $date_fin == $date_debut){
			$th=DB::table('transaction_hopital')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
			$total=DB::table('transaction_hopital')->whereBetween('date', [$date_debut,$date_fin])->sum('montant');
			$thcount=DB::table('transaction_hopital')->whereBetween('date', [$date_debut,$date_fin])->get()->count();
			return view('vente/liste-transaction-personnel-rech',[
            'th' => $th,
            'date_debut' => $date_debut,
            'date_fin' => $date_fin,
            'thcount' => $thcount,
            'total' => $total,
        ]);	
		 } else 
		 {
			return redirect()->route('liste-transaction-personnel')->with('error', 'La date de fin ne doit pas dépasser la date de début!');
		 }
	}
	//FACTURE TRANSA HOPITAL
	function facturetransa(){

        if(session('user')== null) {
            return redirect('/');
        }
		$date_debut = session('date_debut');
		$date_fin = session('date_fin');
		if($date_fin > $date_debut || $date_fin == $date_debut){
			$th=DB::table('transaction_hopital')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
			$total=DB::table('transaction_hopital')->whereBetween('date', [$date_debut,$date_fin])->sum('montant');
			$thcount=DB::table('transaction_hopital')->whereBetween('date', [$date_debut,$date_fin])->get()->count();
			$pdf = PDF::loadView('vente/liste-transaction-personnel-pdf', [
			'th' => $th,
            'date_debut' => $date_debut,
            'date_fin' => $date_fin,
            'thcount' => $thcount,
            'total' => $total,
		]);
        return $pdf->stream();
	}}
	function facturetransa2(){

        if(session('user')== null) {
            return redirect('/');
        }
		$date_debut = session('date_debut');
		$date_fin = session('date_fin');
		if($date_fin > $date_debut || $date_fin == $date_debut){
			$th=DB::table('transaction_hopital')->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
			$total=DB::table('transaction_hopital')->whereBetween('date', [$date_debut,$date_fin])->sum('montant');
			$thcount=DB::table('transaction_hopital')->whereBetween('date', [$date_debut,$date_fin])->get()->count();
			$pdf = PDF::loadView('vente/liste-transaction-personnel-pdf2', [
			'th' => $th,
            'date_debut' => $date_debut,
            'date_fin' => $date_fin,
            'thcount' => $thcount,
            'total' => $total,
		]);
        return $pdf->stream();
	}}
	//Billetage
	function billetage(){

		if(session('user')== null) {
            return redirect('/');
        }
	$billetage = DB::table('ligne_versement')->get();
	$total = DB::table('ligne_versement')->sum('montligne');
			return view('vente/billetage',[
            'total' => $total,
            'billetage' => $billetage,
        ]);	
	}
	//billetage recherche
	function billetagerecherche(){

		if(session('user')== null) {
            return redirect('/');
        }
		$date_debut = request('date_debut');
        $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]);
		if($date_fin > $date_debut || $date_fin == $date_debut){
	$billetage = DB::table('ligne_versement')->whereBetween('date', [$date_debut,$date_fin])->get();
	$total = DB::table('ligne_versement')->whereBetween('date', [$date_debut,$date_fin])->sum('montligne');
			return view('vente/billetage-recherche',[
            'total' => $total,
            'billetage' => $billetage,
            'date_debut' => $date_debut,
            'date_fin' => $date_fin,
        ]);	
	} else {
	return redirect()->route('billetage')->with('error', 'La date de fin ne doit pas dépasser la date de début!');
	}
}
 //Billetage PDF
 //billetage recherche
	function billetagepdf(){

		if(session('user')== null) {
            return redirect('/');
        }
		$date_debut = session('date_debut');
		$date_fin = session('date_fin');
		if($date_fin > $date_debut || $date_fin == $date_debut){
	$billetage = DB::table('ligne_versement')->whereBetween('date', [$date_debut,$date_fin])->get();
	$total = DB::table('ligne_versement')->whereBetween('date', [$date_debut,$date_fin])->sum('montligne');
			$pdf = PDF::loadView('vente/billetage-pdf',[
            'total' => $total,
            'billetage' => $billetage,
            'date_debut' => $date_debut,
            'date_fin' => $date_fin,
        ]);	
		return $pdf->stream();
	}
}
//BILAN
	function bilan(){

		if(session('user')== null) {
            return redirect('/');
        }
		//DEPENSES
	$depensefou = DB::table('appro_vendable')->where('etat', 'Validée')->get()->sum('montant');
	$autredepense = DB::table('caisse_depense')->where('nature', 'Décaissement')->get()->sum('montant');
	//RECETTES
	$totalvente = DB::table('vente')->where('etat2', 'Cloturée')->get()->sum('montant');
	$totalpaie = DB::table('paiement_client')->where('etat2', 'Cloturée')->get()->sum('montant');
	$totdep = $depensefou + $autredepense;
	$totrec = $totalvente + $totalpaie;
	$benefice = $totrec - $totdep;
	
			return view('solde/bilan',[
            'depensefou' => $depensefou,
            'autredepense' => $autredepense,
            'totalvente' => $totalvente,
            'totalpaie' => $totalpaie,
            'totdep' => $totdep,
            'totrec' => $totrec,
            'benefice' => $benefice,
        ]);	
	}
	
	public function devis(){
		
        if(session('user')== null) {
            return redirect('/');
        }
		
		$produit=DB::table('produit_vendable')->orderby('designation','asc')->get();
		$client=DB::table('client')->take(1)->get();
		$remise=DB::table('remise')->where('magasin_id', session('user')->magasin_id)->where('etat', 'Actif')->orderbydesc('id')->get();
		$categorie=DB::table('categorie')->get();
		$ventes = DB::table('devis')->where('user_id', session('user')->id)->orderBydesc('id')->take(30)->get();
		return view('vente/devis', [
			'produit'=> $produit,
			'ventes'=> $ventes,
			'client'=> $client,
			'cat'=> $categorie,
			'remise'=> $remise,
		]);
	}
	function facturedevis($id)
    {
		if(session('user')== null) {
            return redirect('/');
		}
		
		$devis = DB::table('devis')->where('id',$id)->first();

		$ligne = DB::table('ligne_devis')->where('vente_id',$id)->get();
		$lignetax = DB::table('ligne_taxe_devis')->where('vente_id',$id)->get();
		$ligneM = DB::table('ligne_devis')->where('vente_id',$id)->get()->sum('montligne');
		$montant = $devis->montant;
		$montant=round($montant,0);
		$montant1 = (new \App\Classes\ChiffreEnLettre)->Conversion($montant);

        $pdf = PDF::loadView('/vente/facturedevis', [

            'ligne' => $ligne,
			'devis' => $devis,
			'ligneM' => $ligneM,
			'lignetax' => $lignetax,
			'montant1' => $montant1,
		]);
		
        return $pdf->stream();
    }
	
	function devispost()
    {

		$dat = date('d/m/Y');

        $hour = date('H:i:s');

		$today = implode('-', array_reverse(explode('/', $dat)));
		$todayyy = date('Y-m-d'); 
		$typevente=request('typevente');
		$nomcli=request('nomcli');
		$contact=request('contact');
		$rem=request('remise');
		if ($rem==0){
			$remise=0;
		} else{
			//$remc = DB::table('remise')->where('id', $rem)->first()->taux;
			$remise=DB::table('remise')->where('id', $rem)->first()->taux;
		}
		$peps=collect(request('peps'))->chunk(3);
		if ($peps != ""){
		DB::table('devis')->insert(
				[
					'date' => $today,
					'heure' => $hour,
					'type_vente' => $typevente,
					'remise' => $remise,
					'nomcli' => $nomcli,
					'contact' => $contact,
					'user_id' => session('user')->id,
					'magasin_id' => session('user')->magasin_id,
				]
			);

			$idLastvente = DB::table('devis')->get()->last()->id;
			$idLast= strlen($idLastvente);
	
			if ($idLast==1){
				DB::table('devis')->where('id', $idLastvente)->update(
					[
						'numero' => '000'.$idLastvente,
					]
				);
			} elseif ($idLast==2){
		
				DB::table('devis')->where('id', $idLastvente)->update(
					[
						'numero' => '00'.$idLastvente,
					]
				);
			} elseif ($idLast==3){
				DB::table('devis')->where('id', $idLastvente)->update(
					[
						'numero' => '0'.$idLastvente,
					]
				);
			} else {
				DB::table('devis')->where('id', $idLastvente)->update(
					[
						'numero' => $idLastvente,
					]
				);
			}
	
			$i=0;
			
	foreach ($peps as $key=> $pep){
				$desi =  DB::table('produit_vendable')->where('id', $pep[1 +$i])->first()->desi;
				$qtestoc =  DB::table('stock_magasin')->where('produit_id', $pep[1 +$i])->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->get()->count();
                if ($qtestoc <= 0){
					DB::table('devis')->where('id', $idLastvente)->delete();
                    DB::table('ligne_devis')->where('vente_id', $idLastvente)->delete();
					$message = [
                        "title" => 'Erreur de stock',
                        "type" => 'error',
                        "response" => 'Aucun stock de '.$desi.' n\'est disponible dans ce dépôt !',
                    ];
        
                    return $message;
				} else {
				$qtesto =  DB::table('stock_magasin')->where('produit_id', $pep[1 +$i])->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(1)->first()->apres;
				$categorie_id =  DB::table('produit_vendable')->where('id', $pep[1 +$i])->first()->categorie_id;
                if($qtesto < $pep[2 +$i]){
    
                    DB::table('devis')->where('id', $idLastvente)->delete();
                    DB::table('ligne_devis')->where('vente_id', $idLastvente)->delete();
    
                    $message = [
                        "title" => 'Erreur d\'enregistrement',
                        "type" => 'error',
                        "response" => 'Stock '.' '.$desi.' '.'insuffisant ! Stock restant : '.$qtesto,
                    ];
        
                    return $message;
    
                }else{
				
					if ($typevente=="Détail"){
						$prix =  DB::table('produit_vendable')->where('id', $pep[1 +$i])->first()->prix_detail;
					} else {
						$prix =  DB::table('produit_vendable')->where('id', $pep[1 +$i])->first()->prix_gros;
					}   
					DB::table('ligne_devis')->insert(
						[
								'vente_id' => $idLastvente,
								'categorie_id' => $pep[0 +$i],
								'produit_id' => $pep[1 +$i],
								'qte' => $pep[2 +$i],
								'pv' => $prix,
								'montligne' => ($pep[2 +$i] * $prix),
								'date' => $todayyy, 
								
								'user_id' => session('user')->id,
								'magasin_id' => session('user')->magasin_id,
						]
					);
						$i += count($pep->toArray()); 
				}  
				}
	}
			$mht = DB::table('ligne_devis')->where('vente_id', $idLastvente)->get()->sum('montligne');
			$rem2 = DB::table('devis')->where('id', $idLastvente)->first()->remise;
			$mtremise = $mht * ($rem2/100);
			$mht1 = $mht - $mtremise;
			DB::table('devis')->where('id', $idLastvente)->update(
						[
							'montant_ht' => $mht,
							'remise' => $remise,
							'montant_remise' => $mtremise,
							'net_com' => $mht1,
						]
					);
					
			$tau = DB::table('taxes')->get();
			$nc = DB::table('devis')->where('id', $idLastvente)->first()->net_com;
			$today = date('Y-m-d'); 
			foreach($tau as $taux){
				DB::table('ligne_taxe_devis')->insert(
						[
							'vente_id' => $idLastvente,
							'taux' => $taux->taux,
							'montligne' => $nc * $taux->taux,
						]
					);
			}
			$sumtaux = DB::table('ligne_taxe_devis')->where('vente_id', $idLastvente)->get()->sum('montligne');
			$ttc = $sumtaux + $nc;
			DB::table('devis')->where('id', $idLastvente)->update(
						[
							'total_taux' => $sumtaux,
							'montant' => $ttc,
						]
					);
			
		}
	$message = [
				"title" => 'success',
				"type" => 'success',
				"response" => 'Opération effectué avec succes !',
			];
	
			return $message;
	}
	public function listevente323(){

		if(session('user')== null) {
            return redirect('/');
        }
		$today = date('Y-m-d');
		if (session('user')->roles=="Caissier"){
			$caissier=DB::table('users')->where('id', session('user')->id)->get();
			$ligne = DB::table('ligne_vente')->where('user_id', session('user')->id)->where('date', $today)->get();
			$total = DB::table('vente')->where('user_id', session('user')->id)->where('date', $today)->where('etat', 'Validée')->sum('montant');
			$paiement_client = DB::table('paiement_client')->where('user_id', session('user')->id)->where('date', $today)->sum('montant');
			$remise = DB::table('vente')->where('user_id', session('user')->id)->where('date', $today)->where('etat', 'Validée')->sum('remise');
			$montant = DB::table('vente')->where('user_id', session('user')->id)->where('date', $today)->where('etat', 'Validée')->sum('montant_ht');
			
		    $totaldep = DB::table('caisse_depense')->where('user_id', session('user')->id)->where('date', $today)->where('etat', 'Validée')->sum('montant');
		    $dep = DB::table('caisse_depense')->where('user_id', session('user')->id)->where('date', $today)->where('etat', 'Validée')->get();
		} else {
			$caissier=DB::table('users')->where('roles', 'Caissier')->get();
			$ligne = DB::table('ligne_vente')->where('date', $today)->get();
			$total = DB::table('vente')->where('date', $today)->where('etat', 'Validée')->sum('montant');
			$paiement_client = DB::table('paiement_client')->where('date', $today)->sum('montant');
			$remise = DB::table('vente')->where('date', $today)->where('etat', 'Validée')->sum('remise');
			$montant = DB::table('vente')->where('date', $today)->where('etat', 'Validée')->sum('montant_ht');
			
			$totaldep = DB::table('caisse_depense')->where('date', $today)->where('etat', 'Validée')->sum('montant');
			$dep = DB::table('caisse_depense')->where('date', $today)->where('etat', 'Validée')->get();
		}
		
		return view('vente/historique-caissier', [
			'caissier'=> $caissier,
			'paiement_client'=> $paiement_client,
			'ligne'=> $ligne,
			'total'=> $total,
			'remise'=> $remise,
			'montant'=> $montant,
			'dep'=> $dep,
			'totaldep'=> $totaldep,
		]);
	}
	public function listevente324(){

		if(session('user')== null) {
            return redirect('/');
        }
		
		$date_debut = request('date_debut');
		$caissier = request('caissier');
        $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(['caissier'=> $caissier]);
		
		if($date_fin > $date_debut || $date_fin == $date_debut){
		
			$ligne=DB::table('ligne_vente')->where('user_id', $caissier)->whereBetween('date', [$date_debut,$date_fin])->orderBydesc('id')->get();
			$caissier1=DB::table('users')->where('roles', 'Caissier')->get();
			$total=DB::table('vente')->where('user_id', $caissier)->where('etat', 'Validée')->whereBetween('date', [$date_debut,$date_fin])->where('etat', 'Validée')->sum('montant');
			$paiement_client = DB::table('paiement_client')->where('user_id', $caissier)->whereBetween('date', [$date_debut,$date_fin])->sum('montant');
			$remise=DB::table('vente')->where('user_id', $caissier)->where('etat', 'Validée')->whereBetween('date', [$date_debut,$date_fin])->where('etat', 'Validée')->sum('remise');
			$montant=DB::table('vente')->where('user_id', $caissier)->where('etat', 'Validée')->whereBetween('date', [$date_debut,$date_fin])->where('etat', 'Validée')->sum('montant_ht');
			
			$totaldep=DB::table('caisse_depense')->where('user_id', $caissier)->where('etat', 'Validée')->whereBetween('date', [$date_debut,$date_fin])->where('etat', 'Validée')->sum('montant');
			$dep=DB::table('caisse_depense')->where('user_id', $caissier)->where('etat', 'Validée')->whereBetween('date', [$date_debut,$date_fin])->where('etat', 'Validée')->get();
			
			return view('vente/historique-caissier-rech', [
			'ligne'=> $ligne,
			'caissier1'=> $caissier1,
			'caissier'=> $caissier,
			'total'=> $total,
			'paiement_client'=> $paiement_client,
			'remise'=> $remise,
			'montant'=> $montant,
			'date_debut'=> $date_debut,
			'date_fin'=> $date_fin,
			'totaldep'=> $totaldep,
			'dep'=> $dep,
		]);
	} else 
		 {
			return redirect()->route('historique-par-caissier')->with('error', 'La date de fin ne doit pas dépasser la date de début!');
	}}

	public function listevente325(){

		if(session('user')== null) {
            return redirect('/');
        }
		$today = date('Y-m-d');
		if (session('user')->roles=="Caissier"){
			$caissier=DB::table('users')->where('id', session('user')->id)->get();
			$ligne = DB::table('ligne_vente')->where('user_id', session('user')->id)->where('date', $today)->get();
			$total = DB::table('vente')->where('user_id', session('user')->id)->where('date', $today)->where('etat', 'Validée')->sum('montant');
			$paiement_client = DB::table('paiement_client')->where('user_id', session('user')->id)->where('date', $today)->sum('montant');
			$remise = DB::table('vente')->where('user_id', session('user')->id)->where('date', $today)->where('etat', 'Validée')->sum('remise');
			$montant = DB::table('vente')->where('user_id', session('user')->id)->where('date', $today)->where('etat', 'Validée')->sum('montant_ht');
			
			$totaldep = DB::table('caisse_depense')->where('user_id', session('user')->id)->where('date', $today)->where('etat', 'Validée')->sum('montant');
			$dep = DB::table('caisse_depense')->where('user_id', session('user')->id)->where('date', $today)->where('etat', 'Validée')->get();
			
		} else {
			$caissier=DB::table('users')->where('roles', 'Caissier')->get();
			$ligne = DB::table('ligne_vente')->where('date', $today)->get();
			$total = DB::table('vente')->where('date', $today)->where('etat', 'Validée')->sum('montant');
			$paiement_client = DB::table('paiement_client')->where('date', $today)->sum('montant');
			$remise = DB::table('vente')->where('date', $today)->where('etat', 'Validée')->sum('remise');
			$montant = DB::table('vente')->where('date', $today)->where('etat', 'Validée')->sum('montant_ht');
			
			$totaldep = DB::table('caisse_depense')->where('date', $today)->where('etat', 'Validée')->sum('montant');
			$dep = DB::table('caisse_depense')->where('date', $today)->where('etat', 'Validée')->get();
		}
		
		$pdf = PDF::loadView('vente/historique-caissier-pdf', [
			'caissier'=> $caissier,
			'ligne'=> $ligne,
			'total'=> $total,
			'paiement_client'=> $paiement_client,
			'today'=> $today,
			'remise'=> $remise,
			'montant'=> $montant,
			'totaldep'=> $totaldep,
			'dep'=> $dep,
		]);
		return $pdf->stream();
	}
	//recherche facture
	public function listevente234(){

		if(session('user')== null) {
            return redirect('/');
        }
		//$numero = request('numero');
		if (session('user')->roles== "Admin"){
			$ventes=DB::table('vente')->orderBydesc('id')->limit(50)->get();
		} elseif (session('user')->roles== "Gérant"){
			$ventes=DB::table('vente')->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->limit(50)->get();
		} else {
			$ventes=DB::table('vente')->where('user_id', session('user')->id)->orderBydesc('id')->limit(50)->get();
		}
		return view('vente/rech-fact-cli', [
			'ventes'=> $ventes,
		]);
	}
	public function listevente235(){

		if(session('user')== null) {
            return redirect('/');
        }
		$numero = request('numero');
		if (session('user')->roles== "Admin"){
		$verif=DB::table('vente')->where('numero', $numero)->first();
		} elseif (session('user')->roles== "Admin"){
		$verif=DB::table('vente')->where('magasin_id', session('user')->magasin_id)->where('numero', $numero)->first();
		} else {
		$verif=DB::table('vente')->where('user_id', session('user')->id)->where('numero', $numero)->first();	
		}
		if ($verif){
		$ventes=DB::table('vente')->where('numero', $numero)->get();
		return view('vente/rech-fact-cli2', [
			'ventes'=> $ventes,
		]);
	} else 
		 {
			return redirect()->route('recherche-facture')->with('error', 'Vous avez saisi un numéro incorrect ou soit la facture n\'est pas enregistrée sous votre nom !');
	}}
	public function detailcloture($id){

		if(session('user')== null) {
            return redirect('/');
        }
		$cl = DB::table('cloture')->where('id',$id)->first();
		$today = date('Y-m-d');
			$ligne = DB::table('ligne_vente')->where('date', $cl->date)->where('user_id',$cl->user_id)->get();
			$total = DB::table('vente')->where('date', $cl->date)->where('etat', 'Validée')->where('user_id',$cl->user_id)->sum('montant');
			$remise = DB::table('vente')->where('date', $cl->date)->where('etat', 'Validée')->where('user_id',$cl->user_id)->sum('remise');
			$montant = DB::table('vente')->where('date', $cl->date)->where('etat', 'Validée')->where('user_id',$cl->user_id)->sum('montant_ht');
		return view('vente/detailcloture', [
			'caissier'=> $cl->user_id,
			'dd'=> $cl->date,
			'ligne'=> $ligne,
			'total'=> $total,
			'remise'=> $remise,
			'montant'=> $montant,
		]);
	}
	
	function modifvente3($id) {
        if(session('user')== null) {
            return redirect('/');
        }
        $client = DB::table('client')->get();
        $produit = DB::table('produit_vendable')->orderBy('designation','ASC')->get();
        $vente = DB::table('vente')->where('id',$id)->first();
		$ventes = DB::table('vente')->where('etat2', 'En cours')->where('user_id', session('user')->id)->orderBydesc('id')->take(50)->get();
        $ligne_vente = DB::table('ligne_vente')->where('vente_id',$id)->get();
        return view('vente/modifier3',[
            'client' => $client,
            'produit' => $produit,
            'ligne_vente' => $ligne_vente,
            'vente' => $vente,
            'ventes' => $ventes,
            'vente_id' => $id,
        ]);
    }
	function modifventev2($id)
		{
			//$todayyy =implode('-', array_reverse(explode('/', $dat)));
			$todayyy = date('Y-m-d');
			$typevente=request('typevente');
			$nomcli=request('nomcli');
			$contact=request('contact');
			$taxes=request('taxes');
			$remise=request('remise');
			//$peps=collect(request('peps'))->chunk(3);
			$peps=request('item');
            
            $vo = DB::table('ligne_vente')->where('vente_id', $id)->get();
	    	foreach($vo as $vos){					
					$sg = DB::table('produit_vendable')->where('id', $vos->produit_id)->first()->stock_general;
					$qtesto = DB::table('stock_magasin')->where('produit_id', $vos->produit_id)->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(1)->first()->apres;
					$qteval = $vos->qte;
					DB::table('produit_vendable')->where('id', $vos->produit_id)->update(
						[
							'stock_general' => ($sg - $qteval),
						]
					);
					DB::table('stock_magasin')->insert(
							[
								'date' => $todayyy,
								'produit_id' => $vos->produit_id,
								'qte' => $qteval,
								'type_operation' => 'Modification vente',
								'en_stock' => $qtesto,
								'apres' => ($qtesto + $qteval),
								'stock_general' => ($sg + $qteval),
								'magasin_id' => session('user')->magasin_id,
								'user_id' => session('user')->id,
								'vente_id' => $id,
							]
						);
						
					$sv = DB::table('produit_vendable')->where('id',  $vos->produit_id)->first()->totvendu;
					DB::table('produit_vendable')->where('id',  $vos->produit_id)->update(
						[
							'totvendu' => $sv - $qteval,
						]
					);
			}
			
			
			$supl = DB::table('ligne_vente')->where('vente_id', $id)->delete();
			$sup2 = DB::table('ligne_taxe')->where('vente_id', $id)->delete();
            
			DB::table('vente')->where('id', $id)->update(
				[
						'nomcli' => $nomcli,
						'contact' => $contact,
						'remise' => $remise,
						'etat' => "Proforma",
				]
			);
			
			$date = DB::table('vente')->where('id', $id)->first();
			
			$i=0;
			
			foreach ($peps as $key=> $pep){

				$desi =  DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->desi;
				$pr = DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->pr;
					$qtestoc =  DB::table('stock_magasin')->where('produit_id', $pep[0 +$i])->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->get()->count();
					if ($qtestoc ==0){
						$qtesto = 0;
					}else{
					$qtesto =  DB::table('stock_magasin')->where('produit_id', $pep[0 +$i])->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(1)->first()->apres;
					}
					$categorie_id =  DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->categorie_id;
					
					/*if ($typevente == "Détail"){
					$prix =  DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->prix_detail;
					} else {
						$prix =  DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->prix_gros;
					}*/
						
						$categorie_id = DB::table('produit_vendable')->where('id', $pep[0 +$i])->first()->categorie_id;
						DB::table('ligne_vente')->insert(
							[
									'vente_id' => $id,
									'categorie_id' => $categorie_id,
									'produit_id' => $pep[0 +$i],
									'qte' => $pep[1 +$i],
									'remise' => 0,
									'pv' => $pep[2 +$i],
									'pr' => $pr,
									'montligne' => ($pep[1 +$i] * $pep[2 +$i]),
									'montlignepr' => ($pep[1 +$i] * $pr),
									'date' => $todayyy,
									'user_id' => session('user')->id,
									'magasin_id' => session('user')->magasin_id,
									'etat' => "Proforma",
							]
						);
							$i; 
					}  
				$mht = DB::table('ligne_vente')->where('vente_id', $id)->get()->sum('montligne');
				$mtremise = $remise;
				$mht1 = $mht - $mtremise;
				DB::table('vente')->where('id', $id)->update(
							[
								'montant_ht' => $mht,
								'remise' => $mtremise,
								'montant_remise' => $mtremise,
								'net_com' => $mht1,
							]
						);
						
				$nc = DB::table('vente')->where('id', $id)->first()->net_com;
				/*$today = date('Y-m-d'); 
				foreach($tau as $taux){
					DB::table('ligne_taxe')->insert(
							[
								'vente_id' => $id,
								'taux' => $taux->taux,
								'montligne' => $nc * $taux->taux,
							]
						);
				}
				$sumtaux = DB::table('ligne_taxe')->where('vente_id', $id)->get()->sum('montligne');
				$ttc = $sumtaux + $nc;*/
				if ($taxes == "Oui"){
					$tau = DB::table('taxes')->get();
						foreach($tau as $taux){
						DB::table('ligne_taxe')->insert(
								[
									'vente_id' => $id,
									'taux' => $taux->taux,
									'montligne' => $nc * $taux->taux,
								]
							);
						}
						$sumtaux = DB::table('ligne_taxe')->where('vente_id', $id)->get()->sum('montligne');
						$ttc = $sumtaux + $nc;
					} else {
						$sumtaux = 0;
						$ttc = $nc;
					}
				DB::table('vente')->where('id', $id)->update(
							[
								'total_taux' => $sumtaux,
								'montant' => $ttc,
							]
						);
				return redirect()->route('vente-code')->with('status','Vente modifiée avec succès' );
		}
	
}