<?php
// app/helpers.php

function view(string $name, array $data = []) {
  extract($data);
  require __DIR__ . '/../views/' . $name . '.php';
}

function active_class(string $slug, string $current): string {
  return $slug === $current
    ? 'bg-gray-900 text-white'
    : 'text-gray-300 hover:bg-gray-700 hover:text-white';
}

/**
 * POST JSON com cURL.
 * Retorna ['ok'=>bool,'status'=>int,'body'=>string,'error'=>string|null]
 *
 * @param string $url
 * @param array  $payload
 * @param int    $timeout
 * @param array  $headers  Ex.: ['X-Signature: abc', 'Authorization: Bearer ...']
 */
function http_post_json(string $url, array $payload, int $timeout = 10, array $headers = []): array {
  if (!$url) return ['ok'=>false,'status'=>0,'body'=>'','error'=>'Empty URL'];

  // sempre garante Content-Type JSON
  $finalHeaders = array_merge(['Content-Type: application/json'], $headers);

  $ch = curl_init($url);
  curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => $finalHeaders,
    CURLOPT_POSTFIELDS     => json_encode($payload, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
    CURLOPT_TIMEOUT        => $timeout,
  ]);
  $body   = curl_exec($ch);
  $errno  = curl_errno($ch);
  $err    = $errno ? curl_error($ch) : null;
  $status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
  curl_close($ch);

  return ['ok' => !$errno && $status >= 200 && $status < 300, 'status'=>$status, 'body'=>$body ?? '', 'error'=>$err];
}

function base_url(): string {
  $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
  $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
  return $scheme . '://' . $host;
}

function user_webhook_url(string $token): string {
  return rtrim(base_url(), '/') . '/webhook/' . $token;
}






/** Normaliza o plano para um dos três válidos, caindo em 'basic' se vier nulo/ruim. */
function valid_plan(?string $plan): string {
  $p = strtolower(trim((string)$plan));
  return in_array($p, ['basic','profissional','premium'], true) ? $p : 'basic';
}

/**
 * Lê o plano do usuário logado na tabela auth_users.
 * - $userId: vem de $_SESSION['user']['id']
 * - Retorna sempre: 'basic' | 'profissional' | 'premium'
 */
function get_user_plan(PDO $pdo, ?string $userId): string {
  if (!$userId) return 'basic';
  try {
    $st = $pdo->prepare('SELECT plan FROM auth_users WHERE id = :id LIMIT 1');
    $st->execute([':id' => $userId]);
    return valid_plan($st->fetchColumn());
  } catch (Throwable $e) {
    return 'basic'; // em caso de erro, degrada com segurança
  }
}

/**
 * Verifica se o plano atual pode acessar a rota ($page).
 * - BASIC pode: painel, conexoes, webhook, leads, disparos, agente-disparo, suporte
 * - PROFISSIONAL/PREMIUM: tudo
 */
function can_access_page(string $page, string $plan): bool {
  // Sempre liberar a rota de upgrade (e login, se existir)
  if (in_array($page, ['upgrade', 'login'], true)) return true;

  if ($plan === 'profissional' || $plan === 'premium') return true;

  $basicAllowed = [
    'painel',
    'conexoes',
    'webhook',
    'leads',
    'disparos',
    'agente-disparo',
    'suporte',
    'google',
    'atualizacoes',
    'minha_conta',
    'dicas',

  ];
  return in_array($page, $basicAllowed, true);
}






