<?php

namespace App\Services;

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use App\Services\ChargeAngelsApi;

class EmailService
{
    public function __construct(
        private MailerInterface $mailer,
        private ChargeAngelsApi $client,
        private ParameterBagInterface $params
    ){}
    public function startChargeEmail(string $to, array $data){

        $dataToMail = [];
        $dataToMail['pin']=$this->getPin($data);
        $dataToMail['id']=$data['id'];
        $dataToMail['connectorId']=$data['connectorId'];
        $dataToMail['url']=$data['url'];
        $dataToMail['mail']=$to;

        $email = (new TemplatedEmail())
            ->from('nepasrepondrelodmi@gmail.com')
            ->to(new Address($to))
            ->subject('Lodmi - Session démarée')

            // path of the Twig template to render
            ->htmlTemplate('emails/startCharge.html.twig')

            // pass variables (name => value) to the template
            ->context($dataToMail);
        try {
            $this->mailer->send($email);
            return $dataToMail;
        } catch (TransportExceptionInterface $e) {
            // some error prevented the email sending; display an
            // error message or try to resend the message
            return null;
        }
    }
    public function stopChargeEmail(string $to, array $data):array|null|string{
        $response = $this->client->infoCharge($data['idCharge']);
//        dump($response);
        $stripe = new \Stripe\StripeClient($this->params->get('stripe_secret'));
        $res = $stripe->paymentIntents->search(['query' => 'metadata[\'chargeId\']:\''.$data['idCharge'].'\'']);
        dump( $data['idCharge'],$res);
        if(count($res->data)>0){
            $intent = $stripe->paymentIntents->retrieve($res->data[0]->id);
            $intent->capture(['amount_to_capture' => $response['stop']['roundedPrice']*100]);
        }
        $seconds = $response['stop']['totalDurationSecs'];
        $dataToView = [
            'time'=>sprintf('%02d:%02d:%02d', ($seconds/ 3600),($seconds/ 60 % 60), $seconds% 60),
            'conso'=>$response['stop']['totalConsumptionWh']/1000,
            'price'=>$response['stop']['roundedPrice'],
            'code'=>$data['idCharge'],
            'borne'=>$data['idBorne'],
        ];
        $email = (new TemplatedEmail())
            ->from('nepasrepondrelodmi@gmail.com')
            ->to(new Address($res->data[0]->metadata->email))
            ->subject('Lodmi - Session terminée')

            // path of the Twig template to render
            ->htmlTemplate('emails/stopCharge.html.twig')

            // pass variables (name => value) to the template
            ->context($dataToView);
        try {
            $this->mailer->send($email);
            return $response;
        } catch (TransportExceptionInterface $e) {
            // some error prevented the email sending; display an
            // error message or try to resend the message
            return null;
        }
    }
    private function getPin(array $data){
        $infoResponse = $this->client->request(Request::METHOD_GET, sprintf('/api/transactions/status/active?ChargingStationID='.$data['id'].'&ConnectorId='.$data['connectorId'].'&Limit=1', ));
        $info = json_decode($infoResponse->getContent(), true);
        $ret='123456';
        if($info['result']){
            if (count($info['result'])<1){
                $this->getPin($data);
            }else{
                $ret=$info['result'][0]['id'];
            }
        }else{
            $this->getPin($data);
        }

        return $ret;
    }
}
