<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\PaymentIntent;

use Illuminate\Mail\Mailable;
use App\Mail\Confirmation;
use App\Mail\NotificationMail;
use Illuminate\Support\Facades\Mail;
use Srmklive\PayPal\Services\PayPal as PayPalClient;
use Illuminate\Support\Facades\Storage;



class PaymentController extends Controller
{  

	public function virbanc(Request $request)
	{

		$clientId = $request->input('idclient');
		$commandeId = $request->input('idcommande');
		$montant = $request->input('amount');
		
		$nom = DB::table('client')->where('id', $clientId)->first()->nom;
		
		$prenom = DB::table('client')->where('id', $clientId)->first()->prenom;
		
		$email = DB::table('client')->where('id', $clientId)->first()->email;


		// Stockage du fichier
		if ($request->hasFile('docu')) {
			$file = $request->file('docu');
			$path = $file->store('paiements', 'public');
			
			DB::table('transaction')->insert([
				'client_id' => $clientId,
				'commande_id' => $commandeId,
				'nom' => $nom.' '.$prenom,
				'email' => $email,
				'montant' => $montant,
				'status' => 'En attente',
				'fichier_preuve' => json_encode([$path]),
				'payment' => 'Virement bancaire',
            ]);

			 return redirect()->route('merci', ['id' => $commandeId ]);
		}

		return back()->withErrors(['docu' => 'Le reçu de virement ou capture du reçu est requis.']);
	}
	
	

    public function hpaie(Request $request)
	{

		$clientId = $request->input('idclient');
		$commandeId = $request->input('idcommande');
		$montant = $request->input('amount');
		$nom = $request->input('nom');
		$prenom = $request->input('prenom');
		$adresse = $request->input('adresse');
		$ville = $request->input('ville');
		$pays = $request->input('pays');
		$tel = $request->input('tel');
		$email = $request->input('email');

		DB::table('transaction')->insert([
			'client_id' => $clientId,
			'commande_id' => $commandeId,
			'nom' => $nom.' '.$prenom,
			'email' => $email,
			'montant' => $montant,
			'status' => 'En attente',
			'payment' => 'Espèce',
		]);
		
		DB::table('client')->where('id', $clientId)->update(

			[
				'tel' => $tel,
				'ville' => $ville,
				'pays' => $pays,
				'email' => $email,
				'adresse' => $adresse,

			]
		);

	    return redirect()->route('merci', ['id' => $commandeId ]);
		
	}
	


    public function zelpay(Request $request)
	{

		$clientId = $request->input('idclient');
		$commandeId = $request->input('idcommande');
		$montant = $request->input('amount');
        $identifiant = $request->input('identifiant');
		
		$nom = DB::table('client')->where('id', $clientId)->first()->nom;
		
		$prenom = DB::table('client')->where('id', $clientId)->first()->prenom;
		
		$email = DB::table('client')->where('id', $clientId)->first()->email;


		// Stockage du fichier
		if ($request->hasFile('docu')) {
			$file = $request->file('docu');
			$path = $file->store('paiements', 'public');
			
			DB::table('transaction')->insert([
				'client_id' => $clientId,
				'commande_id' => $commandeId,
				'nom' => $nom.' '.$prenom,
				'email' => $email,
				'montant' => $montant,
                'zelle_id' => $identifiant,
				'status' => 'En attente',
				'fichier_preuve' => json_encode([$path]),
				'payment' => 'Zelle',
            ]);

			 return redirect()->route('merci', ['id' => $commandeId ]);
		}

		return back()->withErrors(['docu' => 'La capture d\'ecran de la transaction est requise.']);
	}



    public function storeTransaction(Request $request)
    {

		$data = json_decode($request->getContent(), true);

        DB::table('transaction')->insert([

            'client_id' => $data['idclient'],
			'commande_id' => $data['idcommande'],
            'nom' => $data['payer_name'],
            'email' => $data['payer_email'],
            'montant' => $data['amount'],
            'paypal_id' => $data['payer_id'],
            'status' => $data['status'],
            'payment' => 'Paypal',
        ]);

        return response()->json(['success' => true]);
    }

   
    function choose($id) {

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

        $idcmde = $id;

        return view('payment/choisir_payement',[

            'idcmde' => $idcmde,

        ]);
    }
	
	
	function pay($id) {

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

        $idcmde = $id;

        return view('payment/payment',[

            'idcmde' => $idcmde,

        ]);
    }


    function paypal($id) {

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

        $idcmde = $id;

        return view('payment/payment-paypal',[

            'idcmde' => $idcmde,

        ]);
    }



    
    function vire($id) {

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

        $idcmde = $id;

        return view('payment/virement-bancaire',[

            'idcmde' => $idcmde,

        ]);
    }
	
	

    function horspaie($id) {

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

        $idcmde = $id;

        return view('payment/payment-hors-ligne',[

            'idcmde' => $idcmde,

        ]);
    }


    
    function zel($id) {

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

        $idcmde = $id;

        return view('payment/payment-zelle',[

            'idcmde' => $idcmde,

        ]);
    }
	
	
	
