<?php

namespace Myvetshop\Module\Clinique\Prestashop\Hook;

use Myvetshop\Module\Clinique\Adapter\ConfigurationAdapter;
use Myvetshop\Module\Clinique\Adapter\Hook\ActionObjectCustomerAddAfterInterface;
use Myvetshop\Module\Clinique\Adapter\Hook\ActionObjectCustomerUpdateAfterInterface;

class PhplistListener implements ActionObjectCustomerAddAfterInterface, ActionObjectCustomerUpdateAfterInterface
{
    private ConfigurationAdapter $configurationAdapter;

    public function __construct(
        ConfigurationAdapter $configurationAdapter
    ) {
        $this->configurationAdapter = $configurationAdapter;
    }

    public function actionObjectCustomerAddAfter(\Customer $customer): void
    {
        $this->syncCustomerWithPhpList($customer);
    }

    public function actionObjectCustomerUpdateAfterInterface(\Customer $customer): void
    {
        $this->syncCustomerWithPhpList($customer);
    }

    private function syncCustomerWithPhpList(\Customer $customer): void
    {
        $phplistUrl = $this->configurationAdapter->get('MYVETSHOPCLINIQUE_PHPLIST_URL');

        if (!$phplistUrl) {
            return;
        }

        $curl = \curl_init();
        \curl_setopt($curl, \CURLOPT_URL, $phplistUrl . '/lists/?pi=myvetshop&p=syncfromprestashop');
        \curl_setopt($curl, \CURLOPT_TIMEOUT, 30);
        \curl_setopt($curl, \CURLOPT_RETURNTRANSFER, 1);
        \curl_setopt($curl, \CURLOPT_SSL_VERIFYPEER, false);
        \curl_setopt($curl, \CURLOPT_SSL_VERIFYHOST, false);
        \curl_setopt($curl, \CURLOPT_POST, 1);
        \curl_setopt(
            $curl,
            \CURLOPT_POSTFIELDS,
            [
                'email' => $customer->email,
                'newsletter' => $customer->newsletter,
                'optin' => $customer->optin,
                'firstname' => $customer->firstname,
                'lastname' => $customer->lastname,
            ]
        );
        \curl_exec($curl);
    }
}
