<?php
$page_title = 'Step 7 — Create a template &amp; send with it';
require 'header.php';
?>

<p>
    This step does two things: first it <strong>creates a template</strong>
    on your account via <span class="endpoint">POST /templates/add</span>,
    then it shows how you'd use that template to send email via
    <span class="endpoint">POST /messages/send-template</span> with per-recipient
    merge variables.
</p>

<h2>Part A — Create a template</h2>

<form method="post">
    <label>Template name <small>(used to generate the slug)</small></label>
    <input type="text" name="name" required value="<?= h($_POST['name'] ?? 'demo-welcome') ?>">

    <label>Subject line</label>
    <input type="text" name="subject" required value="<?= h($_POST['subject'] ?? 'Welcome, *|FIRSTNAME|*!') ?>">

    <label>From email</label>
    <input type="email" name="from_email" required value="<?= h($_POST['from_email'] ?? DEFAULT_FROM_EMAIL) ?>">

    <label>From name</label>
    <input type="text" name="from_name" value="<?= h($_POST['from_name'] ?? DEFAULT_FROM_NAME) ?>">

    <label>HTML code <small>(use <code>*|MERGEVAR|*</code> for Mailchimp-style placeholders)</small></label>
    <textarea name="code" rows="8"><?= h($_POST['code'] ?? "<h1>Hello *|FIRSTNAME|*,</h1>\n<p>Thanks for joining us on *|SIGNUPDATE|*.</p>\n<p>Your account code: <strong>*|CODE|*</strong></p>") ?></textarea>

    <label>Publish immediately?
        <small>(templates exist as draft + published; unchecked = save draft only)</small>
    </label>
    <select name="publish">
        <option value="1" <?= ($_POST['publish'] ?? '1')==='1'?'selected':'' ?>>Yes — publish now</option>
        <option value="0" <?= ($_POST['publish'] ?? '1')==='0'?'selected':'' ?>>No — save as draft</option>
    </select>

    <button type="submit" name="run_add">Create template</button>
</form>

<?php
if (isset($_POST['run_add']) && is_configured()) {

    // --- Create-template call --------------------------------
    // Fields prefixed with "publish_" get used once you publish.
    $result = mandrill_call('/templates/add', [
        'name'       => trim($_POST['name']),
        'from_email' => trim($_POST['from_email']),
        'from_name'  => trim($_POST['from_name']),
        'subject'    => trim($_POST['subject']),
        'code'       => $_POST['code'],
        'publish'    => $_POST['publish'] === '1',
    ]);
    // ---------------------------------------------------------

    if (!mandrill_is_error($result)) {
        $slug = $result['decoded']['slug'] ?? '';
        echo '<div class="callout ok"><strong>Template created.</strong> '
           . 'Slug: <code>' . h($slug) . '</code> &mdash; use this slug when sending.</div>';
    }

    render_debug($result);
}
?>

<h2>Part B — Send using a template</h2>

<p>
    Once a template exists, you <em>don't</em> use <code>/messages/send</code>
    — you use <code>/messages/send-template</code>, which takes a template
    slug plus merge variables. The HTML and subject come from the template
    itself.
</p>

<form method="post">
    <label>Template slug <small>(from Part A, or from Step 6)</small></label>
    <input type="text" name="template_slug" required value="<?= h($_POST['template_slug'] ?? 'demo-welcome') ?>">

    <label>To address</label>
    <input type="email" name="to_email" required value="<?= h($_POST['to_email'] ?? '') ?>" placeholder="recipient@example.com">

    <label>Merge variables <small>(one per line, format: <code>NAME=value</code>)</small></label>
    <textarea name="merge_vars" rows="5"><?= h($_POST['merge_vars'] ?? "FIRSTNAME=Jane\nSIGNUPDATE=" . date('Y-m-d') . "\nCODE=ABC123") ?></textarea>

    <button type="submit" name="run_send">Send using template</button>
