<?php

ini_set('display_errors', '1');
error_reporting(E_ALL);

/*
 * IMPORTANT:
 * Revoke the API key you pasted publicly and create a new one.
 */
$apiKey = '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';

$payload = [
    'personalizations' => [
        [
            'to' => [
                [
                    'email' => 'chigubhujethro5@gmail.com',
                    'name'  => 'Jethro Chigubhu'
                ]
            ]
        ]
    ],
    'from' => [
        'email' => 'mchigubhu@macsoftlabs.com',
        'name'  => 'Macsoft Labs'
    ],
    'subject' => 'SendGrid PHP Test',
    'content' => [
        [
            'type'  => 'text/plain',
            'value' => 'This is a SendGrid test email.'
        ],
        [
            'type'  => 'text/html',
            'value' => '<strong>This is a SendGrid test email.</strong>'
        ]
    ]
];

$json = json_encode($payload);

if ($json === false) {
    exit('Could not encode SendGrid payload: ' . json_last_error_msg());
}

$ch = curl_init('https://api.sendgrid.com/v3/mail/send');

curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json'
    ],
    CURLOPT_POSTFIELDS => $json,
    CURLOPT_TIMEOUT => 60,
    CURLOPT_CONNECTTIMEOUT => 20
]);

$response = curl_exec($ch);

if ($response === false) {
    $error = curl_error($ch);
    curl_close($ch);
    exit('cURL error: ' . htmlspecialchars($error, ENT_QUOTES, 'UTF-8'));
}

$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

$responseHeaders = substr($response, 0, $headerSize);
$responseBody = substr($response, $headerSize);

curl_close($ch);

echo '<pre>';
echo 'HTTP Status: ' . $statusCode . PHP_EOL . PHP_EOL;
echo 'Headers:' . PHP_EOL;
echo htmlspecialchars($responseHeaders, ENT_QUOTES, 'UTF-8');
echo PHP_EOL . 'Body:' . PHP_EOL;
echo htmlspecialchars($responseBody, ENT_QUOTES, 'UTF-8');
echo '</pre>';