<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

/**
 * Event for module Mailchimp_observer
 *
 * @author CIEXT skeleton
 */
class Mailchimp_observer_event implements SplObserver
{

    #[\ReturnTypeWillChange]
    public function update(SplSubject $subject)
    {
        $event_name = $subject->get_event_name();
        $event_data = $subject->get_event_data();

        if ($event_name == 'add') {
            $ci = get_instance();
            $ci->load->library('ciext/configurator');
            $cnf = new configurator('newsletter');

            if (!empty($cnf->item('mailchimp_activation'))) {
                $data = $ci->newsletter_email_tmodel->fetch($event_data['id']);
                $this->save_email($cnf, $data['email']);
            }
        }
    }

    protected function save_email(\configurator $cnf, $email)
    {
        $param = $cnf->get_config();
        $re = '/[\d]+$/';

        preg_match_all($re, $param['mc_api_key'], $matches, PREG_SET_ORDER, 0);

        $link_num = (isset($matches[0][0])) ? $matches[0][0] : '';

        $url = 'https://us' . $link_num . '.api.mailchimp.com/3.0/lists/' . $param['mc_list_id'] . '/members';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $param['mc_api_key']);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        $json = json_encode([
            'email_address' => $email,
            'status'        => 'subscribed',
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);


        return ($httpCode == 200);
    }

}
