<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/mock_data.php';

if (session_status() !== PHP_SESSION_ACTIVE) session_start();

$cfg = $config ?? eaq_load_config();
$baseUrl = $cfg['base_url'] ?? eaq_base_url();

// Load/seed CRM mock snapshot
$crm = eaq_read_json('mock_crm.json', null);
if ($crm === null) {
  $crm = eaq_seed_mock_crm();
  eaq_write_json('mock_crm.json', $crm);
}

// Handle admin action: toggle follow-up completion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($cfg['enable_admin_actions'] ?? true)) {
  $action = (string)($_POST['action'] ?? '');
  if ($action === 'toggle_followup') {
    if (!eaq_is_installed()) eaq_redirect($baseUrl . '/install/');
    eaq_require_admin($cfg);

    $followupId = (string)($_POST['followup_id'] ?? '');
    $toggled = false;
    foreach ($crm['followups'] as &$fu) {
      if (($fu['Id'] ?? '') === $followupId) {
        $fu['IsCompleted'] = !($fu['IsCompleted'] ?? false);
        $toggled = true;
        break;
      }
    }
    unset($fu);
    if ($toggled) {
      eaq_write_json('mock_crm.json', $crm);
      $notice = 'Follow-up atualizado.';
    } else {
      $error = 'Follow-up não encontrado.';
    }
  }
}

$lang = $cfg['lang'] ?? 'pt-BR';

$counts = [
  'leads_total' => count($crm['leads'] ?? []),
  'opps_total' => count($crm['opportunities'] ?? []),
  'sessions_total' => count($crm['sessions'] ?? []),
  'followups_open' => 0,
  'followups_done' => 0,
];
foreach ($crm['followups'] ?? [] as $fu) {
  if (!empty($fu['IsCompleted'])) $counts['followups_done']++;
  else $counts['followups_open']++;
}

