<?php

require_once __DIR__ . '/agent_schema.php';

if (!function_exists('ua_agent_uuid')) {
  function ua_agent_uuid(): string {
    $data = random_bytes(16);
    $data[6] = chr((ord($data[6]) & 0x0f) | 0x40);
    $data[8] = chr((ord($data[8]) & 0x3f) | 0x80);
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
  }
}

if (!function_exists('ua_agent_json')) {
  function ua_agent_json($value): string {
    $json = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    return is_string($json) ? $json : '{}';
  }
}

if (!function_exists('ua_agent_activity_add')) {
  function ua_agent_activity_add(mysqli $conn, array $data): array {
    ua_agent_schema_migrate($conn);
    $uuid = trim((string)($data['event_uuid'] ?? ''));
    if ($uuid === '') $uuid = ua_agent_uuid();
    $uuidEsc = $conn->real_escape_string($uuid);
    $existing = @$conn->query("SELECT id,event_uuid FROM agent_activity_log WHERE event_uuid='{$uuidEsc}' LIMIT 1");
    if ($existing && $existing->num_rows) {
      $row = $existing->fetch_assoc();
      return ['ok'=>true,'duplicate'=>true,'id'=>(int)$row['id'],'event_uuid'=>$uuid,'error'=>''];
    }
    $agentId = isset($data['agent_id']) && (int)$data['agent_id'] > 0 ? (int)$data['agent_id'] : null;
    $eventType = substr(trim((string)($data['event_type'] ?? 'EVENT')), 0, 60);
    $direction = strtoupper(trim((string)($data['direction'] ?? 'LOCAL')));
    if (!in_array($direction, ['FROM_MAIN','TO_MAIN','LOCAL'], true)) $direction = 'LOCAL';
    $instanceId = substr(trim((string)($data['source_instance_id'] ?? '')), 0, 80);
    $entityType = substr(trim((string)($data['entity_type'] ?? '')), 0, 50);
    $entityId = substr(trim((string)($data['entity_id'] ?? '')), 0, 120);
    $requestId = substr(trim((string)($data['request_id'] ?? '')), 0, 120);
    $status = strtoupper(trim((string)($data['status'] ?? 'SUCCESS')));
    $summary = substr(trim((string)($data['summary'] ?? '')), 0, 500);
    $payload = ua_agent_json($data['payload'] ?? []);
    $error = trim((string)($data['error_message'] ?? ''));
    $actorType = substr(trim((string)($data['actor_type'] ?? 'admin')), 0, 30);
    $actorId = isset($data['actor_id']) && (int)$data['actor_id'] > 0 ? (int)$data['actor_id'] : null;
    $occurredAt = (string)($data['occurred_at'] ?? date('Y-m-d H:i:s'));

    $stmt = $conn->prepare("INSERT INTO agent_activity_log
      (event_uuid,agent_id,event_type,direction,source_instance_id,entity_type,entity_id,request_id,status,summary,payload_json,error_message,actor_type,actor_id,occurred_at)
      VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
    if (!$stmt) return ['ok'=>false,'error'=>$conn->error,'event_uuid'=>$uuid];
    $types = 'si' . str_repeat('s', 11) . 'is';
    $stmt->bind_param(
      $types,
      $uuid, $agentId, $eventType, $direction, $instanceId, $entityType, $entityId,
      $requestId, $status, $summary, $payload, $error, $actorType, $actorId, $occurredAt
    );
    try {
      $ok = $stmt->execute();
      $errorText = $ok ? '' : $stmt->error;
    } catch (Throwable $e) {
      $ok = false;
      $errorText = $e->getMessage();
    }
    $id = $ok ? (int)$stmt->insert_id : 0;
    $stmt->close();
    if ($ok && $agentId) {
      @$conn->query("UPDATE agents SET last_activity_at='" . $conn->real_escape_string($occurredAt) . "' WHERE id={$agentId}");
    }
    return ['ok'=>$ok,'duplicate'=>false,'id'=>$id,'event_uuid'=>$uuid,'error'=>$errorText];
  }
}
