<?php
declare(strict_types=1);

header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

 $cfg = require __DIR__ . '/../../blogger_api/config.php';
 require_once __DIR__ . '/../../blogger_api/social/SocialService.php';
$tenantsDir = rtrim((string)($cfg['tenants_dir'] ?? '/home/mytown/blog.mytown.ink/tenants'), '/');

function read_json(string $path): ?array {
  if (!is_file($path)) return null;
  $raw = file_get_contents($path);
  if ($raw === false) return null;
  $d = json_decode($raw, true);
  return is_array($d) ? $d : null;
}

function api_base_url(): string {
  $raw = $_ENV['BLOGGER_API_BASE_URL'] ?? getenv('BLOGGER_API_BASE_URL') ?? '';
  return $raw === '' ? 'https://api.blogger.mytown.ink' : rtrim($raw, '/');
}

$ref = trim((string)($_GET['ref'] ?? ''));
$validRef = preg_match('/^t_[a-f0-9]{16}$/', $ref);
$tenantDir = $validRef ? ($tenantsDir . '/' . $ref) : '';
$active = ($validRef && is_dir($tenantDir)) ? read_json($tenantDir . '/active.json') : null;
$status = is_array($active) ? strtolower((string)($active['status'] ?? '')) : '';
$token  = is_array($active) && is_array($active['download'] ?? null) ? (string)($active['download']['token'] ?? '') : '';
$isActive = ($status === 'active' && $token !== '');

 $draftDir = ($validRef && is_dir($tenantDir . '/drafts')) ? $tenantDir . '/drafts' : '';
 $drafts = [];
if ($draftDir !== '') {
  $files = glob($draftDir . '/*.json') ?: [];
  foreach ($files as $file) {
    $data = read_json($file);
    if (!is_array($data)) continue;
    $drafts[] = $data;
  }
  usort($drafts, fn($a, $b) => strcmp($b['created_at'] ?? '', $a['created_at'] ?? ''));
}

$openaiDataFile = ($validRef && is_dir($tenantDir . '/data')) ? ($tenantDir . '/data/openai.json') : '';
$openaiConfigured = $openaiDataFile !== '' && is_file($openaiDataFile);
$apiBase = api_base_url();
$helpLinks = [
  'OpenAI key guide' => 'https://blogger.mytown.ink/docs/support/OpenAI_Key_Guide.md',
  'Help center / FAQ' => 'https://blogger.mytown.ink/docs/docs/support/09_Support_Playbook.md',
];

$supportEmail = 'support@mytown.ink';
$whatsAppNumber = '+27820012345';
$supportMessage = urlencode("Tenant ref {$ref} needs help with the Option 2 flow.");

