<?php
// ask-leads-dashboard.php
// Este script exibe um dashboard HTML com filtros e estatísticas diárias de leads do AskSuite.

// Ajusta caminho do arquivo de conexão para refletir a estrutura de diretórios
require_once __DIR__ . '/../config/conexao.php'; // fornece $pdo

// 1) Parâmetros de período e filtros
date_default_timezone_set('America/Sao_Paulo');
$today        = date('Y-m-d');
$firstOfMonth = date('Y-m-01');

$start = (isset($_GET['start']) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['start']))
         ? $_GET['start'] : $firstOfMonth;
$end   = (isset($_GET['end'])   && preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['end']))
         ? $_GET['end']   : $today;
$utm_source = isset($_GET['utm_source']) && preg_match('/^[\w\-]+$/', $_GET['utm_source'])
             ? $_GET['utm_source'] : '';
$tag        = isset($_GET['tag'])        && preg_match('/^[\w\-\s]+$/u', $_GET['tag'])
             ? $_GET['tag'] : '';

// 2) Busca canais e tags para filtro (no intervalo definido)
$stmt = $pdo->prepare(
    "SELECT DISTINCT utm_source FROM asksuite_leads
     WHERE utm_source IS NOT NULL
       AND fetch_date BETWEEN :start AND :end
     ORDER BY utm_source"
);
$stmt->execute([':start' => $start, ':end' => $end]);
$channels = $stmt->fetchAll(PDO::FETCH_COLUMN);

$stmt = $pdo->prepare(
    "SELECT tags FROM asksuite_leads
     WHERE JSON_LENGTH(tags) > 0
       AND fetch_date BETWEEN :start AND :end"
);
$stmt->execute([':start' => $start, ':end' => $end]);
$allTags = [];
foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $jsonTags) {
    $arr = json_decode($jsonTags, true);
    if (is_array($arr)) {
        foreach ($arr as $t) {
            $allTags[$t] = true;
        }
    }
}
sort($channels);
$tags = array_keys($allTags);
sort($tags);

// 3) Monta query de estatísticas diárias
$sql = <<<SQL
SELECT
  fetch_date AS date,
  COUNT(*) AS total_leads,
  SUM(request_price = 1) AS leads_req_price,
  SUM(request_price = 0) AS leads_geral,
  SUM(request_price = 1 AND link_quotation_opened = 1) AS cotacoes_abertas,
  SUM(request_price = 1 AND link_quotation_opened = 0) AS nao_clicou,
  SUM(has_reservation = 1) AS reservas,
  SUM(IFNULL(min_total_value_price_quote, 0)) AS receita_potencial
FROM asksuite_leads
WHERE fetch_date BETWEEN :start AND :end
SQL;
$params = [':start' => $start, ':end' => $end];

if ($utm_source) {
    $sql .= " AND utm_source = :utm_source";
    $params[':utm_source'] = $utm_source;
}
if ($tag) {
    $sql .= " AND JSON_CONTAINS(tags, JSON_QUOTE(:tag), '$')";
    $params[':tag'] = $tag;
}
$sql .= " GROUP BY fetch_date ORDER BY fetch_date";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$detail_daily = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 4) Totais gerais e percentuais
$totals = array_fill_keys([
    'total_leads','leads_req_price','leads_geral',
    'cotacoes_abertas','nao_clicou','reservas','receita_potencial'
], 0);
foreach ($detail_daily as $row) {
    foreach ($totals as $k => $_) {
        $totals[$k] += $row[$k];
    }
}
function pct($n, $d) {
    return $d > 0 ? round($n / $d * 100, 2) : 0;
}
$totals['pct_pediu_preco']      = pct($totals['leads_req_price'], $totals['total_leads']);
$totals['pct_abertura_cotacao'] = pct($totals['cotacoes_abertas'], $totals['leads_req_price']);
$totals['pct_conversao_final']  = pct($totals['reservas'], $totals['total_leads']);
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Dashboard Leads AskSuite</title>
  <style>
    body { font-family: Arial, sans-serif; margin: 20px; }
    table { border-collapse: collapse; width: 100%; margin-top: 15px; }
    th, td { border: 1px solid #ccc; padding: 8px; text-align: center; }
    th { background: #f0f0f0; }
    form > * { margin-right: 10px; }
  </style>
</head>
<body>
  <h1>Dashboard Leads AskSuite</h1>

  <form method="get">
    <label>Início: <input type="date" name="start" value="<?php echo htmlspecialchars($start); ?>"></label>
    <label>Fim:    <input type="date" name="end"   value="<?php echo htmlspecialchars($end); ?>"></label>

    <label>Canal:
      <select name="utm_source">
        <option value="">Todos</option>
        <?php foreach ($channels as $c): ?>
          <option value="<?php echo htmlspecialchars($c); ?>" <?php echo $utm_source === $c ? 'selected' : ''; ?>><?php echo htmlspecialchars($c); ?></option>
        <?php endforeach; ?>
      </select>
    </label>

    <label>Tag:
      <select name="tag">
        <option value="">Todas</option>
        <?php foreach ($tags as $t): ?>
          <option value="<?php echo htmlspecialchars($t); ?>" <?php echo $tag === $t ? 'selected' : ''; ?>><?php echo htmlspecialchars($t); ?></option>
        <?php endforeach; ?>
      </select>
    </label>

    <button type="submit">Filtrar</button>
  </form>

  <h2>Totais (<?php echo htmlspecialchars($start); ?> a <?php echo htmlspecialchars($end); ?>)</h2>
  <table>
    <tr>
      <th>Total Leads</th><th>Pediu Preço</th><th>Geral</th><th>Cotações Abertas</th>
      <th>Não Clicou</th><th>Reservas</th><th>Receita Potencial</th>
      <th>% Pediu Preço</th><th>% Abertura</th><th>% Conversão</th>
    </tr>
    <tr>
      <td><?php echo $totals['total_leads']; ?></td>
      <td><?php echo $totals['leads_req_price']; ?></td>
      <td><?php echo $totals['leads_geral']; ?></td>
      <td><?php echo $totals['cotacoes_abertas']; ?></td>
      <td><?php echo $totals['nao_clicou']; ?></td>
      <td><?php echo $totals['reservas']; ?></td>
      <td>R$ <?php echo number_format($totals['receita_potencial'], 2, ',', '.'); ?></td>
      <td><?php echo $totals['pct_pediu_preco']; ?>%</td>
      <td><?php echo $totals['pct_abertura_cotacao']; ?>%</td>
      <td><?php echo $totals['pct_conversao_final']; ?>%</td>
    </tr>
  </table>

  <h2>Detalhamento Diário</h2>
  <table>
    <tr>
      <th>Data</th><th>Total</th><th>Pediu Preço</th><th>Cotações Abertas</th><th>Reservas</th><th>Receita Potencial</th>
    </tr>
    <?php foreach ($detail_daily as $row): ?>
      <tr>
        <td><?php echo htmlspecialchars($row['date']); ?></td>
        <td><?php echo $row['total_leads']; ?></td>
        <td><?php echo $row['leads_req_price']; ?></td>
        <td><?php echo $row['cotacoes_abertas']; ?></td>
        <td><?php echo $row['reservas']; ?></td>
        <td>R$ <?php echo number_format($row['receita_potencial'], 2, ',', '.'); ?></td>
      </tr>
    <?php endforeach; ?>
  </table>
</body>
</html>