<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DB;

use PDF;

class ConsignationController extends Controller
{
    //
	



    function facturepaie($id)
    {
        if(session('user')== null) {
            return redirect('/');
        }
        $paie = DB::table('paiement_client')->where('id',$id)->first();
        //$vente_id = DB::table('paiement_client')->where('id',$id)->first()->vente_id;
        $client = DB::table('paiement_client')->where('id',$id)->first()->client_id;
        $ligne = DB::table('ligne_vente_client')->where('client_id',$client)->where('etat','Validée')->get();
        //$paye = DB::table('paiement_fou')->where('appro_id',$appro_id)->get()->sum('montant');
        //$vente = DB::table('vente_client')->where('client_id',$client)->where('etat','Validée')->first();
        $vente = DB::table('vente_client')->where('client_id',$client)->where('etat','Validée')->get()->sum('montant');

        $pdf = PDF::loadView('/client_externe/facture_paie', [

            'paie' => $paie,
            'ligne' => $ligne,
            'vente' => $vente,
            'client' => $client,
            //'paye' => $paye,
        ]);
        
        return $pdf->stream();
    }

    function pclient($id)
    {
        if(session('user')== null) {
            return redirect('/');
		}
		$vente = DB::table('vente_client')->where('client_id',$id)->first();
		$paie = DB::table('paiement_client')->where('client_id',$id)->get();
		return view('client_externe/paiement',[
            'vente' => $vente,
            'paie' => $paie,
        ]);	
    }

	public function venteclient($id){
      
        if(session('user')== null) {
            return redirect('/');
        }
		$vente= DB::table('vente_client')->where('client_id',$id)->where('etat','Validée')->get();
		$total= DB::table('vente_client')->where('client_id',$id)->where('etat','Validée')->get()->sum('montant');
		$totalpaie= DB::table('paiement_client')->where('client_id',$id)->get()->sum('montant');
		$reste = $total - $totalpaie;
        $client= DB::table('client_externe')->where('id',$id)->first()->noms;
        
         return view('client_externe/liste_vente',[

		'vente' => $vente,
		'client' => $client,
		'total' => $total,
		'totalpaie' => $totalpaie,
        'reste' => $reste,
        
	  ]);
	}



    function factureconsignation($id)
    {
		if(session('user')== null) {
            return redirect('/');
		}
		
		$consignation = DB::table('consignation')->where('id',$id)->first();

		$ligne = DB::table('ligne_consignation')->where('consignation_id',$id)->get();
		$lignetax = DB::table('ligne_taxe_consignation')->where('consignation_id',$id)->get();
		$ligneM = DB::table('ligne_consignation')->where('consignation_id',$id)->get()->sum('montligne');
		

        $pdf = PDF::loadView('/consignation/facture', [

            'ligne' => $ligne,
			'consignation' => $consignation,
			'ligneM' => $ligneM,
			'lignetax' => $lignetax,
		]);
		
        return $pdf->stream();
    }


