<?php

$audience = $request->param('personi', $request->headers['X-Personi-Audience'] ?? null);

// Client timezone offset (query param or header): minutes or "+HH:MM"
$tzOffset = $request->param('tz_offset', $request->headers['X-Personi-TZ-Offset'] ?? null);

if (!$audience) {
    return;
}

if (is_string($audience)) {
    $audience = array_map('trim', explode(',', $audience));
}

// Build evaluation context using tz_offset
$ctx = [];
if ($tzOffset !== null && $tzOffset !== '') {
    if (is_numeric($tzOffset)) {
        $ctx['tzoffset'] = (int)$tzOffset;
    } elseif (is_string($tzOffset) && preg_match('/^([+-])(\d{2}):(\d{2})$/', $tzOffset, $m)) {
        $sign = $m[1] === '-' ? -1 : 1;
        $hours = (int)$m[2];
        $mins = (int)$m[3];
        $ctx['tzoffset'] = $sign * ($hours * 60 + $mins);
    }
}

// Context variables for replacement
$variables = $request->param('personi_vars', []);

// Handle JSON string in query param or header
if (is_string($variables)) {
    try {
        $decoded = json5_decode($variables, true);
        if (is_array($decoded)) {
            $variables = $decoded;
        }
    } catch (\Throwable $e) {
        $variables = [];
    }
}

if ($headerContext = $request->headers['X-Personi-Vars'] ?? null) {
    try {
        $decoded = json5_decode($headerContext, true);
        if (is_array($decoded)) {
            $variables = is_array($variables) ? array_merge($variables, $decoded) : $decoded;
        }
    } catch (\Throwable $e) {

    }
}

if (!empty($variables) && is_array($variables)) {
    $ctx['variables'] = $variables;
}

$this->on(['content.api.items', 'content.api.item', 'pages.api.page'], function (&$contents) use($audience, $ctx) {
    $contents = $this->helper('personi')->process($contents, $audience, $ctx);
});