$socialService = $validRef ? new SocialService($cfg) : null;
$socialStatus = ['linkedin' => false, 'facebook' => false];
$lastSocialJob = null;
if ($socialService) {
  $socialStatus = $socialService->connectedProviders($ref);
  $lastSocialJob = $socialService->lastJob($ref);
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>Blogger Kit status</title>
  <style>
    :root {
      font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
      color: #0f172a;
      background: #f8fafc;
    }
    body {
      max-width: 1040px;
      margin: 0 auto;
      padding: 24px;
    }
    h1 {
      margin-top: 0;
    }
    .grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
      gap: 16px;
    }
    .card {
      background: #fff;
      border-radius: 18px;
      border: 1px solid #e5e7eb;
      padding: 20px;
      box-shadow: 0 20px 45px -25px rgba(15, 23, 42, 0.35);
    }
    .card h2 {
      margin-top: 0;
    }
    .muted {
      color: #475569;
    }
    .btn {
      border: 0;
      background: #111827;
      color: #fff;
      padding: 10px 16px;
      border-radius: 12px;
      font-weight: 700;
      cursor: pointer;
      font-size: 0.95rem;
    }
    .btn.secondary {
      background: #e5e7eb;
      color: #111827;
      margin-left: 8px;
    }
    .badge {
      display: inline-flex;
      padding: 4px 10px;
      border-radius: 999px;
      font-size: 0.85rem;
      font-weight: 600;
      background: #e2e8f0;
      color: #0f172a;
    }
    label {
      display: block;
      font-weight: 600;
      margin-bottom: 6px;
    }
    input[type="text"],
    input[type="password"],
    textarea {
      width: 100%;
      padding: 10px 12px;
      border-radius: 10px;
      border: 1px solid #cbd5f5;
      font-size: 1rem;
      margin-bottom: 12px;
      font-family: inherit;
      background: #f9fafb;
    }
    table {
      width: 100%;
      border-collapse: collapse;
      font-size: 0.95rem;
    }
    th, td {
      padding: 12px 8px;
      text-align: left;
      border-bottom: 1px solid #e2e8f0;
    }
    th { text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.06em; color: #64748b; }
    .status-generated { color: #0f172a; }
    .status-published { color: #15803d; }
    .status-failed { color: #b91c1c; }
    .floating-support {
      position: fixed;
      bottom: 24px;
      right: 24px;
      display: flex;
      flex-direction: column;
      gap: 10px;
    }
    .support-btn {
      background: #0ea5e9;
      color: #fff;
      border-radius: 999px;
      padding: 12px 16px;
      text-decoration: none;
      font-weight: 700;
      display: inline-flex;
      align-items: center;
      gap: 8px;
      box-shadow: 0 10px 25px rgba(14, 165, 233, 0.35);
    }
    .support-btn.secondary {
      background: #059669;
    }
    .status-message {
      margin-top: 12px;
      font-size: 0.9rem;
    }
    .links a {
      display: inline-flex;
      margin-right: 12px;
      color: #0f172a;
      text-decoration: none;
      font-weight: 600;
    }
    .social-card {
      display: flex;
      flex-direction: column;
    }
    .social-providers {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
      gap: 12px;
      margin-top: 16px;
    }
    .social-provider {
      padding: 12px;
      border: 1px dashed #cbd5f5;
      border-radius: 12px;
      background: #f8fafc;
    }
    .social-provider .coming-soon {
      font-size: 0.8rem;
      color: #0ea5e9;
      display: inline-flex;
      align-items: center;
      gap: 6px;
    }
    .social-provider .small-note {
      font-size: 0.85rem;
      color: #475569;
    }
    .flex {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 12px;
    }
  </style>
</head>
<body>
  <header>
    <h1>Blogging workspace</h1>
    <p class="muted">Tenant <code><?= htmlspecialchars($ref) ?></code></p>
  </header>

  <?php if (!$validRef): ?>
    <div class="card">
      <p class="muted">Please open this page with the link sent after checkout.</p>
    </div>
  <?php elseif (!$isActive): ?>
    <div class="card">
      <h2>Status</h2>
      <p class="muted">We are still waiting for the webhook to finish. Refresh after a minute.</p>
      <p class="muted">Ref: <code><?= htmlspecialchars($ref) ?></code></p>
    </div>
  <?php else: ?>
    <section class="grid">
      <div class="card">
        <h2>Kit download</h2>
        <p class="muted">Your download token is one-time. Refresh this page after each download.</p>
        <button class="btn" id="downloadBtn">Download kit</button>
        <button class="btn secondary" id="refreshBtn" type="button">Refresh</button>
      </div>

      <div class="card">
        <h2>OpenAI key</h2>
        <p class="muted">
          <?= $openaiConfigured ? 'Key saved (encrypted) ‒ you can replace it any time.' : 'No key yet. Save your OpenAI key to enable content generation.' ?>
        </p>
        <label for="openaiKey">OpenAI API key</label>
        <input type="password" id="openaiKey" placeholder="sk-..." />
        <div>
          <button class="btn" id="saveKeyBtn">Save key</button>
          <button class="btn secondary" id="testKeyBtn" type="button">Test key</button>
          <button class="btn secondary" id="deleteKeyBtn" type="button">Delete key</button>
        </div>
        <p class="status-message" id="openaiKeyStatus"></p>
      </div>
    </section>

    <section class="card">
      <h2>Generate post</h2>
      <p class="muted">
        Enter a topic or short prompt. OpenAI will craft a draft, then click preview/approve in the list below.
      </p>
      <label for="topicInput">Topic or prompt</label>
      <input type="text" id="topicInput" placeholder="e.g. 5 tips to boost local SEO" />
      <label for="titleInput">Title (optional)</label>
      <input type="text" id="titleInput" placeholder="Optional headline override" />
      <button class="btn" id="generateBtn">Generate draft</button>
      <p class="status-message" id="generateStatus"></p>
    </section>

    <section class="card">
      <div class="flex">
        <h2>Drafts</h2>
        <?php if (empty($drafts)): ?>
          <p class="muted">No drafts yet. Generate once to see them here.</p>
        <?php endif; ?>
      </div>
      <?php if (!empty($drafts)): ?>
        <table>
          <thead>
            <tr>
              <th>Created</th>
              <th>Title</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($drafts as $draft): ?>
              <?php
                $status = strtolower((string)($draft['status'] ?? 'generated'));
                $previewUrl = $apiBase . '/content/preview.php?ref=' . urlencode($ref) . '&draft=' . urlencode((string)($draft['draft_id'] ?? '')) . '&token=' . urlencode((string)($draft['preview_token'] ?? ''));
                $approveToken = (string)($draft['approve_token'] ?? '');
                $createdAt = htmlspecialchars((string)($draft['created_at'] ?? ''), ENT_QUOTES);
              ?>
              <tr data-draft-id="<?= htmlspecialchars((string)($draft['draft_id'] ?? '')) ?>" data-preview-url="<?= htmlspecialchars($previewUrl, ENT_QUOTES) ?>" data-approve-token="<?= htmlspecialchars($approveToken, ENT_QUOTES) ?>">
                <td><?= $createdAt ? date('M j, Y H:i', strtotime($createdAt)) : 'n/a' ?></td>
                <td><?= htmlspecialchars((string)($draft['title'] ?? 'Untitled')) ?></td>
                <td class="status-<?= htmlspecialchars($status) ?>">
                  <span class="badge"><?= htmlspecialchars(ucfirst($status)) ?></span>
                  <?php if (isset($draft['wp_link']) && $draft['wp_link'] !== ''): ?>
                    <div><a href="<?= htmlspecialchars($draft['wp_link'], ENT_QUOTES) ?>" target="_blank" rel="noreferrer">View live post</a></div>
                  <?php endif; ?>
                </td>
                <td>
                  <button class="btn secondary previewBtn" type="button">Preview</button>
                  <?php if ($status !== 'published' && $approveToken !== ''): ?>
                    <button class="btn approveBtn" type="button">Approve</button>
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      <?php endif; ?>
      </section>

    <section class="card social-card">
      <h2>Social posting (coming soon)</h2>
      <p class="muted">Connect LinkedIn and Facebook to queue posts based on your drafts in the future.</p>
      <div class="social-providers">
        <?php
        $socialLabels = ['linkedin' => 'LinkedIn', 'facebook' => 'Facebook'];
        foreach ($socialLabels as $id => $label):
          $connected = $socialStatus[$id] ?? false;
        ?>
          <div class="social-provider">
            <div class="badge <?= $connected ? 'status-published' : 'status-generated' ?>">
              <?= $connected ? 'Connected' : 'Not connected' ?>
            </div>
            <p class="muted">Provider: <?= htmlspecialchars($label) ?></p>
            <button class="btn secondary" type="button" disabled>Connect <?= htmlspecialchars($label) ?></button>
            <span class="coming-soon">Coming soon</span>
            <p class="small-note"><?= $connected ? 'Key/token stored and encrypted.' : 'Save credentials via the API when available.' ?></p>
          </div>
        <?php endforeach; ?>
      </div>
      <?php if ($lastSocialJob): ?>
        <?php
          $jobTime = isset($lastSocialJob['created_at']) ? date('M j, Y H:i', strtotime($lastSocialJob['created_at'])) : 'unknown time';
          $jobProvider = htmlspecialchars((string)($lastSocialJob['provider'] ?? ''));
          $jobStatus = htmlspecialchars((string)($lastSocialJob['status'] ?? ''));
          $jobDraft = htmlspecialchars((string)($lastSocialJob['draft_id'] ?? ''));
        ?>
        <p class="muted">Last queued job: <?= $jobProvider ?> · draft <?= $jobDraft ?> · <?= $jobStatus ?> at <?= $jobTime ?></p>
      <?php endif; ?>
    </section>

    <section class="card links">
      <h2>Need help?</h2>
      <p class="muted">Check the docs or contact support for a walkthrough.</p>
      <?php foreach ($helpLinks as $label => $link): ?>
        <a href="<?= htmlspecialchars($link, ENT_QUOTES) ?>" target="_blank" rel="noreferrer"><?= htmlspecialchars($label) ?></a>
      <?php endforeach; ?>
    </section>
  <?php endif; ?>

  <div class="floating-support">
    <a class="support-btn" href="mailto:<?= htmlspecialchars($supportEmail) ?>?subject=Help%20with%20<?= rawurlencode($ref) ?>&body=Tenant%20ref%20<?= rawurlencode($ref) ?>%20needs%20help" target="_blank" rel="noreferrer">
      Support email
    </a>
    <a class="support-btn secondary" href="https://wa.me/<?= preg_replace('/[^0-9]/', '', $whatsAppNumber) ?>?text=<?= htmlspecialchars($supportMessage, ENT_QUOTES) ?>" target="_blank" rel="noreferrer">
      WhatsApp
    </a>
  </div>

  <script>
    (() => {
    const ref = <?= json_encode($ref) ?>;
    const apiBase = <?= json_encode($apiBase) ?>;

      function apiFetch(path, data) {
        return fetch(apiBase + path, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data),
        }).then(res => res.json().then(body => ({ ok: res.ok, status: res.status, body })));
      }

      document.getElementById('downloadBtn')?.addEventListener('click', () => {
        const token = <?= json_encode($token) ?>;
        if (!token || !ref) return;
        window.location.assign('/download.php?ref=' + encodeURIComponent(ref) + '&token=' + encodeURIComponent(token));
      });

      document.getElementById('refreshBtn')?.addEventListener('click', () => location.reload(true));

      document.getElementById('saveKeyBtn')?.addEventListener('click', async () => {
        const input = document.getElementById('openaiKey');
        const status = document.getElementById('openaiKeyStatus');
        if (!input || !status) return;
        const key = input.value.trim();
        if (key === '') {
          status.textContent = 'OpenAI key cannot be empty.';
          return;
        }
        status.textContent = 'Saving...';
        const { ok, body } = await apiFetch('/openai/save.php', { ref, api_key: key });
        status.textContent = ok ? 'Key saved securely.' : 'Save failed: ' + (body.error || 'unknown error');
      });

      document.getElementById('testKeyBtn')?.addEventListener('click', async () => {
        const status = document.getElementById('openaiKeyStatus');
        status.textContent = 'Testing key...';
        const { ok, body } = await apiFetch('/openai/test.php', { ref });
        status.textContent = ok ? 'Key works: ' + (body.message || 'ok') : 'Test failed: ' + (body.error || 'OpenAI error');
      });

      document.getElementById('deleteKeyBtn')?.addEventListener('click', async () => {
        const status = document.getElementById('openaiKeyStatus');
        status.textContent = 'Removing key...';
        const { ok, body } = await apiFetch('/openai/delete.php', { ref });
        status.textContent = ok ? 'Key deleted.' : 'Delete failed: ' + (body.error || 'unknown');
      });

      document.getElementById('generateBtn')?.addEventListener('click', async () => {
        const topic = document.getElementById('topicInput')?.value.trim() || '';
        const title = document.getElementById('titleInput')?.value.trim() || '';
        const status = document.getElementById('generateStatus');
        if (!topic) {
          status.textContent = 'Please provide a topic or prompt before generating.';
          return;
        }
        status.textContent = 'Generating draft...';
        const { ok, body } = await apiFetch('/content/generate.php', { ref, topic, title });
        if (ok && body.ok) {
          status.textContent = 'Draft queued. Refresh to see it in the list.';
          document.getElementById('topicInput').value = '';
          document.getElementById('titleInput').value = '';
        } else {
          status.textContent = 'Generation failed: ' + (body.error || 'unknown');
        }
      });

      document.querySelectorAll('.previewBtn').forEach(btn => {
        btn.addEventListener('click', (e) => {
          const row = e.currentTarget.closest('tr');
          const url = row?.dataset.previewUrl;
          if (url) window.open(url, '_blank', 'noreferrer');
        });
      });

      document.querySelectorAll('.approveBtn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
          const row = e.currentTarget.closest('tr');
          if (!row) return;
          const draftId = row.dataset.draftId;
          const token = row.dataset.approveToken;
          const btnEl = e.currentTarget;
          btnEl.disabled = true;
          btnEl.textContent = 'Publishing...';
          const { ok, body } = await apiFetch('/content/approve.php', { ref, draft: draftId, token });
          if (ok && body.ok) {
            btnEl.textContent = 'Published';
            btnEl.disabled = true;
            row.querySelector('td:nth-child(3) .badge').textContent = 'Published';
            row.querySelector('td:nth-child(3)').className = 'status-published';
          } else {
            btnEl.textContent = 'Approve';
            btnEl.disabled = false;
            alert('Approve failed: ' + (body.error || 'see logs'));
          }
        });
      });
    })();
  </script>
</body>
</html>