$webglExists = file_exists(__DIR__ . '/../web-build/index.html');
$webglUrl = $baseUrl . '/web-build/index.html';
?>
<!doctype html>
<html lang="<?php echo htmlspecialchars($lang, ENT_QUOTES); ?>">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?php echo htmlspecialchars($cfg['app_name'] ?? 'EventsAppQuest', ENT_QUOTES); ?></title>
  <style>
    body { font-family: Arial, sans-serif; background:#0b1220; color:#e8eefc; margin:0; }
    .top { padding: 18px; border-bottom: 1px solid #223053; display:flex; justify-content:space-between; gap:14px; flex-wrap:wrap; }
    .title { font-size: 18px; font-weight: 700; }
    .pill { background:#111a2e; border:1px solid #223053; border-radius: 999px; padding: 8px 12px; font-size: 13px; color:#cfe0ff; }
    .wrap { max-width: 1200px; margin: 0 auto; padding: 18px; }
    .grid { display:grid; grid-template-columns: 1fr; gap: 14px; }
    @media (min-width: 1000px) { .grid-2 { grid-template-columns: 1fr 1fr; } }
    .card { background:#111a2e; border:1px solid #223053; border-radius: 14px; padding: 14px; }
    h2 { margin: 0 0 10px 0; font-size: 16px; }
    table { width:100%; border-collapse: collapse; }
    th, td { padding: 10px 8px; border-bottom: 1px solid #223053; font-size: 13px; text-align:left; }
    th { color:#b7c8f0; font-weight: 700; }
    .muted { color:#b7c8f0; font-size: 13px; }
    .btn { padding: 8px 12px; border-radius: 10px; border:1px solid #2a3b63; background:#2454ff; color:#fff; cursor:pointer; text-decoration:none; display:inline-block; }
    .btn-secondary { background:#0b1220; color:#cfe0ff; }
    .btn-small { padding: 6px 10px; font-size: 12px; }
    .notice { background:#1f3b2f; border:1px solid #2c6a49; color:#bff2d6; padding:10px 12px; border-radius: 10px; margin-bottom: 12px; }
    .error { background:#3b0f0f; border:1px solid #6a1f1f; color:#ffd2d2; padding:10px 12px; border-radius: 10px; margin-bottom: 12px; }
    iframe { width:100%; height: 620px; border:0; border-radius: 14px; background:#0b1220; }
    .form-inline { display:flex; gap:10px; align-items:center; flex-wrap:wrap; }
    .badge { font-size: 12px; padding: 6px 10px; border-radius: 999px; border:1px solid #2a3b63; color:#cfe0ff; display:inline-block; }
    .badge-ok { border-color:#2c6a49; background:#0f2b1d; }
    .badge-warn { border-color:#6a5b1f; background:#2b2412; }
  </style>
</head>
<body>
  <div class="top">
    <div>
      <div class="title"><?php echo htmlspecialchars($cfg['app_name'] ?? 'EventsAppQuest', ENT_QUOTES); ?></div>
      <div class="muted"><?php echo htmlspecialchars($cfg['lang'] ?? 'pt-BR', ENT_QUOTES); ?></div>
    </div>
    <div class="pill">
      Leads: <?php echo (int)$counts['leads_total']; ?> |
      Oportunidades: <?php echo (int)$counts['opps_total']; ?> |
      Sessões: <?php echo (int)$counts['sessions_total']; ?> |
      Follow-ups abertos: <?php echo (int)$counts['followups_open']; ?>
    </div>
  </div>

  <div class="wrap">
    <?php if (!empty($notice)): ?><div class="notice"><?php echo htmlspecialchars($notice, ENT_QUOTES); ?></div><?php endif; ?>
    <?php if (!empty($error)): ?><div class="error"><?php echo htmlspecialchars($error, ENT_QUOTES); ?></div><?php endif; ?>

    <div class="grid grid-2">
      <div class="card">
        <h2>Visão geral (CRM mock)</h2>
        <p class="muted" style="margin-top:0;">
          Esta tela serve para você avaliar visualmente e testar interações sem depender do Unity Editor.
          Se existir <code>/web-build/index.html</code>, o painel também pode embutir o WebGL.
        </p>
        <div style="display:flex; gap:10px; flex-wrap:wrap; margin-top:10px;">
          <span class="badge badge-ok">Mock local</span>
          <?php if ($webglExists): ?><span class="badge badge-warn">WebGL detectado (opcional)</span><?php else: ?><span class="badge">WebGL não exportado</span><?php endif; ?>
        </div>

        <h2 style="margin-top:16px;">Follow-ups</h2>
        <table>
          <thead>
            <tr><th>Prioridade</th><th>Título</th><th>Prazo</th><th>Status</th><?php if (!empty($cfg['enable_admin_actions'])): ?><th>Ação</th><?php endif; ?></tr>
          </thead>
          <tbody>
            <?php foreach (($crm['followups'] ?? []) as $fu): ?>
              <tr>
                <td><?php echo htmlspecialchars((string)($fu['Priority'] ?? ''), ENT_QUOTES); ?></td>
                <td><?php echo htmlspecialchars((string)($fu['Title'] ?? ''), ENT_QUOTES); ?></td>
                <td><?php echo htmlspecialchars((string)($fu['DueDate'] ?? ''), ENT_QUOTES); ?></td>
                <td><?php echo !empty($fu['IsCompleted']) ? '<span style="color:#9be7b7;font-weight:700;">Concluído</span>' : '<span style="color:#ffd89b;font-weight:700;">Aberto</span>'; ?></td>
                <?php if (!empty($cfg['enable_admin_actions'])): ?>
                  <td>
                    <form method="post" action="" style="margin:0;">
                      <input type="hidden" name="action" value="toggle_followup">
                      <input type="hidden" name="followup_id" value="<?php echo htmlspecialchars((string)($fu['Id'] ?? ''), ENT_QUOTES); ?>">
                      <button class="btn btn-secondary btn-small" type="submit"><?php echo !empty($fu['IsCompleted']) ? 'Reabrir' : 'Concluir'; ?></button>
                    </form>
                  </td>
                <?php endif; ?>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
        <p class="muted" style="margin-bottom:0;">
          Se as ações falharem, faça login: <a href="<?php echo htmlspecialchars($baseUrl . '/app/login.php', ENT_QUOTES); ?>">/app/login.php</a>.
        </p>
      </div>

      <div class="card">
        <h2>Dashboard (Leads / Oportunidades / Propostas)</h2>
        <div class="grid" style="gap:12px;">
          <div>
            <h2 style="font-size:14px;">Leads</h2>
            <table>
              <thead><tr><th>Nome</th><th>Empresa</th><th>Status</th></tr></thead>
              <tbody>
              <?php foreach (($crm['leads'] ?? []) as $l): ?>
                <tr>
                  <td><?php echo htmlspecialchars((string)($l['Name'] ?? ''), ENT_QUOTES); ?></td>
                  <td><?php echo htmlspecialchars((string)($l['Company'] ?? ''), ENT_QUOTES); ?></td>
                  <td><?php echo htmlspecialchars((string)($l['Status'] ?? ''), ENT_QUOTES); ?></td>
                </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
          <div>
            <h2 style="font-size:14px;">Oportunidades</h2>
            <table>
              <thead><tr><th>Título</th><th>Stage</th><th>Valor</th></tr></thead>
              <tbody>
              <?php foreach (($crm['opportunities'] ?? []) as $o): ?>
                <tr>
                  <td><?php echo htmlspecialchars((string)($o['Title'] ?? ''), ENT_QUOTES); ?></td>
                  <td><?php echo htmlspecialchars((string)($o['Stage'] ?? ''), ENT_QUOTES); ?></td>
                  <td><?php echo htmlspecialchars((string)($o['Value'] ?? ''), ENT_QUOTES); ?></td>
                </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
          <div>
            <h2 style="font-size:14px;">Propostas</h2>
            <table>
              <thead><tr><th>Nome</th><th>Status</th></tr></thead>
              <tbody>
              <?php foreach (($crm['proposals'] ?? []) as $p): ?>
                <tr>
                  <td><?php echo htmlspecialchars((string)($p['Name'] ?? ''), ENT_QUOTES); ?></td>
                  <td><?php echo htmlspecialchars((string)($p['Status'] ?? ''), ENT_QUOTES); ?></td>
                </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>

        <h2 style="margin-top:16px;">WebGL (opcional)</h2>
        <?php if ($webglExists): ?>
          <iframe src="<?php echo htmlspecialchars($webglUrl, ENT_QUOTES); ?>"></iframe>
        <?php else: ?>
          <p class="muted" style="margin-bottom:0;">
            Nenhuma build WebGL detectada em <code>/web-build/index.html</code>.
            Quando você exportar WebGL do Unity, coloque o conteúdo gerado no diretório <code>web-build/</code> e esta seção vai embutir automaticamente.
          </p>
        <?php endif; ?>
      </div>
    </div>

  </div>
</body>
</html>

