<?php
/**
 * Demo Oracle — configuration du module.
 *
 * Un seul reglage : l'URL vers laquelle renvoient toutes les mentions
 * « disponible en version complete ». Vide, les mentions restent de simples
 * explications, sans lien — la demonstration s'installe alors sans renvoi
 * commercial.
 *
 * Stocke dans securite/modules/demo_oracle.json (Module::getConfig/updateConfig).
 */
require_once dirname(__DIR__, 2) . '/bootstrap.php';
require_once __DIR__ . '/lib/boot.php';

$auth->requireRole('demo_oracle_admin');

// canAccessAsAdmin ne teste pas l'activation : la configuration reste
// joignable avant que le module soit actif.
if (!$moduleRegistry->canAccessAsAdmin('demo_oracle', $currentUser)) {
    http_response_code(403);
    include WEBROOT_PATH . '/includes/403.php';
    exit;
}

if (!Session::has('csrf_token')) {
    Session::set('csrf_token', bin2hex(random_bytes(32)));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!hash_equals(Session::get('csrf_token', ''), $_POST['csrf_token'] ?? '')) {
        Session::setFlash('error', t('msg.error'));
        header('Location: ' . demo_oracle_url('admin'));
        exit;
    }

    $cfg = $moduleRegistry->getConfig('demo_oracle');
    $url = trim((string)($_POST['full_version_url'] ?? ''));

    if ($url === '') {
        unset($cfg['full_version_url']);
    } elseif (!preg_match('#^https?://#i', $url) || !filter_var($url, FILTER_VALIDATE_URL)) {
        Session::setFlash('error', t('demo_oracle.admin_url_invalid'));
        header('Location: ' . demo_oracle_url('admin'));
        exit;
    } else {
        $cfg['full_version_url'] = $url;
    }

    $moduleRegistry->updateConfig('demo_oracle', $cfg);
    Session::setFlash('success', t('msg.saved'));
    header('Location: ' . demo_oracle_url('admin'));
    exit;
}

$cfg = $moduleRegistry->getConfig('demo_oracle');

View::display(__DIR__ . '/views/admin.php', [
    'fullVersionUrl' => (string)($cfg['full_version_url'] ?? ''),
    'dbCount'        => DemoOracleSchema::count($db),
    'maxDbs'         => DEMO_ORACLE_MAX_DATABASES,
    'csrfToken'      => Session::get('csrf_token'),
    'pageTitle'      => t('demo_oracle.admin_title'),
]);
