<?php
declare(strict_types=1);
require_once __DIR__ . '/../../src/bootstrap.php';

if (!Auth::user()) {
    json_out(['ok' => false, 'error' => 'unauthorized'], 401);
}

$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
$id = (int) ($_GET['id'] ?? 0);

if ($method === 'GET') {
    if ($id <= 0) {
        json_out(['ok' => false, 'error' => 'invalid id'], 400);
    }
    $report = ReportRepository::getById($id);
    if (!$report) {
        json_out(['ok' => false, 'error' => 'not found'], 404);
    }
    json_out([
        'ok' => true,
        'id' => $id,
        'tags' => $report['tags'] ?? [],
        'workflow' => TagCatalog::workflowPresets(),
        'presets' => TagCatalog::editorPresets(),
        'can_edit' => Auth::canEditTags((int) ($report['company_id'] ?? 0)),
    ]);
}

if ($method !== 'PUT' && $method !== 'POST') {
    json_out(['ok' => false, 'error' => 'method not allowed'], 405);
}

$raw = file_get_contents('php://input');
$data = is_string($raw) && $raw !== '' ? json_decode($raw, true) : $_POST;
if (!is_array($data)) {
    json_out(['ok' => false, 'error' => 'invalid json'], 400);
}
$id = (int) ($data['id'] ?? $id);
if ($id <= 0) {
    json_out(['ok' => false, 'error' => 'invalid id'], 400);
}

$tagsIn = $data['tags'] ?? [];
if (!is_array($tagsIn)) {
    json_out(['ok' => false, 'error' => 'tags must be array'], 400);
}

$report = ReportRepository::getById($id);
if (!$report) {
    json_out(['ok' => false, 'error' => 'not found'], 404);
}

if (!Auth::canEditTags((int) ($report['company_id'] ?? 0))) {
    json_out(['ok' => false, 'error' => 'forbidden'], 403);
}

try {
    ReportRepository::setCustomTags($id, $tagsIn);
    $updated = ReportRepository::getById($id);
    json_out([
        'ok' => true,
        'id' => $id,
        'tags' => $updated['tags'] ?? [],
    ]);
} catch (Throwable $e) {
    error_log('report_tags: ' . $e->getMessage());
    $out = ['ok' => false, 'error' => 'save failed'];
    if (cfg('debug')) {
        $out['hint'] = $e->getMessage();
    }
    json_out($out, 500);
}
