<?php


namespace Plugins\StripePlugin;

/* * *
 * Utilitaire pour strip
 */

class StripeHelper {
    /*     * *
     * Initialisation de class Stripe avec les bonne clés
     */

    public static function InitStripe($core, $privateKey) {

        require_once("../Library/autoload.php");
        spl_autoload_register('stripe_autoloader');

        \Stripe\Stripe::setCABundlePath("/etc/ssl/certs/apache-selfsigned.crt");

        \Stripe\Stripe::setVerifySslCerts(false);

        // For sample support and debugging. Not required for production:
        \Stripe\Stripe::setAppInfo(
                "stripe-samples/accept-a-payment/payment-element",
                "0.0.2",
                "https://github.com/stripe-samples"
        );

        $stripe = new \Stripe\StripeClient([
            'api_key' => (string) $privateKey,
            'stripe_version' => '2020-08-27',
        ]);

        return $stripe;
    }

    /*     * *
     * Création d'un session de paiement
     */

    public static function CreatePaidSession($core, $privateKey,  $mount) {

        $stripe = self::InitStripe($core, $privateKey);

        $paymentIntent = $stripe->paymentIntents->create([
            'automatic_payment_methods' => ['enabled' => true],
            'amount' => ($mount * 100),
            'currency' => 'eur',
        ]);

        return $paymentIntent->client_secret;
    }



    /**
     * Création d'un 
     */
    public static function CreatePaymentIntent($core, $data, $userId) {

       
        ini_set('display_errors', 1);
        error_reporting(E_ERROR);

        $stripe = self::InitStripe($core);

        // Récupérer le token envoyé depuis le front-end
        $token = $data['stripToken'];

        try {
            // Créer un PaymentIntent
            $paymentIntent = $stripe->paymentIntents->create([
                'amount' => (int)($data["Total"]  * 100 ), // Montant en centimes (ici 50,00€)
                'currency' => 'eur',
                'payment_method' => $token,
                'confirmation_method' => 'manual',
                'confirm' => true, // Confirmer immédiatement pour déclencher le 3D Secure si nécessaire
            ]);

            if ($paymentIntent->status === 'requires_action' && $paymentIntent->next_action->type === 'use_stripe_sdk') {
                // Si une action 3D Secure est requise, retourner les informations au front-end
                return json_encode([
                    'requiresAction' => true,
                    'paymentIntentId' => $paymentIntent->id,
                    'clientSecret' => $paymentIntent->client_secret
                ]);
            } else if ($paymentIntent->status === 'succeeded') {
                // Paiement réussi
                return true;
              
            }
        } catch (\Stripe\Exception\ApiErrorException $e) {
            // Gérer les erreurs d'API Stripe
            return json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }

    public static function finalizePaiement($core, $data) {
         $stripe = self::InitStripe($core);

// Récupérer l'ID du PaymentIntent
        $paymentIntentId = $data['paymentIntentId'];

        try {
            // Confirmer le PaymentIntent
            $paymentIntent = $stripe->paymentIntents->retrieve($paymentIntentId);
            $paymentIntent->confirm();

            if ($paymentIntent->status === 'succeeded') {
                // Paiement confirmé
                //return json_encode(['status' => 'succeeded']);
                return true;
            } else {
                // Paiement échoué
                return json_encode(['status' => 'failed']);
            }
        } catch (\Stripe\Exception\ApiErrorException $e) {
            // Gérer les erreurs d'API Stripe
            return json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }
}
