<?php
// track.php - registra visitas y eventos (IP + fecha) para Movitax
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/db_connect.php'; // debe definir $conn (mysqli)
if (!isset($conn) || !($conn instanceof mysqli)) {
  echo json_encode(["ok"=>false,"error"=>"No se pudo inicializar la conexión (db_connect.php)."]);
  exit;
}
$conn->set_charset('utf8mb4');

function client_ip(): string {
  $keys = ['HTTP_CF_CONNECTING_IP','HTTP_X_FORWARDED_FOR','HTTP_CLIENT_IP','REMOTE_ADDR'];
  foreach ($keys as $k) {
    if (!empty($_SERVER[$k])) {
      $ip = $_SERVER[$k];
      if ($k === 'HTTP_X_FORWARDED_FOR') {
        $parts = explode(',', $ip);
        $ip = trim($parts[0]);
      }
      return substr($ip, 0, 45);
    }
  }
  return "0.0.0.0";
}

$action = $_GET['action'] ?? ($_POST['action'] ?? '');
$ip = client_ip();
$ua = substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 255);
$pagina = basename($_SERVER['HTTP_REFERER'] ?? 'movitaxsmarth20.html');
if ($pagina === '' || $pagina === 'track.php') $pagina = 'movitaxsmarth20.html';

if ($action === 'visit') {
  $stmt = $conn->prepare("INSERT INTO visitas (ip, user_agent, pagina) VALUES (?,?,?)");
  if (!$stmt) { echo json_encode(["ok"=>false,"error"=>$conn->error]); exit; }
  $stmt->bind_param("sss", $ip, $ua, $pagina);
  $ok = $stmt->execute();
  $id = (int)$conn->insert_id;
  $stmt->close();
  echo json_encode(["ok"=>$ok, "visitor_no"=>$id]);
  exit;
}

if ($action === 'event') {
  $tipo = trim($_POST['type'] ?? '');
  $etq  = trim($_POST['label'] ?? '');
  if ($tipo === '') { echo json_encode(["ok"=>false,"error"=>"missing type"]); exit; }
  $tipo = substr($tipo, 0, 60);
  $etq  = ($etq === '') ? null : substr($etq, 0, 120);

  $stmt = $conn->prepare("INSERT INTO eventos (ip, pagina, tipo, etiqueta) VALUES (?,?,?,?)");
  if (!$stmt) { echo json_encode(["ok"=>false,"error"=>$conn->error]); exit; }
  // bind_param no acepta null con "s" si está estrictamente null en algunas configs; convertir a cadena vacía
  $etqSafe = $etq ?? '';
  $stmt->bind_param("ssss", $ip, $pagina, $tipo, $etqSafe);
  $ok = $stmt->execute();
  $id = (int)$conn->insert_id;
  $stmt->close();
  echo json_encode(["ok"=>$ok, "id_evento"=>$id]);
  exit;
}

echo json_encode(["ok"=>false,"error"=>"unknown action"]);
