<?php
// public/api/followups.php
require_once __DIR__ . '/../../app/config.php';
require_once __DIR__ . '/../../app/db.php';
require_once __DIR__ . '/../../app/helpers.php';

header('Content-Type: application/json; charset=utf-8');

function jexit(array $p, int $s=200){ http_response_code($s); echo json_encode($p, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); exit; }

if (empty($_SESSION['user']['id']) || empty($_SESSION['user']['email'])) {
  jexit(['ok'=>false,'error'=>'Não autenticado'], 401);
}

$pdo = db();

/** igual padrão do projeto */
function getOrCreateUsersId(PDO $pdo, string $sessionId, string $email, ?string $name=null): string {
  $q = $pdo->prepare('SELECT id FROM users WHERE email = :e LIMIT 1'); $q->execute([':e'=>$email]);
  $id = $q->fetchColumn(); if ($id) return $id;
  $ins = $pdo->prepare('INSERT INTO users (id,email,name) VALUES (:id,:e,:n) ON CONFLICT (email) DO NOTHING');
  $ins->execute([':id'=>$sessionId,':e'=>$email,':n'=>$name]);
  $q->execute([':e'=>$email]); $id = $q->fetchColumn();
  if (!$id) throw new RuntimeException('Falha ao sincronizar usuário.');
  return $id;
}

$authId    = $_SESSION['user']['id'];
$authEmail = $_SESSION['user']['email'];
$authName  = $_SESSION['user']['name'] ?? null;
$userId    = getOrCreateUsersId($pdo, $authId, $authEmail, $authName);

$action = $_GET['action'] ?? '';

function norm_steps(array $steps): array {
  // Normaliza/valida steps: reenumera day=1..N, checa hour e campos por tipo
  $out = [];
  $day = 1;
  foreach ($steps as $s) {
    $tipo = trim((string)($s['tipo'] ?? ''));
    $hour = trim((string)($s['hour'] ?? ''));
    if (!preg_match('/^\d{2}:\d{2}$/', $hour)) $hour = '09:00';

    $row = ['day'=>$day++, 'hour'=>$hour, 'tipo'=>$tipo];

    if ($tipo === 'texto') {
      $row['conteudo'] = trim((string)($s['conteudo'] ?? ''));
    } elseif (in_array($tipo, ['imagem','audio','pdf','video'], true)) {
      $row['url']     = trim((string)($s['url'] ?? ''));
      $row['legenda'] = trim((string)($s['legenda'] ?? ''));
    } else {
      // tipo "fim" ou inválido => ignora no follow
      continue;
    }
    $out[] = $row;
  }
  return $out;
}

