<?php
include '../config/config.php';

echo "<h2>Mailchimp Marketing API Test</h2>";

// 1. Data from your previous message
$audience_id = '56dba538c1'; 
$test_email = '12isurukumarasiri@gmail.com'; 

// 2. Correct URL structure for the Marketing API
// We use the 'members' endpoint to add a contact to your list
$url = "https://" . MAILCHIMP_SERVER . ".api.mailchimp.com/3.0/lists/$audience_id/members/";

$data = [
    "email_address" => $test_email,
    "status" => "subscribed", 
    "merge_fields" => [
        "FNAME" => "Isuru",
        "LNAME" => "Kumarasiri"
    ]
];

$options = [
    'http' => [
        'header'  => "Content-type: application/json\r\n" .
                     "Authorization: Basic " . base64_encode("user:" . MAILCHIMP_API_KEY) . "\r\n",
        'method'  => 'POST',
        'content' => json_encode($data),
        'ignore_errors' => true
    ],
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false,
    ]
];

$context = stream_context_create($options);

echo "Attempting to add <b>$test_email</b> to Audience ID: <b>$audience_id</b>...<br>";

$response = @file_get_contents($url, false, $context);
$headers = $http_response_header;

echo "<h4>Mailchimp API Response:</h4><pre>";
echo htmlspecialchars($response);
echo "</pre>";

// Check for 200 (Success) or 400 (Member already exists - also technically a success for testing)
if (isset($headers[0]) && (strpos($headers[0], '200') !== false)) {
    echo "<div style='padding:15px; background:green; color:white; font-weight:bold;'>SUCCESS: Contact added to Mailchimp list!</div>";
} elseif (strpos($response, 'Member Exists') !== false) {
    echo "<div style='padding:15px; background:blue; color:white; font-weight:bold;'>INFO: Contact already exists in the list (Connection is Working).</div>";
} else {
    echo "<div style='padding:15px; background:red; color:white; font-weight:bold;'>FAILED: Check the error details above.</div>";
}
?>