<?php
/**
 * Endpoint de tracking del lado cliente
 * Recibe datos enviados por JavaScript (resolución, timezone, plugins, etc.)
 * y los añade al JSON de tracking.
 */
require_once __DIR__ . '/../../../config/bootstrap.php';

use App\Services\AuthService;
use App\Services\SecurityService;

header('Content-Type: application/json');
header('X-Content-Type-Options: nosniff');

// Solo POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    exit;
}

$auth = new AuthService();
$security = new SecurityService();

// Verificar sesión
if (!$auth->isAuthenticated()) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$user   = $auth->user();
$adminId = $user['id'];

// Leer body JSON
$rawBody = file_get_contents('php://input');
$data = json_decode($rawBody, true);

if (!is_array($data)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid payload']);
    exit;
}

// Sanitizar y limitar datos
$allowed = [
    'screen_width', 'screen_height', 'window_width', 'window_height',
    'color_depth', 'pixel_ratio', 'timezone', 'timezone_offset',
    'language', 'languages', 'platform', 'cores', 'memory',
    'touch_points', 'touch_support', 'cookies_enabled',
    'java_enabled', 'do_not_track', 'online', 'connection_type',
    'fonts_count', 'plugins', 'canvas_fp', 'webgl_vendor', 'webgl_renderer',
    'geolocation', 'battery_level', 'battery_charging', 'page', 'referrer',
    'performance_navigation', 'performance_timing'
];

$clientData = [];
foreach ($allowed as $key) {
    if (isset($data[$key])) {
        $val = $data[$key];
        // Limitar strings a 500 chars
        if (is_string($val)) {
            $val = substr(htmlspecialchars($val, ENT_QUOTES, 'UTF-8'), 0, 500);
        }
        $clientData[$key] = $val;
    }
}

// Cargar archivo JSON
$trackingFile = storage_path('logs/user_tracking.json');
if (!is_dir(dirname($trackingFile))) {
    mkdir(dirname($trackingFile), 0755, true);
}

$trackingData = [];
if (file_exists($trackingFile)) {
    $raw = file_get_contents($trackingFile);
    $trackingData = json_decode($raw, true) ?? [];
}

// Buscar la entrada más reciente del admin actual (del mismo día)
// y enriquecerla con los datos del cliente
$today = date('Y-m-d');
$updated = false;

for ($i = count($trackingData) - 1; $i >= 0; $i--) {
    $entry = &$trackingData[$i];
    if (
        isset($entry['admin_id'], $entry['timestamp']) &&
        $entry['admin_id'] === $adminId &&
        substr($entry['timestamp'], 0, 10) === $today
    ) {
        $entry['client_data'] = $clientData;
        $entry['client_data_updated_at'] = date('Y-m-d H:i:s');
        $updated = true;
        break;
    }
}

// Si no se encontró entrada para hoy, crear una nueva
if (!$updated) {
    $clientIp = $security->getClientIP();
    $clientUA = $security->getUserAgent();

    $newEntry = [
        'timestamp'      => date('Y-m-d H:i:s'),
        'timestamp_unix' => time(),
        'admin_id'       => $adminId,
        'admin_nombre'   => $user['nombre'],
        'admin_email'    => $user['email'],
        'ip'             => $clientIp,
        'browser'        => ['raw' => $clientUA],
        'client_data'    => $clientData,
        'client_data_updated_at' => date('Y-m-d H:i:s'),
        'fingerprint'    => md5($clientIp . $clientUA . $today),
        'page'           => $clientData['page'] ?? 'unknown',
    ];

    $trackingData[] = $newEntry;
}

// Mantener máximo 500 entradas
if (count($trackingData) > 500) {
    $trackingData = array_slice($trackingData, -500);
}

file_put_contents(
    $trackingFile,
    json_encode($trackingData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
    LOCK_EX
);

echo json_encode([
    'success' => true,
    'message' => 'Tracking data saved',
    'entries' => count($trackingData)
]);
