<?php
require_once __DIR__ . '/config.php';

/**
 * Make a POST call to the Mandrill API.
 *
 * Every Mandrill endpoint is POST + JSON body, and authentication
 * is just the API key passed as a field called "key" in that body.
 *
 * @param string $endpoint  e.g. "/allowlists/add"
 * @param array  $params    parameters for the call (key added automatically)
 * @return array            { endpoint, url, http_code, raw_response,
 *                            decoded, curl_error, request_body,
 *                            duration_ms }
 */
function mandrill_call(string $endpoint, array $params = []): array {
    $params['key'] = MANDRILL_API_KEY;
    $url  = MANDRILL_API_BASE . $endpoint;
    $body = json_encode($params);

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
        CURLOPT_POSTFIELDS     => $body,
        CURLOPT_TIMEOUT        => 30,
    ]);

    $t0       = microtime(true);
    $response = curl_exec($ch);
    $duration = (microtime(true) - $t0) * 1000;
    $info     = curl_getinfo($ch);
    $err      = curl_error($ch);
    curl_close($ch);

    // Redact the API key before we display the request body anywhere
    $redacted = $params;
    $redacted['key'] = '***REDACTED***';

    return [
        'endpoint'     => $endpoint,
        'url'          => $url,
        'http_code'    => (int)($info['http_code'] ?? 0),
        'raw_response' => $response,
        'decoded'      => json_decode((string)$response, true),
        'curl_error'   => $err,
        'request_body' => $redacted,
        'duration_ms'  => round($duration, 1),
    ];
}

/** Is the API key configured? */
function is_configured(): bool {
    return defined('MANDRILL_API_KEY')
        && MANDRILL_API_KEY !== 'PASTE-YOUR-API-KEY-HERE'
        && MANDRILL_API_KEY !== '';
}

/**
 * Is this recipient allowed by the optional test-recipient whitelist?
 * An empty whitelist means "no restriction".
 */
function recipient_allowed(string $email): bool {
    $list = defined('ALLOWED_TEST_RECIPIENTS') ? ALLOWED_TEST_RECIPIENTS : [];
    if (empty($list)) return true;
    return in_array(strtolower(trim($email)), array_map('strtolower', $list), true);
}

/**
 * Was the call a success? Mandrill returns HTTP 200 on success.
 * On error it returns a JSON object like:
 *   { "status": "error", "code": -1, "name": "Invalid_Key", "message": "..." }
 */
function mandrill_is_error(array $result): bool {
    if ($result['curl_error'])       return true;
    if ($result['http_code'] !== 200) return true;
    if (is_array($result['decoded'])
        && isset($result['decoded']['status'])
        && $result['decoded']['status'] === 'error') {
        return true;
    }
    return false;
}

/** Pretty-print data as JSON. */
function json_pretty($data): string {
    return json_encode(
        $data,
        JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
    );
}

/** HTML escape shortcut. */
function h(?string $s): string {
    return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}

/**
 * Render the standard "what just happened" debug panel.
 * Every demo page calls this to show exactly what went over the wire.
 */
function render_debug(array $result): void {
    $is_error = mandrill_is_error($result);
    ?>
    <div class="debug">
        <h3>What just happened?</h3>
        <p>
            <strong>POST</strong>
            <code><?= h($result['url']) ?></code>
            &mdash;
            <strong>HTTP <?= h((string)$result['http_code']) ?></strong>
            in <?= h((string)$result['duration_ms']) ?> ms
            <?= $is_error
                ? '<span class="tag tag-err">error</span>'
                : '<span class="tag tag-ok">success</span>' ?>
        </p>

        <h4>Request body (sent as JSON)</h4>
<pre><?= h(json_pretty($result['request_body'])) ?></pre>

        <h4>Response body</h4>
<pre><?= h(is_array($result['decoded'])
            ? json_pretty($result['decoded'])
            : (string)$result['raw_response']) ?></pre>

        <?php if ($result['curl_error']): ?>
            <h4>cURL error</h4>
<pre><?= h($result['curl_error']) ?></pre>
        <?php endif; ?>
    </div>
    <?php
}
