<?php

namespace Daniv04\HaciendaPackage\Providers\Cyberfuel;

use DateTime;
use Daniv04\HaciendaPackage\Providers\Contracts\ProviderInterface;
use Daniv04\HaciendaPackage\Providers\Cyberfuel\Transformer\CyberfuelTransformer;
use Daniv04\HaciendaPackage\Traits\DateParserTrait;
use Daniv04\HaciendaPackage\Traits\GenerateSecurityCode;
use Illuminate\Support\Facades\Http;


class CyberfuelProvider implements ProviderInterface
{
    use DateParserTrait;
    use GenerateSecurityCode;
    
    public function sendDocument(array $payload, string $consecutiveNumber): array
    {
        $date = $payload['Encabezado']['FechaEmision'] ?? (new DateTime())->format('Y-m-d\TH:i:sP');
        $dateParsed = $this->parseDateToArray($date);
        $securityCode = $this->generateSecurityCode($consecutiveNumber . $date);

        if(in_array($payload['Clave']['TipoComprobante'] ?? '', ['05', '06', '07']))
        {
            $transformedData = CyberfuelTransformer::transformSentDocument($payload, $consecutiveNumber, $dateParsed, $securityCode);
        }
        else
        {
             $transformedData = CyberfuelTransformer::transformDocument($payload, $consecutiveNumber, $dateParsed, $securityCode);
        }

        $baseUrl = config('cyberfuel.api_base_url_stag');
        $methodUrl = config('cyberfuel.makeXml_url_stag');
        $url = $baseUrl . $methodUrl;
        try
        {
            $response =  Http::post($url, $transformedData); 

            if (!$response->successful()) 
            {
                return [
                    'success' => false,
                    'message' => 'Provider error Http on: ' . $response->status(),
                    'errors' => [$response->body()],
                ];
            } 

            $responseData = $response->json();
            $code = $response->json('code');
        

            if($code === "1")
            {
                return [
                    'success' => true,
                    'message' => 'Document sent successfully to Cyberfuel',
                    'data' => $responseData,
                ];
            }

            return [
                'success' => false,
                'message' => 'Error on sending the document',
                'errors' => $responseData,
            ];


            
        }catch (\Exception $e)
        {
            return [
                'success' => false,
                'message' => 'Exception on sending the document: ' . $e->getMessage(),
                'errors' => [$e->getTraceAsString()],
            ];
        }

    }

    

    public function getDocumentStatus(string $key): array
    {
        // TODO: implementar consulta de estado en Cyberfuel
        return [];
    }

    public function getName(): string
    {
        return 'cyberfuel';
    }
}