</form>

<?php
if (isset($_POST['run_send']) && is_configured() && !empty($_POST['to_email'])) {

    if (!recipient_allowed($_POST['to_email'])) {
        echo '<div class="callout warn"><strong>Recipient not on the test whitelist.</strong> '
           . 'Add <code>' . h($_POST['to_email']) . '</code> to <code>ALLOWED_TEST_RECIPIENTS</code> '
           . 'in <code>config.php</code>, or clear that list to allow any recipient.</div>';
        require 'footer.php';
        exit;
    }

    // --- Parse the NAME=value lines into Mandrill's shape ----
    $vars = [];
    foreach (preg_split('/\r?\n/', $_POST['merge_vars']) as $line) {
        if (strpos($line, '=') === false) continue;
        [$n, $v] = explode('=', $line, 2);
        $vars[] = ['name' => trim($n), 'content' => trim($v)];
    }

    // --- The send-template call ------------------------------
    $result = mandrill_call('/messages/send-template', [
        'template_name'    => trim($_POST['template_slug']),
        'template_content' => [],  // only used for editable regions (advanced)
        'message' => [
            'to' => [[
                'email' => trim($_POST['to_email']),
                'type'  => 'to',
            ]],
            // "merge_vars" is per-recipient; "global_merge_vars" applies to all.
            // For a single recipient, either works — using global is simplest.
            'global_merge_vars' => $vars,
            'tags'              => ['template-demo'],
        ],
    ]);
    // ---------------------------------------------------------

    if (!mandrill_is_error($result) && is_array($result['decoded'])) {
        foreach ($result['decoded'] as $r) {
            $s = $r['status'] ?? '?';
            echo '<div class="callout ' . ($s==='sent'||$s==='queued'?'ok':'warn') . '">'
               . '<strong>' . h($r['email']) . ':</strong> ' . h($s);
            if (!empty($r['reject_reason'])) echo ' — ' . h($r['reject_reason']);
            echo '</div>';
        }
    }

    render_debug($result);
}
?>

<h2>The /messages/send-template call, annotated</h2>

<pre><code>mandrill_call('/messages/send-template', [
    'template_name'    =&gt; 'welcome-email',   // the template slug
    'template_content' =&gt; [],                // for &lt;div mc:edit="..."&gt; regions
    'message' =&gt; [
        'to' =&gt; [
            ['email' =&gt; 'jane@example.com', 'type' =&gt; 'to'],
            ['email' =&gt; 'mike@example.com', 'type' =&gt; 'to'],
        ],

        // Same for every recipient
        'global_merge_vars' =&gt; [
            ['name' =&gt; 'COMPANY_NAME', 'content' =&gt; 'Acme Corp'],
        ],

        // Different per recipient (overrides globals)
        'merge_vars' =&gt; [
            [
                'rcpt' =&gt; 'jane@example.com',
                'vars' =&gt; [
                    ['name' =&gt; 'FIRSTNAME', 'content' =&gt; 'Jane'],
                ],
            ],
            [
                'rcpt' =&gt; 'mike@example.com',
                'vars' =&gt; [
                    ['name' =&gt; 'FIRSTNAME', 'content' =&gt; 'Mike'],
                ],
            ],
        ],
    ],
]);</code></pre>

<h2>Merge var syntax in the template</h2>

<p>Inside your template's HTML, reference variables with <code>*|NAME|*</code>:</p>

<pre><code>&lt;h1&gt;Hello *|FIRSTNAME|*,&lt;/h1&gt;
&lt;p&gt;Your activation code is &lt;strong&gt;*|CODE|*&lt;/strong&gt;.&lt;/p&gt;</code></pre>

<p>
    This is identical to how Mailchimp's newsletter templates work, so you
    can copy-paste between the two sides.
</p>

<p><a href="08-stats.php">→ Next: account stats &amp; recent activity</a></p>

<?php require 'footer.php'; ?>
