<?php

require_once __DIR__ . "/../../../vendor/autoload.php";

$json = [];
try {
    $consumerKey = \Intgrtn\Lib\Common::request("consumerKey");
    $consumerSecret = \Intgrtn\Lib\Common::request("consumerSecret");
    $accessKey = \Intgrtn\Lib\Common::request("accessKey");
    $accessSecret = \Intgrtn\Lib\Common::request("accessSecret");

    $list = \Intgrtn\Lib\Common::request("list");

    $email = \Intgrtn\Lib\Common::request("email");
    $name = \Intgrtn\Lib\Common::request("name");
    $ip = \Intgrtn\Lib\Common::request("ip");
    $customFields = \Intgrtn\Lib\Common::request("customFields", []);

    if (empty($consumerKey)) {
        throw new ErrorException("Enter consumerKey");
    }
    if (empty($consumerSecret)) {
        throw new ErrorException("Enter consumerSecret");
    }
    if (empty($accessKey)) {
        throw new ErrorException("Enter accessKey");
    }
    if (empty($accessSecret)) {
        throw new ErrorException("Enter accessSecret");
    }
    if (empty($list)) {
        throw new ErrorException("Enter list");
    }
    if (empty($email)) {
        throw new ErrorException("Enter email");
    }

    try {
        $aweber = new AWeberAPI($consumerKey, $consumerSecret);
        $account = $aweber->getAccount($accessKey, $accessSecret);
        $newSubscriber = null;
        $lists = $account->lists->find(array('name' => $list));
        if (!isset($lists[0])) {
            throw new ErrorException("Aweber list not found");
        }

        $params = array(
            'email' => $email,
            'name' => $name,
            'ip_address' => $ip,
            'custom_fields' => $customFields
        );
        $subscribers = $lists[0]->subscribers;
        $newSubscriber = $subscribers->create($params);
    } catch (AWeberAPIException $exc) {
        throw new ErrorException($exc->getMessage());
    }

    $json['data'] = [
        "aweber" => [
            "response" => $newSubscriber
        ]
    ];
    $json['message'] = "Success";
} catch (ErrorException $exc) {
    http_response_code(400);
    $json['message'] = $exc->getMessage();
}

header('Content-Type: application/json');
echo json_encode($json);
