<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DB;
use PDF;

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

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

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

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

        $id=request('id');
		$prestation_id = DB::table('ligne_prestation')->where('id', $id)->first()->prestation_id;
		$prestation = DB::table('prestation')->where('id', $prestation_id)->first();
		$montligne = DB::table('ligne_prestation')->where('id', $id)->first()->montligne;
		$montant = $prestation->montant - $montligne;
		if ($prestation->montant_taxe > 0){
		$taxe = DB::table('taxes')->sum('taux');
		$montant_taxe = $montant * $taxe;
		$ttc = ($montant + $montant_taxe) - $prestation->remise;
		} else {
			$taxe = 0;
			$montant_taxe = 0;
			$ttc = $montant - $prestation->remise;
		}
		DB::table('prestation')->where('id', $prestation->id)->update(
			[
				'montant' => $montant,
				'montant_taxe' => $montant_taxe,
				'ttc' => $ttc,
			]
		);
		DB::table('ligne_prestation')->where('id', $id)->delete();
	return redirect()->route('consultation_prestation',['id'=>$prestation->id])->with('status', 'Suppression effectuée avec succes');
    }
	//Modifier
	function modifprestation($id) {
        if(session('user')== null) {
            return redirect('/');
        }
        $fournisseurs = DB::table('fournisseur')->get();
        $produits = DB::table('produit_vendable')->get();
        $magasin = DB::table('magasin')->orderBydesc('id')->get();
        $ligne_prestation = DB::table('ligne_prestation')->where('prestation_id',$id)->get();
		$prestation = DB::table('prestation')->where('id',$id)->first();
        return view('prestation/modifier',[
            'fournisseurs' => $fournisseurs,
            'produits' => $produits,
            'magasin' => $magasin,
            'ligne_prestation' => $ligne_prestation,
            'prestation' => $prestation,
        ]);
    }

    function voirvalider ($id) {

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

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

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

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

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

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

            $qteval = $lignes->qte;
			
			//$verif = DB::table('stock_magasin')->where('produit_id', $lignes->produit_id)->where('magasin_id', $magasin)->get()->count();
		
			$sm = DB::table('magasin_general')->where('produit_id', $lignes->produit_id)->orderBydesc('id')->take(1)->first()->apres;
				
				DB::table('magasin_general')->insert(
                    [
                        'date' => $today,
                        'produit_id' => $lignes->produit_id,
                        'qte' => $qteval,
                        'type_operation' => 'Annulation prestation',
						'en_stock' => $sm,
						'apres' => ($sm - $qteval),
                    ]
                );
			
			
            DB::table('produit_vendable')->where('id', $lignes->produit_id)->update(
                [
                    'stock_magasin' => ($sm - $qteval),
                    //'stock_general' => ($qtesto + $qteval),
                ]
            );
			
        }
		DB::table('prestation')->where('id', $id)->update(
                [
                    'etat' => "Annulée",
                ]
            );

            DB::table('ligne_prestation')->where('prestation_id', $id)->update(
                [
                    'etat' => "Annulée",
                ]
            );
		
		$solde_compte = DB::table('transaction_fournisseur')->where('fournisseur_id', $fou)->orderBydesc('id')->take(1)->first()->solde_compte;
		$ss = $solde_compte - $lh;
		
		DB::table('transaction_fournisseur')->insert(
			[
				'date' => $todayyy,
				'libelle' => 'Annulation '.$ref,
				'montant' => $lh,
				'solde_initial' => $solde_compte,
				'solde_compte' => $ss,
				'type' => 'Débit',
				'fournisseur_id' => $fou,
				'prestation_id' => $id,
			]
		);
		DB::table('transaction_fournisseur')->where('prestation_id', $id)->update(
			[
				'etat' => 'Annulée',
			]
		);
				
        return redirect()->route('nouveau_prestation')->with('status', 'Annulation effectuée avec succes');
	}
    
    function valider () {

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

            DB::table('prestation')->where('id', $id)->update(
                [
                    'etat' => "Validée",
                ]
            );
            DB::table('ligne_prestation')->where('prestation_id', $id)->update(
                [
                    'etat' => "Validée",
                ]
            );
        return redirect()->route('prestation')->with('status', 'Validation effectuée avec succès');
	}
	function annulerdetail () {

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

            
        $ligne = DB::table('ligne_prestation')->where('id', $id)->first();
        $prestation_id = DB::table('ligne_prestation')->where('id', $id)->first()->prestation_id;
		$fou = DB::table('prestation')->where('id', $prestation_id)->first()->fournisseur_id;
		$ref = DB::table('prestation')->where('id', $prestation_id)->first()->numero;
		$lh = DB::table('prestation')->where('id', $prestation_id)->first()->montant;
		//$magasin = DB::table('prestation')->where('id', $id)->first()->magasin_id;
        //$qtesto = DB::table('produit_vendable')->where('id', $lignes->produit_id)->first()->stock_general;
        $qtesto = DB::table('produit_vendable')->where('id', $ligne->produit_id)->first()->stock_general;
        $qteval = $ligne->qte;
        $montligne = $ligne->montligne;
		$lh2 = $lh - $montligne;	
			
		//$verif = DB::table('stock_magasin')->where('produit_id', $lignes->produit_id)->where('magasin_id', $magasin)->get()->count();
		
		$sm = DB::table('magasin_general')->where('produit_id', $ligne->produit_id)->orderBydesc('id')->take(1)->first()->apres;
				
		DB::table('magasin_general')->insert(
			[
				'date' => $today,
				'produit_id' => $ligne->produit_id,
				'qte' => $qteval,
				'type_operation' => 'Annulation prestation',
				'en_stock' => $sm,
				'apres' => ($sm - $qteval),
			]
		);
        DB::table('produit_vendable')->where('id', $ligne->produit_id)->update(
			[
				'stock_magasin' => ($sm - $qteval),
			]
		);
		DB::table('prestation')->where('id', $ligne->prestation_id)->update(
                [
                    'montant' => $lh2,
                ]
            );
			

            DB::table('ligne_prestation')->where('id', $id)->update(
                [
                    'etat' => "Annulée",
                ]
            );
		
		$solde_compte = DB::table('transaction_fournisseur')->where('fournisseur_id', $fou)->orderBydesc('id')->take(1)->first()->solde_compte;
		$ss = $solde_compte - $montligne;
		$sf = DB::table('transaction_fournisseur')->where('prestation_id', $prestation_id)->first()->solde_compte;
		DB::table('transaction_fournisseur')->where('prestation_id', $id)->update(
			[
				'montant' => $lh2,
				'solde_compte' => ($sf - $montligne),
			]
		);
		
		DB::table('transaction_fournisseur')->insert(
			[
				'date' => $todayyy,
				'libelle' => 'Annulation '.$ref,
				'montant' => $montligne,
				'solde_initial' => $solde_compte,
				'solde_compte' => $ss,
				'type' => 'Débit',
				'fournisseur_id' => $fou,
				'prestation_id' => $prestation_id,
			]
		);
		
				
        return redirect()->route('consultation_prestation', ['id'=>$prestation_id])->with('status', 'Annulation effectuée avec succès');
	}
    function nouveau() {
		if(session('user')== null) {
            return redirect('/');
        }
       
        $fournisseurs = DB::table('fournisseur')->get();
        $prestations = DB::table('prestation')->orderBydesc('id') ->limit(100)->get();
        $magasin = DB::table('magasin')->orderBydesc('id')->get();

        return view('prestation/nouveau',[

            'fournisseur' => $fournisseurs,
            'prestation' => $prestations,
        ]);
    }
	function paiement($id) {
		if(session('user')== null) {
            return redirect('/');
        }
       
        $prestation = DB::table('prestation')->where('id', $id)->first();
        $paiement = DB::table('paiement_prestation')->orderBydesc('id')->get();

        return view('prestation/paiement',[

            'paiement' => $paiement,
            'prestation' => $prestation,
        ]);
    }
	
	function listedesprestation() {
       if(session('user')== null) {
            return redirect('/');
        }
        $fournisseurs = DB::table('fournisseur')->orderBy('nom','asc')->get();
        //$produits = DB::table('produit_vendable')->get();
        $prestations = DB::table('prestation')->where('etat', 'Validée')->orderBydesc('id')->limit(200)->get();
        return view('prestation/liste',[
            'fournisseur' => $fournisseurs,
            'prestation' => $prestations,
        ]);
    }
	public function recherche() {
		$date_debut = request('date_debut');
		$client = 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(['client'=> $client]);
		
		 if($date_fin > $date_debut || $date_fin == $date_debut){
			if ($client==0){
				$prestation = DB::table('prestation')->whereBetween('date_prestation', [$date_debut,$date_fin])->get();
				$prestationcount=DB::table('prestation')->whereBetween('date_prestation', [$date_debut,$date_fin])->get()->count();
				$total = DB::table('prestation')->where('etat', 'Validée')->whereBetween('date_prestation', [$date_debut,$date_fin])->get()->sum('montant');
			} else {
				$prestation = DB::table('prestation')->where('client_id', $client)->whereBetween('date_prestation', [$date_debut,$date_fin])->get();
				$prestationcount=DB::table('prestation')->where('client_id', $client)->whereBetween('date_prestation', [$date_debut,$date_fin])->get()->count();
				$total = DB::table('prestation')->where('client_id', $client)->where('etat', 'Validée')->whereBetween('date_prestation', [$date_debut,$date_fin])->get()->sum('montant');
			}
			$fournisseur = DB::table('fournisseur')->orderBy('nom','asc')->get();
			return view('prestation/liste-prestation-recherche',[
            'prestation' => $prestation,
            'client' => $client,
            'fournisseur' => $fournisseur,
            'prestationcount' => $prestationcount,
            'date_debut' => $date_debut,
            'date_fin' => $date_fin,
            'total' => $total,
        ]);	
		 } else 
		 {
			return redirect()->route('liste-des-prestations')->with('error', 'La date de fin ne doit pas dépasser la date de début!');
		 }
	}
	
	//FACTURE prestation
	
	function factureprestation($id)
    {

		$prestation = DB::table('prestation')->where('id',$id)->first();
		$ligne = DB::table('ligne_prestation')->where('prestation_id',$id)->get();
		$lignem = DB::table('ligne_prestation')->where('prestation_id',$id)->sum('montligne');
		$montant1 = (new \App\Classes\ChiffreEnLettre)->Conversion($prestation->ttc);
        $pdf = PDF::loadView('/prestation/facture', [
            'ligne' => $ligne,
			'prestation' => $prestation,
			'lignem' => $lignem,
			'montant1' => $montant1,
		]);
		
        return $pdf->stream();
    }

    function enregistrer(Request $request)
    {
        $taxe=request('taxe');
        $remise=request('remise');
        $client_id=request('client_id');
        $datep=implode('-', array_reverse(explode('/', request('datep'))));
        $prestation=collect(request('prestation'))->chunk(3);
		
            DB::table('prestation')->insert(
                [
                    'remise' => $remise,
                    'client_id' => $client_id,
                    'date_prestation' => $datep,
                    'etat' => "Proforma",
					'user_id' => session('user')->id,
					'magasin_id' => session('user')->magasin_id,
                ]
            );

            $idLastprestation = DB::table('prestation')->get()->last()->id;

            $id2= strlen($idLastprestation);

            if ($id2==1){

                DB::table('prestation')->where('id', $idLastprestation)->update(
                    [
                        'numero' => 'FA-000'.$idLastprestation,
                    ]
                );

            } elseif ($id2==2){

                DB::table('prestation')->where('id', $idLastprestation)->update(
                    [
                        'numero' => 'FA-00'.$idLastprestation,
                    ]
                );

            } elseif ($id2==3){

                DB::table('prestation')->where('id', $idLastprestation)->update(
                    [
                        'numero' => 'FA-0'.$idLastprestation,
                    ]
                );

            } else {

                DB::table('prestation')->where('id', $idLastprestation)->update(
                    [
                        'numero' => 'FA-'.$idLastprestation,
                    ]
                );
            }

        $i=0;

        foreach ($prestation as $key=> $prestations){

            DB::table('ligne_prestation')->insert(
                [
                    'prestation_id' => $idLastprestation,
                    'client_id' => $client_id,
                    'etat' => "Proforma",
                    'designation' => $prestations[0 +$i],
                    'qte' => $prestations[1 +$i],
                    'pu' => $prestations[2 +$i],
                    'montligne' => ($prestations[1 +$i] * $prestations[2 +$i]),
					'date' => $datep,
					'user_id' => session('user')->id,
					'magasin_id' => session('user')->magasin_id,
                ]
            );
            $i += count($prestations->toArray());
        }
		$montant = DB::table('ligne_prestation')->where('prestation_id', $idLastprestation)->sum('montligne');
		if ($taxe == "Oui"){
			$tva = DB::table('taxes')->sum('taux');
			$montant_taxe = $montant * $tva;
			$ttc = ($montant + $montant_taxe) - $remise;
		} else {
			$tva = 0;
			$montant_taxe = 0;
			$ttc = ($montant + $montant_taxe) - $remise;
		}
		DB::table('prestation')->where('id', $idLastprestation)->update(
                    [
                        'montant' => $montant,
                        'montant_taxe' => $montant_taxe,
                        'ttc' => $ttc,
                    ]
                );
		
            $message = [
                "title" => 'Succès',
                "type" => 'success',
                "response" => 'Enregistrement effectué avec succès !',
            ];
            return $message;
    }
	function modifprestationp($id)
    {

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

		$supl = DB::table('ligne_prestation')->where('prestation_id', $id)->delete();
		
		DB::table('prestation')->where('id', $id)->update(
                [
                    'fournisseur_id' => $fournisseur,
                    'magasin_id' => $magasin,
                    'date_prestation' => $dateprestation,
                    'etat' => "Proforma",
					'magasin_id' => session('user')->magasin_id,
                   
                ]
            );
			$idLastprestation = DB::table('prestation')->where('id', $id)->first()->id;

		$i=0;
        foreach ($prestationvision as $key=> $prestationvisions){

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

            DB::table('ligne_prestation')->insert(
                [
                    'prestation_id' => $idLastprestation,
					'magasin_id' => $magasin,
                    'fournisseur_id' => $idLastprestation,
                    'etat' => "Proforma",
                    'produit_id' => $prestationvisions[0 +$i],
                    'qte' => $prestationvisions[1 +$i],
                    'pa' => $prestationvisions[2 +$i],
                    'montligne' => ($prestationvisions[1 +$i] * $prestationvisions[2 +$i]),
					'date' => $dateprestation,
					'en_stock' => $qtesto,
                    'apres' => ($qtesto + $prestationvisions[1 +$i]),
					'magasin_id' => session('user')->magasin_id,
                ]
            );

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

        }

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

    }
	
