<?php

$tokenRec = require_valid_token_web();
require_role(['admin', 'supervisor'], $tokenRec);

require_once __DIR__ . '/../lib/analytics.php';

switch ($method) {

case 'GET':
    try {
        $opened = qdb_open_read_or_fail();
        [$pdo, $tmpDb, $lockFp] = $opened;
        if (!empty($_GET['overview'])) {
            $data = qdb_analytics_overview($pdo, $tokenRec);
            qdb_discard($tmpDb, $lockFp);
            json_success($data);
        }

        if (!empty($_GET['staleClients'])) {
            $clients = qdb_analytics_stale_clients($pdo, $tokenRec);
            qdb_discard($tmpDb, $lockFp);
            json_success(['clients' => $clients]);
        }

        qdb_discard($tmpDb, $lockFp);
        json_error('BAD_REQUEST', 'Unknown query', 400);
    } catch (Throwable $e) {
        qdb_handler_fail($e, 'Analytics', null, $tmpDb ?? null, $lockFp ?? null);
    }
    break;

case 'PUT':
    $body = read_json_body();
    $clientCode = trim((string)($body['clientCode'] ?? ''));
    $note = qdb_normalize_client_followup_note($body['note'] ?? '');

    try {
        $opened = qdb_open_write_or_fail();
        [$pdo, $tmpDb, $lockFp] = $opened;
        qdb_analytics_set_followup_note($pdo, $tokenRec, $clientCode, $note);
        qdb_save($tmpDb, $lockFp);
        json_success(['clientCode' => $clientCode, 'note' => $note]);
    } catch (Throwable $e) {
        qdb_handler_fail($e, 'Save follow-up note', null, $tmpDb ?? null, $lockFp ?? null);
    }
    break;

default:
    json_error('METHOD_NOT_ALLOWED', 'Method not allowed', 405);
}
