<?php

namespace Controllers;

require_once __DIR__ . '/../Services/StripeService.php';
require_once __DIR__ . '/../Services/NSService.php';



use Services\StripeService;
use Services\NSService;
//use App\Services\NetSuiteService;
//use App\Helpers\LoggerHelper;

class WebhookController
{
    private $stripeService;
    private $netsuiteService;

    public function __construct()
    {
        $this->stripeService = new StripeService();
        $this->netsuiteService = new NSService();
    }

    public function handleWebhook($payload, $sigHeader)
    {
        try {
            // Validar la firma del evento de Stripe
            $event = $this->stripeService->validateWebhook($payload, $sigHeader);
            //LoggerHelper::log("Webhook recibido: " . $event->type);

            switch ($event->type) {
                case 'checkout.session.completed':
                    $this->processCheckoutSession($event->data->object);
                    break;
                default:
                    //LoggerHelper::log("Evento no manejado: " . $event->type);
                    break;
            }

            http_response_code(200);
        } catch (\Exception $e) {
            error_log("Error: " . $e->getMessage());

            //LoggerHelper::log("Error: " . $e->getMessage());
            http_response_code(400);
        }
    }

    private function processCheckoutSession($session)
    {
        error_log("Procesando checkout.session.completed");
        //LoggerHelper::log("Procesando checkout.session.completed");
        
        // Procesar el evento directamente
        try {
            //error_log(print_r('session: '.$session, TRUE));

            $this->netsuiteService->processSession($session);
            //LoggerHelper::log("Sesión procesada exitosamente para NetSuite: " . $session->id);
        } catch (\Exception $e) {
            error_log("Error al procesar sesión en NetSuite: " . $e->getMessage());
            error_log("Stack trace del error: " . $e->getTraceAsString());

            //LoggerHelper::log("Error al procesar sesión en NetSuite: " . $e->getMessage());
        }
    }
}
