<?php

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

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

switch ($method) {

case 'GET':
    try {
        [$pdo, $tmpDb, $lockFp] = qdb_open_read_or_fail();
        $settings = qdb_settings_get_on_pdo($pdo);
        $sessionCount = (int)$pdo->query('SELECT COUNT(*) FROM session')->fetchColumn();
        qdb_discard($tmpDb, $lockFp);
        json_success([
            'settings'      => $settings,
            'activeSessions' => $sessionCount,
            'defaults'      => qdb_settings_defaults(),
        ]);
    } catch (Throwable $e) {
        qdb_handler_fail($e, 'Load settings', null, $tmpDb ?? null, $lockFp ?? null);
    }
    break;

case 'PUT':
case 'PATCH':
    $body = read_json_body();
    try {
        [$pdo, $tmpDb, $lockFp] = qdb_open_write_or_fail();
        $current = qdb_settings_get_on_pdo($pdo);
        $merged = qdb_settings_validate_and_merge($body, $current);
        qdb_settings_save_on_pdo($pdo, $merged);
        qdb_save($tmpDb, $lockFp);
        json_success(['settings' => $merged]);
    } catch (InvalidArgumentException $e) {
        json_error('INVALID_FIELD', $e->getMessage(), 400);
    } catch (Throwable $e) {
        qdb_handler_fail($e, 'Save settings', null, $tmpDb ?? null, $lockFp ?? null);
    }
    break;

case 'POST':
    $body = read_json_body();
    $action = trim((string)($body['action'] ?? ''));
    if ($action !== 'revokeAllSessions') {
        json_error('BAD_REQUEST', 'Unknown action', 400);
    }
    $confirm = trim((string)($body['confirmPhrase'] ?? ''));
    $revokeAllPhrase = 'REVOKE ALL SESSIONS';
    if ($confirm !== $revokeAllPhrase) {
        json_error(
            'CONFIRMATION_REQUIRED',
            'Type exactly "' . $revokeAllPhrase . '" to revoke every session',
            400
        );
    }
    try {
        [$pdo, $tmpDb, $lockFp] = qdb_open_write_or_fail();
        $removed = token_revoke_all_on_pdo($pdo);
        qdb_save($tmpDb, $lockFp);
        json_success(['revokedSessions' => $removed]);
    } catch (Throwable $e) {
        qdb_handler_fail($e, 'Revoke all sessions', null, $tmpDb ?? null, $lockFp ?? null);
    }
    break;

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