<?php
	
add_filter('ninja_popups_subscribe_by_sendinblue', 'ninja_popups_subscribe_by_sendinblue', 10, 1);

function ninja_popups_subscribe_by_sendinblue($params = array()) 
{
    if (snp_get_option('ml_manager') != 'sendinblue') {
        return;
    }
    require_once SNP_DIR_PATH . '/include/sendinblue/vendor/autoload.php';

	$ml_sendinblue_list = $params['popup_meta']['snp_ml_sendinblue_list'][0];
    if (!$ml_sendinblue_list) {
	    $ml_sendinblue_list = (int)snp_get_option('ml_sendinblue_list');
    }


    $result = array(
		'status' => false,
		'log' => array(
			'listId' => $ml_sendinblue_list,
			'errorMessage' => '',
		)
	);
	
	if (snp_get_option('ml_sendinblue_apikey') && $ml_sendinblue_list) {

        $config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', snp_get_option('ml_sendinblue_apikey'));

        $apiInstance = new SendinBlue\Client\Api\ContactsApi(
            new GuzzleHttp\Client(),
            $config
        );

        $createContact = new \SendinBlue\Client\Model\CreateContact(); // Values to create a contact

        $createContact['email'] = snp_trim($params['data']['post']['email']);
        $createContact['listIds'] = [$ml_sendinblue_list];

        if (!empty($params['data']['post']['name'])) {
			$atributes = array(
				'FIRSTNAME' => $params['data']['names']['first'],
				'LASTNAME' => $params['data']['names']['last']
			);
		}
	
		if (count($params['data']['cf']) > 0) {
			foreach ($params['data']['cf'] as $field => $value) {
				$atributes[$field] = $value;
			}
		}
		
		$createContact->setAttributes($atributes);

        try {
            $result = $apiInstance->createContact($createContact);
            $result['status'] = true;
        } catch (Exception $e) {
            $result['log']['errorMessage'] =  $e->getMessage();
        }
    }
    
    return $result;
}