<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: accept, origin, content-type, authorization, Cache-Control, X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Content-Type: application/json');

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

$name = \Intgrtn\Lib\Common::request("name");
$email = \Intgrtn\Lib\Common::request("email");
$listID = \Intgrtn\Lib\Common::request("listID");
$apiKey = \Intgrtn\Lib\Common::request("apiKey");
$hashKey = \Intgrtn\Lib\Common::request("hashKey");
$subdomain = \Intgrtn\Lib\Common::request("subdomain");
$apiUrl = "https://$subdomain.sendlane.com/api/v1/list-subscriber-add";


try {

    if(empty($name)) {
        throw new Exception("Name is required");
    }

    if(empty($email)) {
        throw new Exception("Email is required");
    }

    if(empty($listID)) {
        throw new Exception("listID is required");
    }

    if(empty($apiKey)) {
        throw new Exception("apiKey is required");
    }

    if(empty($hashKey)) {
        throw new Exception("hashKey is required");
    }

    if(empty($subdomain)) {
        throw new Exception("subdomain is required");
    }

    $api_params = array(
        'api' => $apiKey,
        'hash' => $hashKey
    );

    $params = array(
        'api' => $apiKey,
        'hash' => $hashKey,
        'email' => $email,
        'list_id' => $listID,
        'name' => $name
    );


    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl . '?' . http_build_query($api_params));
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
    $result = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    echo json_encode(['status' => 'success']);
} catch (Exception $e) {
    echo json_encode(['status' => 'failed', 'message' => $e->getMessage()]);
//    $filename = __DIR__ . '/error-autoresponder.log';
//    $array["date"] = date("Y-m-d H:i:s");
//    $array["post"] = $_POST;
//    $array["get"] = $_GET;
//    $array["session"] = $_SESSION;
//    $array["request"] = $_REQUEST;
//    $array["error"] = $e->getMessage();
//    $logoutLog = json_encode($array) . "\n\n";
//    file_put_contents($filename, $logoutLog, FILE_APPEND);
//    echo json_encode(['status' => 'failed']);
}


