<?php
// helpers/tracking.php — registro de acciones de usuarios para Growth Intelligence

function dm_track_event(int $user_id, string $event_type, string $module = '', array $meta = []): void {
    global $pdo;
    if (!$pdo || $user_id <= 0) return;
    try {
        $pdo->prepare("INSERT INTO dm_events (user_id, event_type, module, meta) VALUES (?,?,?,?)")
            ->execute([$user_id, $event_type, $module ?: null, $meta ? json_encode($meta) : null]);
        // Recalcular engagement score en dm_subscriptions si existe
        _dm_update_engagement_score($user_id);
    } catch (Throwable $e) { /* silencioso — nunca romper el flujo principal */ }
}

function _dm_update_engagement_score(int $user_id): void {
    global $pdo;
    $score = 0;
    $events = $pdo->prepare("SELECT event_type, COUNT(*) as cnt FROM dm_events WHERE user_id=? GROUP BY event_type");
    $events->execute([$user_id]);
    $map = [];
    foreach ($events->fetchAll() as $r) $map[$r['event_type']] = (int)$r['cnt'];

    if (!empty($map['byok_connected']))      $score += 30;
    if (!empty($map['proposal_generated']))  $score += 25;
    if (!empty($map['client_added']))        $score += 20;
    // 3+ módulos distintos visitados
    $modules = $pdo->prepare("SELECT COUNT(DISTINCT module) as cnt FROM dm_events WHERE user_id=? AND event_type='module_visited'");
    $modules->execute([$user_id]);
    if ((int)$modules->fetchColumn() >= 3)   $score += 15;
    if (!empty($map['report_generated']))    $score += 10;
    $avi_uses = min(3, (int)($map['avi_query'] ?? 0));
    $score += $avi_uses * 5;

    $score = min(100, $score);
    $pdo->prepare("UPDATE dm_subscriptions SET engagement_score=? WHERE user_id=?")
        ->execute([$score, $user_id]);
}

// Eventos estándar con constantes
const DM_EVT_TRIAL_STARTED       = 'trial_started';
const DM_EVT_TRIAL_CONVERTED     = 'trial_converted';
const DM_EVT_TRIAL_EXPIRED       = 'trial_expired';
const DM_EVT_BYOK_CONNECTED      = 'byok_connected';
const DM_EVT_CLIENT_ADDED        = 'client_added';
const DM_EVT_PROPOSAL_GENERATED  = 'proposal_generated';
const DM_EVT_PROPOSAL_STAGE      = 'proposal_stage_completed';
const DM_EVT_MODULE_VISITED      = 'module_visited';
const DM_EVT_REPORT_GENERATED    = 'report_generated';
const DM_EVT_AVI_QUERY           = 'avi_query';
const DM_EVT_LOGIN               = 'login';