    function VoirSuppression ($id) {

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

            'consignation' => $consignation,
        ];
    }

    function supprimer () {

        $id=request('id');

        DB::table('ligne_consignation')->where('consignation_id', $id)->delete();
        DB::table('ligne_taxe_consignation')->where('consignation_id', $id)->delete();

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

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

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

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

    function voirvalider ($id) {

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

    public function consignation(){
		
        if(session('user')== null) {
            return redirect('/');
        }
		
		$emballage=DB::table('emballage')->where('stock_general', '>', 0)->get();
		$client=DB::table('client_externe')->get();
		//$categorie=DB::table('categorie')->get();
		$remise=DB::table('remise')->where('magasin_id', session('user')->magasin_id)->where('etat', 'Actif')->orderBydesc('id')->get();
		if (session('user')->roles=="Admin"){
		$consignation = DB::table('consignation')->where('etat2', 'En cours')->orderBydesc('id')->get();
		} elseif (session('user')->roles=="Gérant") {
			$consignation = DB::table('consignation')->where('etat2', 'En cours')->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->get();
		} else {
			$consignation = DB::table('consignation')->where('etat2', 'En cours')->where('user_id', session('user')->id)->orderBydesc('id')->get();
		}
		return view('consignation/nouveau', [
			'emballage'=> $emballage,
			'client'=> $client,
			'consignation'=> $consignation,
			'remise'=> $remise,
		]);
    }
    
    function valider (){

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

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

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


		foreach($vo as $vos){
					
					$sg = DB::table('emballage')->where('id', $vos->emballage_id)->first()->stock_general;
					$qtesto = DB::table('stock_emballage')->where('emballage_id', $vos->emballage_id)->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(1)->first()->apres;
					$qteval = $vos->qte;
		
					DB::table('emballage')->where('id', $vos->emballage_id)->update(
						[
							'stock_general' => ($sg - $qteval),
						]
					);
					DB::table('stock_emballage')->insert(
							[
								'date' => $today,
								'emballage_id' => $vos->emballage_id,
								'qte' => $qteval,
								'type_operation' => 'Vente',
								'en_stock' => $qtesto,
								'apres' => ($qtesto - $qteval),
								'stock_general' => ($sg - $qteval),
								'magasin_id' => session('user')->magasin_id,
							]
						);
			}
		return redirect()->route('consignation')->with('status', 'Consignation validée avec succès !');
	}

   function enregistrer()
    {

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

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

		$today = implode('-', array_reverse(explode('/', $dat)));
		$todayyy = date('Y-m-d'); 
		//$typevente=request('typevente');
		$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;
		}
		$client=request('client');
		$peps=collect(request('peps'))->chunk(2);
		if ($peps != ""){
		DB::table('consignation')->insert(
				[
					'date' => $today,
					'heure' => $hour,
					'client_id' => $client,
					//'type_vente' => $typevente,
					'remise' => $remise,
					'user_id' => session('user')->id,
					'magasin_id' => session('user')->magasin_id,
				]
			);

			$idLastvente = DB::table('consignation')->get()->last()->id;
			$idLast= strlen($idLastvente);
	
			if ($idLast==1){
				DB::table('consignation')->where('id', $idLastvente)->update(
					[
						'numero' => '000'.$idLastvente,
					]
				);
			} elseif ($idLast==2){
		
				DB::table('consignation')->where('id', $idLastvente)->update(
					[
						'numero' => '00'.$idLastvente,
					]
				);
			} elseif ($idLast==3){
				DB::table('consignation')->where('id', $idLastvente)->update(
					[
						'numero' => '0'.$idLastvente,
					]
				);
			} else {
				DB::table('consignation')->where('id', $idLastvente)->update(
					[
						'numero' => $idLastvente,
					]
				);
			}
	
			$i=0;
			
	foreach ($peps as $key=> $pep){
				$desi =  DB::table('emballage')->where('id', $pep[0 +$i])->first()->libelle;
				$qtestoc =  DB::table('stock_emballage')->where('emballage_id', $pep[0 +$i])->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->get()->count();
                if ($qtestoc <= 0){
					DB::table('consignation')->where('id', $idLastvente)->delete();
                    DB::table('ligne_consignation')->where('consignation_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_emballage')->where('emballage_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[1 +$i])->first()->categorie_id;
                if($qtesto < $pep[1 +$i]){
    
                    DB::table('consignation')->where('id', $idLastvente)->delete();
                    DB::table('ligne_consignation')->where('consignation_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;
					}  */ 
					$prix =  DB::table('emballage')->where('id', $pep[0 +$i])->first()->prix;
					DB::table('ligne_consignation')->insert(
						[
								'consignation_id' => $idLastvente,
								'client_id' => $client,
								'emballage_id' => $pep[0 +$i],
								'qte' => $pep[1 +$i],
								'pv' => $prix,
								'montligne' => ($pep[1 +$i] * $prix),
								'date' => $todayyy, 
								'user_id' => session('user')->id,
								'magasin_id' => session('user')->magasin_id,
						]
					);
						$i += count($pep->toArray()); 
				}  
				}
	}
			$mht = DB::table('ligne_consignation')->where('consignation_id', $idLastvente)->get()->sum('montligne');
			$rem2 = DB::table('consignation')->where('id', $idLastvente)->first()->remise;
			$mtremise = $mht * ($rem2/100);
			$mht1 = $mht - $mtremise;
			DB::table('consignation')->where('id', $idLastvente)->update(
						[
							'montant_ht' => $mht,
							'remise' => $remise,
							'montant_remise' => $mtremise,
							'net_com' => $mht1,
						]
					);
			$tau = DB::table('taxes')->get();
			$nc = DB::table('consignation')->where('id', $idLastvente)->first()->net_com;
			$today = date('Y-m-d'); 
			foreach($tau as $taux){
				DB::table('ligne_taxe_consignation')->insert(
						[
							'consignation_id' => $idLastvente,
							'taux' => $taux->taux,
							'montligne' => $nc * $taux->taux,
						]
					);
			}
			$sumtaux = DB::table('ligne_taxe_consignation')->where('consignation_id', $idLastvente)->get()->sum('montligne');
			$ttc = $sumtaux + $nc;
			DB::table('consignation')->where('id', $idLastvente)->update(
						[
							'total_taux' => $sumtaux,
							'montant' => $ttc,
						]
					);
			
		}
	$message = [
				"title" => 'success',
				"type" => 'success',
				"response" => 'Opération effectuée avec succes !',
			];
	
			return $message;
	}


    function validerclient () {

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

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

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


		foreach($vo as $vos){
					
					$sg = DB::table('emballage')->where('id', $vos->emballage_id)->first()->stock_general;
					$qtesto = DB::table('stock_emballage')->where('emballage_id', $vos->emballage_id)->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(1)->first()->apres;
					$qteval = $vos->qte;
		
					DB::table('emballage')->where('id', $vos->emballage_id)->update(
						[
							'stock_general' => ($sg - $qteval),
						]
					);
					DB::table('stock_emballage')->insert(
							[
								'date' => $today,
								'emballage_id' => $vos->emballage_id,
								'qte' => $qteval,
								'type_operation' => 'Consignation',
								'en_stock' => $qtesto,
								'apres' => ($qtesto - $qteval),
								'stock_general' => ($sg - $qteval),
								'magasin_id' => session('user')->magasin_id,
							]
						);
			}
		return redirect()->route('consignation')->with('status', 'Consignation validée avec succès !');
    }
    

    function enregistrer3(Request $request)
    {
        $client_id=request('client_id');
        $montant=request('montant');
        $mode=request('mode');
		$note=request('note');
        $today2 = date('Y-m-d');
		$apayer = DB::table('vente_client')->where('client_id', $client_id)->get()->sum('montant');
        $clientid = DB::table('vente_client')->where('client_id', $client_id)->first()->client_id;
        $datv1 = DB::table('vente_client')->where('client_id', $client_id)->first()->date;
        
        $datv = implode('/', array_reverse(explode('-', $datv1)));

		$sommePaiement =  DB::table('paiement_client')->where('client_id', $client_id)->get()->sum('montant');
		$total = $sommePaiement + $montant ;
		$mtpd = DB::table('paiement_client')->where('client_id', $client_id)->get()->sum('montant');
		$mtpd1 = $mtpd + $montant;
		$mtd = $apayer - $mtpd1;
		
		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{
        DB::table('paiement_client')->insert(
            [

                'client_id' => $client_id,
                'montant' => $montant,
                'mode' => $mode,
                'date' => $today2,
                'note' => $note,
                'paye' => $mtpd1, 
                'reste' => $mtd,
                'etat' => "En cours",
                'user_id' => session('user')->id,
                'magasin_id' => session('user')->magasin_id,
            ]
        );

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

        return $message;
	
   }   
 }


 function validerpaie () {

    $id=request('id');
    
    $montpaie = DB::table('paiement_client')->where('id', $id)->first()->montant;

    $client_id = DB::table('paiement_client')->where('id', $id)->first()->client_id;
    $noms = DB::table('client_externe')->where('id', $client_id)->first()->noms;
    $today2 = date('Y-m-d');

    DB::table('paiement_client')->where('id', $id)->update(
        [
            'etat' => "Validé",
        ]
    );
	return redirect()->route('liste_des_paiements')->with('status', 'Paiement validé avec succès !');
	}
  
	function fgpost()
    {

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

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

		$today = implode('-', array_reverse(explode('/', $dat)));
		$todayyy = date('Y-m-d'); 
		$client= request('client');
		$serveuse= request('serveuse');
		$typevente=request('typevente');

		$peps=collect(request('peps'))->chunk(2);

			DB::table('factureglobale')->insert(
				[
					'date' => $today,
					'heure' => $hour,
					'client_id' => $client,
					'serveuse_id' => $serveuse,
					'type_vente' => $typevente,
				]
			);

			$idLastvente = DB::table('factureglobale')->get()->last()->id;
			$idLast= strlen($idLastvente);
	
			if ($idLast==1){
				DB::table('factureglobale')->where('id', $idLastvente)->update(
					[
						'numero' => '000'.$idLastvente,
					]
				);
			} elseif ($idLast==2){
		
				DB::table('factureglobale')->where('id', $idLastvente)->update(
					[
						'numero' => '00'.$idLastvente,
					]
				);
			} elseif ($idLast==3){
				DB::table('factureglobale')->where('id', $idLastvente)->update(
					[
						'numero' => '0'.$idLastvente,
					]
				);
			} else {
				DB::table('factureglobale')->where('id', $idLastvente)->update(
					[
						'numero' => $idLastvente,
					]
				);
			}
	
			$i=0;
			
			foreach ($peps as $key=> $pep){
            
                $qtesto =  DB::table('produit_vendable_fini')->where('id', $pep[0 +$i])->first()->stock_gene;
    
                $desi =  DB::table('produit_vendable_fini')->where('id', $pep[0 +$i])->first()->designation;
   
                    $prov_id =  DB::table('produit_vendable_fini')->where('id', $pep[0 +$i])->first()->pv_id;
				
                    if ($typevente=="VIP"){
                        $prix =  DB::table('produit_vendable_fini')->where('id', $pep[0 +$i])->first()->prix_vip;
                    } else {
					$prix =  DB::table('produit_vendable_fini')->where('id', $pep[0 +$i])->first()->prix_ordinaire;
			     	}
	
				   
					DB::table('ligne_factureglobale')->insert(
						[
							'vente_id' => $idLastvente,
							'produit_id' => $pep[0 +$i],
							'qte' => $pep[1 +$i],
							'pv' => $prix,
							'montligne' => ($pep[1 +$i] * $prix),
							'date' => $todayyy,
							'client_id' => $client,
							'produitvendable_id' => $prov_id, 
						]
					);
		
					$i += count($pep->toArray());  
			}
			$message = [
				"title" => 'success',
				"type" => 'success',
				"response" => 'Opération effectué avec succes !',
			];
	
			return $message;
    }
	function factureglobalepdf($id)
    {
		if(session('user')== null) {
            return redirect('/');
		}
		
		$vente = DB::table('factureglobale')->where('id',$id)->first();

		$ligne = DB::table('ligne_factureglobale')->where('vente_id',$id)->get();
		$ligneM = DB::table('ligne_factureglobale')->where('vente_id',$id)->get()->sum('montligne');
		

        $pdf = PDF::loadView('/client_externe/factureglobalepdf', [

            'ligne' => $ligne,
			'vente' => $vente,
			'ligneM' => $ligneM,
		]);
		
        return $pdf->stream();
    }
	function VoirSupp ($id) {

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

            'cli' => $cli,
        ];
    }
	function supp () {

        $id=request('id');

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

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

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

}
