<?php

declare(strict_types=1);

function call_api(string $hook, array $query): array
{
    $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']) . '/router.php?hook=' . rawurlencode($hook);
    $opts = [
        'http' => [
            'method' => 'POST',
            'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
            'content' => http_build_query($query),
            'ignore_errors' => true,
        ],
    ];
    $ctx = stream_context_create($opts);
    $raw = file_get_contents($url, false, $ctx);
    if ($raw === false) {
        return ['ok' => false, 'error' => 'Request failed'];
    }
    $decoded = json_decode($raw, true);
    return is_array($decoded) ? $decoded : ['ok' => false, 'error' => 'Invalid JSON', 'raw' => $raw];
}

$message = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $op = $_POST['fixture_op'] ?? '';
    if ($op === 'save_mailshot') {
        $payload = [
            'op' => 'save',
            'id' => $_POST['id'] ?? '',
            'Purpose' => $_POST['Purpose'] ?? '',
            'DataSource' => $_POST['DataSource'] ?? '',
            'Subject' => $_POST['Subject'] ?? '',
            'Message' => $_POST['Message'] ?? '',
            'AttachmentNames' => $_POST['AttachmentNames'] ?? '[]',
            'PDFAttachment' => $_POST['PDFAttachment'] ?? '',
            'PDFFilenameDerivedFrom' => $_POST['PDFFilenameDerivedFrom'] ?? '',
            'ReplyTo' => $_POST['ReplyTo'] ?? '',
        ];
        $message = call_api('admin_post_feca_mailshots_mailshots_api', $payload);
    }
    if ($op === 'delete_mailshot') {
        $message = call_api('admin_post_feca_mailshots_mailshots_api', ['op' => 'delete', 'id' => $_POST['id'] ?? '0']);
    }
}

$dataSources = call_api('admin_post_feca_mailshots_mailshots_api', ['op' => 'data_sources']);
$mailshots = call_api('admin_post_feca_mailshots_mailshots_api', ['op' => 'list']);
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Mailshots Fixture UI</title>
  <style>
    body { font-family: Georgia, "Times New Roman", serif; background: #f7f6f0; color: #222; margin: 24px auto; max-width: 1200px; padding: 0 16px 40px; }
    .card { background: #fffef9; border: 1px solid #d7d4c6; padding: 14px; margin-bottom: 12px; }
    input, textarea, select { width: 100%; box-sizing: border-box; margin-bottom: 8px; padding: 6px; }
    textarea { min-height: 90px; }
    table { width: 100%; border-collapse: collapse; }
    th, td { border: 1px solid #ddd9c8; padding: 6px 8px; vertical-align: top; }
    pre { background: #f3f1e6; border: 1px solid #ddd9c8; padding: 10px; overflow: auto; }
  </style>
</head>
<body>
  <h1>Mailshots Fixture UI</h1>

  <?php if ($message !== null): ?>
    <div class="card"><strong>API response</strong><pre><?php echo htmlspecialchars(json_encode($message, JSON_PRETTY_PRINT)); ?></pre></div>
  <?php endif; ?>

  <div class="card">
    <h2>Create / Update Mailshot</h2>
    <form method="post">
      <input type="hidden" name="fixture_op" value="save_mailshot">
      <label>ID (blank for create)</label>
      <input name="id" value="">
      <label>Purpose</label>
      <input name="Purpose" value="">
      <label>DataSource</label>
      <select name="DataSource">
        <option value="">-- select --</option>
        <?php foreach (($dataSources['items'] ?? []) as $ds): ?>
          <option value="<?php echo htmlspecialchars((string) $ds); ?>"><?php echo htmlspecialchars((string) $ds); ?></option>
        <?php endforeach; ?>
      </select>
      <label>Subject</label>
      <input name="Subject" value="">
      <label>Message (HTML)</label>
      <textarea name="Message"></textarea>
      <label>PDF Attachment (HTML)</label>
      <textarea name="PDFAttachment"></textarea>
      <label>AttachmentNames JSON</label>
      <input name="AttachmentNames" value="[]">
      <label>PDFFilenameDerivedFrom</label>
      <input name="PDFFilenameDerivedFrom" value="">
      <label>ReplyTo</label>
      <input name="ReplyTo" value="">
      <button type="submit">Save mailshot</button>
    </form>
  </div>

  <div class="card">
    <h2>Current Mailshots</h2>
    <table>
      <thead><tr><th>ID</th><th>Purpose</th><th>DataSource</th><th>Subject</th><th>Delete</th></tr></thead>
      <tbody>
      <?php foreach (($mailshots['items'] ?? []) as $row): ?>
        <tr>
          <td><?php echo htmlspecialchars((string) ($row['id'] ?? '')); ?></td>
          <td><?php echo htmlspecialchars((string) ($row['Purpose'] ?? '')); ?></td>
          <td><?php echo htmlspecialchars((string) ($row['DataSource'] ?? '')); ?></td>
          <td><?php echo htmlspecialchars((string) ($row['Subject'] ?? '')); ?></td>
          <td>
            <form method="post">
              <input type="hidden" name="fixture_op" value="delete_mailshot">
              <input type="hidden" name="id" value="<?php echo htmlspecialchars((string) ($row['id'] ?? '0')); ?>">
              <button type="submit">Delete</button>
            </form>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</body>
</html>