try {
  switch ($action) {

    // ============ LIST ============
    case 'list': {
      $q = $pdo->prepare("SELECT id,nome,status,versao,initial_ignore_seconds,timezone,created_at,updated_at
                            FROM followups WHERE user_id=:u ORDER BY id DESC");
      $q->execute([':u'=>$userId]);
      jexit(['ok'=>true,'data'=>$q->fetchAll(PDO::FETCH_ASSOC)]);
    }

    // ============ GET ============
    case 'get': {
      $id = (int)($_GET['id'] ?? 0);
      $q = $pdo->prepare("SELECT id,nome,status,versao,initial_ignore_seconds,timezone,steps
                            FROM followups WHERE id=:id AND user_id=:u LIMIT 1");
      $q->execute([':id'=>$id, ':u'=>$userId]);
      $row = $q->fetch(PDO::FETCH_ASSOC);
      if (!$row) jexit(['ok'=>false,'error'=>'Não encontrado'], 404);
      // steps pode vir string(json) ou jsonb
      if (!is_array($row['steps'])) {
        $dec = json_decode((string)$row['steps'], true);
        $row['steps'] = is_array($dec) ? $dec : [];
      }
      jexit(['ok'=>true,'data'=>$row]);
    }
    
    
    
    // GET /api/followups.php?action=prefs
    // GET /api/followups.php?action=prefs
    case 'prefs': {
      // usa o $userId já definido no topo (getOrCreateUsersId)
      $st = $pdo->prepare("
          SELECT
            COALESCE(follow_up_enabled, false)                AS enabled,
            COALESCE(follow_up_ignore_seconds, 0)             AS ignore_seconds,
            COALESCE(follow_up_timezone, 'America/Sao_Paulo') AS timezone
          FROM users
          WHERE id = :u
          LIMIT 1
      ");
      $st->execute([':u' => $userId]);

      $row = $st->fetch(PDO::FETCH_ASSOC) ?: [
        'enabled'        => false,
        'ignore_seconds' => 0,
        'timezone'       => 'America/Sao_Paulo',
      ];

      jexit(['ok' => true, 'data' => $row]);
    }



    // ============ SAVE (draft) ============
    case 'save': {
      $in = json_decode(file_get_contents('php://input'), true) ?? [];
      $id     = (int)($in['id'] ?? 0);
      $nome   = trim((string)($in['nome'] ?? ''));
      $ignore = max(0, (int)($in['initial_ignore_seconds'] ?? 0));
      $tz     = trim((string)($in['timezone'] ?? 'America/Sao_Paulo'));
      $steps  = norm_steps(is_array($in['steps'] ?? null) ? $in['steps'] : []);

      if ($nome === '') jexit(['ok'=>false,'error'=>'Informe o nome.'], 422);

      if ($id > 0) {
        $u = $pdo->prepare("UPDATE followups
                               SET nome=:n, initial_ignore_seconds=:ig, timezone=:tz, steps=:st::jsonb
                             WHERE id=:id AND user_id=:u");
        $u->execute([
          ':n'=>$nome, ':ig'=>$ignore, ':tz'=>$tz,
          ':st'=>json_encode($steps, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
          ':id'=>$id, ':u'=>$userId
        ]);
        jexit(['ok'=>true,'id'=>$id]);
      } else {
        $i = $pdo->prepare("INSERT INTO followups
                              (user_id,nome,status,versao,initial_ignore_seconds,timezone,steps)
                            VALUES
                              (:u,:n,'draft',1,:ig,:tz,:st::jsonb)
                            RETURNING id");
        $i->execute([
          ':u'=>$userId, ':n'=>$nome, ':ig'=>$ignore, ':tz'=>$tz,
          ':st'=>json_encode($steps, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
        ]);
        $newId = (int)$i->fetchColumn();
        jexit(['ok'=>true,'id'=>$newId]);
      }
    }

    // ============ PUBLISH ============
    case 'publish': {
      $id = (int)($_POST['id'] ?? 0);
      if ($id <= 0) jexit(['ok'=>false,'error'=>'ID inválido'], 400);

      $u = $pdo->prepare("UPDATE followups
                             SET status='published', versao=versao+1
                           WHERE id=:id AND user_id=:u");
      $u->execute([':id'=>$id, ':u'=>$userId]);
      if ($u->rowCount() === 0) jexit(['ok'=>false,'error'=>'Não encontrado'], 404);

      // carrega p/ webhook
      $q = $pdo->prepare("SELECT id,nome,status,versao,initial_ignore_seconds,timezone,steps
                            FROM followups WHERE id=:id AND user_id=:u");
      $q->execute([':id'=>$id, ':u'=>$userId]);
      $row = $q->fetch(PDO::FETCH_ASSOC) ?: [];

      $steps = $row['steps'];
      if (!is_array($steps)) $steps = json_decode((string)$steps, true) ?: [];

      // user data
      $stU = $pdo->prepare("SELECT id,email,name,meta FROM users WHERE id=:u LIMIT 1");
      $stU->execute([':u'=>$userId]);
      $userRow = $stU->fetch(PDO::FETCH_ASSOC) ?: [];
      $userMeta = $userRow['meta'] ?? null;
      if (is_string($userMeta)) $userMeta = json_decode($userMeta, true);
      if (!is_array($userMeta)) $userMeta = [];

      $webhookList = $userMeta['webhook'] ?? [];
      $webhookUrl  = N8N_WEBHOOK_URL ?: ($webhookList[0] ?? '');

      $payload = [
        'event'    => 'followup.published',
        'user'     => ['id'=>$userRow['id'] ?? $userId, 'email'=>$userRow['email'] ?? null, 'name'=>$userRow['name'] ?? null],
        'followup' => [
          'id'=>(int)$row['id'],
          'name'=>$row['nome'] ?? '',
          'status'=>'published',
          'version'=>(int)$row['versao'],
          'initial_ignore_seconds'=>(int)$row['initial_ignore_seconds'],
          'timezone'=>$row['timezone'] ?? 'America/Sao_Paulo',
          'steps'=>$steps
        ],
        'meta' => $userMeta
      ];

      $wh = null;
      if ($webhookUrl) $wh = http_post_json($webhookUrl, $payload);

      jexit(['ok'=>true,'versao'=>(int)$row['versao'],
        'webhook'=>[
          'configured'=> (bool)$webhookUrl,
          'ok' => $wh['ok'] ?? null,
          'status' => $wh['status'] ?? null,
          'error' => $wh['error'] ?? null
        ]
      ]);
    }

    // ============ DELETE ============
    case 'delete': {
      $id = (int)($_POST['id'] ?? 0);
      $d = $pdo->prepare("DELETE FROM followups WHERE id=:id AND user_id=:u");
      $d->execute([':id'=>$id, ':u'=>$userId]);
      jexit(['ok'=>$d->rowCount()>0]);
    }

    // ============ TOGGLE ENABLED ============
    case 'toggle_enabled': {
      $enabled = (bool)($_POST['enabled'] ?? false);
      $ignore  = max(0, (int)($_POST['ignore_seconds'] ?? 0));
      $tz      = trim((string)($_POST['timezone'] ?? ''));

      $sql = "UPDATE users SET follow_up_enabled=:e, follow_up_ignore_seconds=:i"
           . ($tz !== '' ? ", follow_up_timezone=:tz" : "")
           . " WHERE id=:u";
      $p = [':e'=>$enabled?1:0, ':i'=>$ignore, ':u'=>$userId];
      if ($tz !== '') $p[':tz'] = $tz;
      $u = $pdo->prepare($sql);
      $u->execute($p);

      jexit(['ok'=>true, 'enabled'=>$enabled, 'ignore_seconds'=>$ignore, 'timezone'=>$tz ?: null]);
    }

    default: jexit(['ok'=>false,'error'=>'Ação inválida'], 400);
  }
} catch (Throwable $e) {
  jexit(['ok'=>false,'error'=>$e->getMessage()], 500);
}
