<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use PDF;
use Illuminate\Mail\Mailable;
use Illuminate\Support\Facades\Mail;
use App\Mail\ContactMail;

class AuthentificationController extends Controller

{
    //
	
	function contact (){
        return view ('contact-us');
    }
	
	
	public function envoi(Request $request) {
      
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email',
            'comment' => 'required|string',
        ]);
    
		$emailadmin = 'admin@gmail.com';
       
        Mail::to($emailadmin)->send(new ContactMail($validated)); 

        return response()->json([
            'status' => 'success',
            'message' => 'Votre message a été envoyé avec succès.'
        ]);

    }

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

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

		$ligne = DB::table('ligne_commande')->where('commande_id',$id)->get();
		

        $pdf = PDF::loadView('facture_commande', [

            'idcmde' => $id,

            'ligne' => $ligne,

			'facture' => $facture,


		]);
		
        return $pdf->stream();

    }


    function resetpass ($id) {

        $newpassword = md5(request("newpassword"));
        $confirmpass= md5(request("confirmpass"));

        if($newpassword == $confirmpass){

            DB::table('client')->where('id', $id)->update(
                [
                    'password' => $newpassword,
                ]
            );

         return redirect()->route('client')->with('status', 'Mot de passe rénitialisé avec succes !');

        }else{

            return redirect()->route('reset', ['id' => $id ])->with('error', 'Mots de passe sont incorrects');

        }
           

    }


    function reset ($id) {

        $info = DB::table('information')->get()->last();

        return view('reset', [
 
            'info' => $info,

            'iduser' => $id,

            ]);
    }

    function verifier (Request $request){

        $email= request("email");

        $verification = DB::table('client')->where('email',$email)->first();

        if ($verification) {

            $iduser = DB::table('client')->where('email',$email)->first()->id;

            return redirect()->route('reset', ['id' => $iduser ]);
        }
        else{
            return redirect('/forgot_password')
            ->with('error', 'Votre email est invalide')
            ->withInput();

        }

    }


    function pass () {

        $info = DB::table('information')->get()->last();

        return view('password', [
 
            'info' => $info,

            ]);
    }
	


    function Voirtraitement ($id) {

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



    function somptesave (){

        $idcli =  session('client')->id;

        $nom= request("nom");
        $nom = strtoupper($nom);
        $prenom= request("prenom");
        $email= request("email");
        $adresse= request("adresse");

        $oldpassword=request("oldpassword");

        $newpassword=request("newpassword");

        $confirmpass= request("confirmpass");


        $password = DB::table('client')->where('id', $idcli)->first()->password;

        if ( ($oldpassword != null ) && ($newpassword != null ) && ($confirmpass != null )){

            $oldpassword=md5($oldpassword);

            $newpassword=md5($newpassword);
    
            $confirmpass= md5($confirmpass);

            if( $password == $oldpassword ){

                if($newpassword == $confirmpass){
    
                 DB::table('client')->where('id', $idcli)->update(
    
                        [   
                            'nom' => $nom,
                            'prenom' => $prenom,
                            'email' => $email,
                            'adresse' => $adresse,
                            'password' => $newpassword,
                        ]
                 );
        
                 return redirect()->back()->with('status', 'Modification effectuée avec succes !');
    
                }else{
    
    
                    return redirect()->back()->with('error', 'Le nouveau mot de passe et la confirmation sont incorrectes ! ');
    
                }
    
    
    
            }else{
    
                return redirect()->back()->with('error', 'Le mot de passe actuel saisi est incorrect !');
    
            }

        }else{

            DB::table('client')->where('id', $idcli)->update(
    
                [  
                    'nom' => $nom,
                    'prenom' => $prenom,
                    'email' => $email,
                    'adresse' => $adresse,
                   
                ]
         );

        return redirect()->back()->with('status', 'Modification effectuée avec succes!');

        }


    }


    function moncompte() {

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

        $idcli =  session('client')->id;

        return view('compte',[
           
            'idcli' => $idcli,
		
        ]);
   
    }


    function clt_paie() {

        if(session('client')== null) {
            return redirect('/client');
        }
        
        $idcli =  session('client')->id;

        $paie = DB::table('transaction')->where('client_id', $idcli)->where('status', 'Terminé')->orderBydesc('id')->get();

        return view('paiement_client_commande',[

            'paie' => $paie,
            'idcli' => $idcli,
          
        ]);
    }
	
	

	function clt_cmde() {

        if(session('client')== null) {
            return redirect('/client');
        }
        
        $idcli =  session('client')->id;

        $cmde = DB::table('commande')->where('client_id', $idcli)->orderBydesc('id')->get();

        return view('client_commande',[

            'cmde' => $cmde,
            'idcli' => $idcli,
          
        ]);
    }

 

    function detcpte() {

        if(session('client')== null) {
            return redirect('/client');
        }
        
        $idcli =  session('client')->id;

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

        return view('detail_compte',[

            'client' => $client,
			'idcli' => $idcli,
          
        ]);
    }


    function det($id) {

        if(session('user')== null) {
            return redirect('/admin');
        }
       
        $deta = DB::table('ligne_commande')->where('commande_id', $id)->get();

        return view('details',[

            'deta' => $deta,

            'idcmde' => $id,
          
        ]);
    }


    function detclt($id) {

       if(session('client')== null) {
            return redirect('/client');
        }
       
        $deta = DB::table('ligne_commande')->where('commande_id', $id)->get();

        return view('commande_details_client',[

            'deta' => $deta,

            'idcmde' => $id,
          
        ]);
    }

    function liste_cli() {

        if(session('user')== null) {
            return redirect('/admin');
        }
       
        $cli = DB::table('client')->where('profil', 'Client')->orderBy('nom')->get();

        return view('liste_client',[

            'cli' => $cli,
          
        ]);
    }



    function liste_cmde() {

        if(session('user')== null) {
            return redirect('/admin');
        }
       
        $cmde = DB::table('commande')->orderBydesc('id')->paginate(7);

        return view('liste_commande',[

            'cmde' => $cmde,
          
        ]);
    }


    function liste_tran() {

        if(session('user')== null) {
            return redirect('/admin');
        }
       
        $paie = DB::table('transaction')->orderBydesc('id')->paginate(7);

        return view('liste_transaction',[

            'paie' => $paie,
          
        ]);
    }



	function confirm ($id) {

        $info = DB::table('information')->get()->last();

        return view('confirm', [
 
            'info' => $info,

            'id' => $id,

            ]);

    }



	function confirmpost (Request $request) {
		$code= request("code");
		$id= request("id");
		$verif = DB::table('client')->where('id', $id)->where('code', $code)->first();
		if ($verif){
			DB::table('client')->where('id', $id)->where('code', $code)->update(
			[
				'etat' => 'Actif',
			]
			);
			$client = DB::table('client')->where('id',$id)->where('code',$code )->first();
			session(['client' => $client]); 
			return redirect()->route('compte');
			
		} else {
			return redirect()->route('confirmation-de-compte', ['id'=>$id])->with('error', 'Le code de confirmation saisi est incorrect !');
		}
    }



	function moncompte2() {

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

        $idcli =  session('client')->id;

        return view('tableau-de-bord',[
           
            'idcli' => $idcli,
		
        ]);
   
    }


	
    function enregistrerclient (Request $request){

        $profil= "Client";
        $nom= request("nom");
        $nom = strtoupper($nom);
        $prenom = request("prenom");
        $adresse = request("adresse");
        $email= request("email");
        $tel= request("tel");
        $password=md5(request("password"));
        $confirm=md5(request("confirm"));

        $veri = DB::table('client')->where('email', $email)->first();

        if($veri){

            return redirect()->route('register')->with('error', 'Cet email existe déja');

        }else{

            if ($confirm == $password){
				$code = rand(1, 100000);
                DB::table('client')->insert(
                    [  
                        'profil' => $profil,
                        'nom' => $nom,
                        'prenom' => $prenom,
                        'tel' => $tel,
                        'email' => $email,
                        'adresse' => $adresse,
                        'password' => $password,
                        'code' => $code,
                        
                    ]
                );
				$id = DB::table('client')->where('email', $email)->first()->id;
				
				return redirect()->route('client')->with('status', 'Compte crée avec succès');
	
               
            } else {
                return redirect()->route('register')->with('error', 'Echec! les mots de passe sont incorrectes');
             
            }

        }

    }



    function accueil()
    {    

        $lang = app()->getLocale();

        $cat = DB::table('categorie')
            ->join('produit', 'categorie.id', '=', 'produit.categorie_id')
            ->select(
                'categorie.id',
                DB::raw("libelle_$lang as libelle"),
                'image_categorie'
            )
            ->distinct()
            ->orderBy("libelle_$lang") // tri dynamique selon la langue
            ->get();


        $categorie = DB::table('categorie')
            ->select(
                'id',
                DB::raw("libelle_$lang as libelle"),
                'image_categorie',
            )
            ->orderBy("libelle_$lang")
            ->get();


        $produit = DB::table('produit')
            ->select(
                'id',
                DB::raw("designation_$lang as designation"),
                DB::raw("description_$lang as description"),
                'image_produit',
                'categorie_id',
                'prix',
                'etat_dispo'
            )
            ->where('etat_pub', 'Publié')
            ->where("designation_$lang", 'REGEXP', '^[A-Ha-h]') // commence par A à H
            ->orderByDesc('id')
            ->get();

        
        $produito = DB::table('produit')
            ->select(
                'id',
                DB::raw("designation_$lang as designation"),
                DB::raw("description_$lang as description"),
                'image_produit',
                'categorie_id',
                'prix',
                'etat_dispo'
            )
            ->where('etat_pub', 'Publié')
            ->where("designation_$lang", 'REGEXP', '^[I-Pi-p]') // commence par A à H
            ->orderByDesc('id')
            ->get();


        $produitoo = DB::table('produit')
            ->select(
                'id',
                DB::raw("designation_$lang as designation"),
                DB::raw("description_$lang as description"),
                'image_produit',
                'categorie_id',
                'prix',
                'etat_dispo'
            )
            ->where('etat_pub', 'Publié')
            ->where("designation_$lang", 'REGEXP', '^[Q-Zq-z]') // commence par A à H
            ->orderByDesc('id')
            ->get();


        $best = DB::table('seller')->where('qte_vendu', '>=', 1)->get();
 
        
        return view('accueil', [

            
            'categorie' => $categorie,
            'cat' => $cat,
            'produit' => $produit,
            'produito' => $produito,
            'produitoo' => $produitoo,
            'best' => $best,
           

            ]);
    }


    function login () {

        $info = DB::table('information')->get()->last();

        return view('login', [
 
            'info' => $info,

            ]);

    }


    function loginclient () {

        $info = DB::table('information')->get()->last();

        return view('client', [
 
            'info' => $info,

            ]);


    }


    function logclient ($id) {

            $info = DB::table('information')->get()->last();

            return view('login_client', [
     
                'info' => $info,

                'idprod' => $id,
    
                ]);

    }


    function reg () {
		
		$ville = DB::table('ville')->get();

        $info = DB::table('information')->get()->last();

        return view('register', [
 
            'info' => $info,

            'ville' => $ville

            ]);

    }


    function Connecter (Request $request){

        $login= request("login");
        $password=md5(request("password"));
        $user = DB::table('user')->where('login',$login)->where('password',$password )->first();
        if ($user) {
				session(['user' => $user]);


                    return redirect('/accueil_admin');
                
            }
        else{
            return redirect('/admin')
            ->with('error', 'Login ou mot de passe invalide')
            ->withInput(
                $request->except('password')
              );
        }

    }


    function Connecterclient (Request $request){

        $idproduit= request("idprod");

        $email= request("email");
        $password=md5(request("password"));
        $client = DB::table('client')->where('email',$email)->where('password',$password )->first();
        if ($client) {
				session(['client' => $client]);

                return redirect('/');
                
              }

        else{
            return redirect()->route('login_client', ['id'=>$idproduit])
            ->with('error', 'Login ou mot de passe invalide')
            ->withInput(
                $request->except('password')
              );
        }

    }


    function Conclient (Request $request){

        $email= request("email");
        $password=md5(request("password"));
        $client = DB::table('client')->where('email',$email)->where('password',$password )->first();
        if ($client) {
				session(['client' => $client]);

                return redirect()->route('compte');
                
              }

        else{
            return redirect('/client')
            ->with('error', 'Login ou mot de passe invalide')
            ->withInput(
                $request->except('password')
              );
        }

    }


    function accueil_admin () {

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

        $cmd = DB::table('commande')->get()->count();

        $scmd = DB::table('ligne_commande')->get()->sum('somligne');

        $scmdt = DB::table('ligne_commande')->where('etat1', 'Traitée')->get()->sum('somligne');

        $scmdnt = DB::table('ligne_commande')->where('etat1', 'Non traitée')->get()->sum('somligne');

        $cmdtr = DB::table('commande')->where('etat1', 'Traitée')->get()->count();

        $cmdntr = DB::table('commande')->where('etat1', 'Non traitée')->get()->count();

        $tptem = DB::table('transaction')->where('status', 'Terminé')->get()->sum('montant');

        $tpatm = DB::table('transaction')->where('status', 'En attente')->get()->sum('montant');

        $tpaiem = DB::table('transaction')->get()->sum('montant');

        $pt = DB::table('transaction')->where('status', 'Terminé')->get()->count();

        $pa = DB::table('transaction')->where('status', 'En attente')->get()->count();

        $tp = DB::table('transaction')->get()->count();

        $tcli = DB::table('client')->where('profil', 'Client')->get()->count();

        $tfou = DB::table('client')->where('profil', 'Vendeur')->get()->count();

        $tpro = DB::table('produit')->get()->count();


        return view('accueil_admin', [

            'cmd' => $cmd,
            'scmd' => $scmd,
            'cmdtr' => $cmdtr,
            'cmdntr' => $cmdntr,
            'scmdt' => $scmdt,
            'scmdnt' => $scmdnt,
            'tptem' => $tptem,
            'tpatm' => $tpatm,
            'tpaiem' => $tpaiem,
            'tp' => $tp,
            'pt' => $pt,
            'pa' => $pa,
            'tcli' => $tcli,
            'tfou' => $tfou,
            'tpro' => $tpro,
           
            ]);

    }



    function deconnecter() {

        session(['user'=>null]);
        
        return redirect('/admin');
    }


    function deconnecterclt() {

        session(['client'=>null]);
        
        return redirect('/');
    }
	function mespub()
    {
		if(session('client')== null) {
            return redirect('/');
        }
		$idcli = session('client')->id;
        $prod = DB::table('produit')->where('client_id', $idcli)->paginate(5);
 
        
        return view('mes_pub', [

            'prod' => $prod,
            'idcli' => $idcli,

            ]);
    }

	function supprimer () {

        $id=request('id');


        $veri = DB::table('offre')->where('produit_id', $id)->first();

        if( $veri){

            return redirect()->route('mes-publications')->with('error', 'Suppression impossible...Produit déja utilisée');

        }else{


            $verif = DB::table('ligne_commande')->where('produit_id', $id)->first();

            if($verif){

                return redirect()->route('mes-publications')->with('error', 'Suppression impossible...Produit déja utilisée');

            }else{

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

                return redirect()->route('mes-publications')->with('status', 'Produit supprimé avec succes');

            }

        }

    }


}