//ENREGISTREMENT DEPENSE
	function enregistrer3($id)
    {
        $datep=request('datep');
        $montant=request('montant');
        $mode=request('mode');
        $note=request('note');
        $today=date('Y-m-d');
		$datep = implode('-', array_reverse(explode('/', $datep)));
		$prestation = DB::table('prestation')->where('id', $id)->first();
		$paye = DB::table('paiement_prestation')->sum('montant');
		$reste  = $prestation->ttc - $paye;
		$reste2  = $prestation->ttc - ($paye + $montant);
		$paye2  = $paye + $montant;
		if ($montant > $reste){
			$message = [
			"title" => 'Attention',
			"type" => 'error',
			"response" => 'Attention, le montant saisi ne doit pas dépasser le reste à payer : '.$reste,
		];
		return $message;
		} else {
			DB::table('paiement_prestation')->insert(
			[
				'date' => $datep,
				'mode' => $mode,
				'montant' => $montant,
				'note' => $note,
				'reste' => $reste2,
				'totpaie' => $paye2,
				'user_id' => session('user')->id,
				'magasin_id' => session('user')->magasin_id,
				'client_id' => $prestation->client_id,
				'prestation_id' => $prestation->id,
			]
		);	
		$idLasto = DB::table('paiement_prestation')->get()->last()->id;
			$idLast= strlen($idLasto);
	
			if ($idLast==1){
				DB::table('paiement_prestation')->where('id', $idLasto)->update(
					[
						'numero' => '000'.$idLast,
					]
				);
			} elseif ($idLast==2){
		
				DB::table('paiement_prestation')->where('id', $idLasto)->update(
					[
						'numero' => '00'.$idLast,
					]
				);
			} elseif ($idLast==3){
				DB::table('paiement_prestation')->where('id', $idLasto)->update(
					[
						'numero' => '0'.$idLast,
					]
				);
			} else {
				DB::table('paiement_prestation')->where('id', $idLasto)->update(
					[
						'numero' => $idLast,
					]
				);
			}
		$message = [
			"title" => 'success',
			"type" => 'success',
			"response" => 'Enregistrement succès !',
		];
		return $message;
		}
	}
	public function voir(){
      
        if(session('user')== null) {
            return redirect('/');
        }
		
		$fou= DB::table('fournisseur')->orderBy('nom')->get();
		
		return view('solde/nouveau',[
		
		'fou' => $fou,

	]);
	}
	public function achatfou($id){
      
        if(session('user')== null) {
            return redirect('/');
        }
		$prestation= DB::table('prestation')->where('fournisseur_id',$id)->where('etat','Validée')->get();
		$total= DB::table('prestation')->where('fournisseur_id',$id)->where('etat','Validée')->get()->sum('montant');
		$totalpaie= DB::table('paiement_fou')->where('fournisseur_id',$id)->get()->sum('montant');
		$reste = $total - $totalpaie;
		$fou= DB::table('fournisseur')->where('id',$id)->first()->nom;
	return view('prestation/liste-des-prestation-fournisseurs',[
		'prestation' => $prestation,
		'fou' => $fou,
		'total' => $total,
		'totalpaie' => $totalpaie,
		'reste' => $reste,
	]);
	}
	// Fonction supprimer
	function supprimer () {

        $id=request('id');

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

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

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

    }
	function supppaie () {

        $id=request('id');

        $prest_id = DB::table('paiement_prestation')->where('id', $id)->first()->prestation_id;
        DB::table('paiement_prestation')->where('id', $id)->delete();
        return redirect()->route('paiement-facture',['id'=>$prest_id])->with('status', 'Suppression effectuée avec succes');
    }
	function recu($id)
    {

		if(session('user')== null) {
            return redirect('/');
		}
		
		$paie= DB::table('paiement_prestation')->where('id', $id)->first();
		$pdf = PDF::loadView('prestation/facture_paie', [
		'paie' => $paie,
	]);
	return $pdf->stream();
    }
}