	public function createPaymentIntent(Request $request)
{
    Stripe::setApiKey(env('STRIPE_SECRET'));

    $nom = $request->name;
    $email = $request->email;
    $montant = $request->amount;
    $idclient = $request->idclient;
    $commande_id = $request->idcommande;

    $paymentIntent = \Stripe\PaymentIntent::create([
        'amount' => $montant * 100,
        'currency' => 'xaf',
        'description' => 'Paiement commande #'.$commande_id,
        'metadata' => [
            'nom' => $nom,
            'email' => $email,
            'commande_id' => $commande_id,
            'client_id' => $idclient
        ]
    ]);

    DB::table('transaction')->insert([
        'client_id' => $idclient,
        'commande_id' => $commande_id,
        'nom' => $nom,
        'email' => $email,
        'montant' => $montant,
        'stripe_id' => $paymentIntent->id,
        'status' => 'en attente',
		'payment' => 'Stripe',
    ]);
	

    return response()->json([
        'clientSecret' => $paymentIntent->client_secret
    ]);
}



    function Voirpaie ($id) {

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

        return [
            'pai' => $pai, 
        ];
    }



    function traitecmde () {

        $id=request('id');
		
		$ref = DB::table('commande')->where('id', $id)->first()->reference;
		
		$paymentId = DB::table('transaction')->where('commande_id', $id)->first()->id;
		
		$mode = DB::table('transaction')->where('id', $paymentId)->first()->payment;
		
		if( ($mode == 'Virement bancaire') || ($mode == 'Zelle') || ($mode == 'Espèce') ){
			
			$email = DB::table('transaction')->where('id', $paymentId)->first()->email;

			$nom = DB::table('transaction')->where('id', $paymentId)->first()->nom;

			$montant = DB::table('transaction')->where('id', $paymentId)->first()->montant;

			Mail::to($email)->send(new Confirmation($nom, $montant, $ref, $mode));

			DB::table('transaction')->where('id', $paymentId)->update(
				[
					'status' =>'Terminé',
				]
			);
			
		}
			
		DB::table('commande')->where('id', $id)->update(
			[
				'etat1' =>'Traitée',
			]
		);

		DB::table('ligne_commande')->where('commande_id', $id)->update(
			[
				'etat1' =>'Traitée',
			]
		);
       
        return redirect()->back()->with('status', 'Commande traitée avec succès!');

    }




    function mer($id)  {

        if(session('client')== null) {
            return redirect('/client');
        }
		
		$idc = $id ;
		
		$idcli =  session('client')->id; 
		
		$datecmde = DB::table('commande')->where('id', $idc)->first()->datecmde;

        $ref = DB::table('commande')->where('id', $idc)->first()->reference;
        
        $email = DB::table('transaction')->where('commande_id', $idc)->first()->email;

        $nom = DB::table('transaction')->where('commande_id', $idc)->first()->nom;
		
        $montant = DB::table('transaction')->where('commande_id', $idc)->first()->montant;
		
        $mode = DB::table('transaction')->where('commande_id', $idc)->first()->payment;
	
	    $email1 = 'admin@gmail.com';
	
        $seller = DB::table('ligne_commande')->where('commande_id', $idc)->get();
		
						foreach($seller as $sellers){

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

					$qteval = $sellers->qte;


					if($veri){


						$qteavt = DB::table('seller')->where('produit_id', $sellers->produit_id)->first()->qte_vendu;

						DB::table('seller')->where('produit_id', $sellers->produit_id)->update(

							[
								'qte_vendu' => $qteavt + $qteval ,

							]
						);

					}else{

						DB::table('seller')->insert(
							[
								'produit_id' => $sellers->produit_id,
								'qte_vendu' => $qteval,
								'commande_id' => $idc,

							]
						);

					}

				}

				DB::table('commande')->where('id', $idc)->update(

					[
						'etat' => 'Validé',
						'etat1' => 'Non traitée',

					]
				);

				DB::table('ligne_commande')->where('commande_id', $idc)->update(

					[
						'etat' => 'Validé',
						'etat1' => 'Non traitée',

					]
				);
				
				
		
		if(($mode == 'Virement bancaire') || ($mode == 'Zelle')){
			
			Mail::to($email1)->send(new NotificationMail());
			
			    DB::table('transaction')->where('commande_id', $idc)->update(

					[
						
						'datecmde' => $datecmde,
						'datepaie' => date('Y-m-d'),
						'heurepaie' => date('H:i:s'),

					]
				);
			
		}else{
			
			Mail::to($email)->send(new Confirmation($nom, $montant, $ref, $mode));
				
			Mail::to($email1)->send(new NotificationMail());
			
			    DB::table('transaction')->where('commande_id', $idc)->update(

					[
						'status' => 'Terminé',
						'datecmde' => $datecmde,
						'datepaie' => date('Y-m-d'),
						'heurepaie' => date('H:i:s'),

					]
				);
	
		}
		

		return view('merci',[
		
			'idcli' => $idcli,
			
			'mode' => $mode,
		  
		]);


    }
   
   
   
   
   
   
   
   
   
   
   
   
   
}
