<?php
declare(strict_types=1);

$pageTitle = 'API';
require_once __DIR__ . '/includes/header.php';

$self = basename($_SERVER['PHP_SELF']);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && gpc_csrf_check($_POST['csrf'] ?? null)) {
    gpc_setting_save('panel_name', trim((string) ($_POST['panel_name'] ?? 'GPC Panel')));
    gpc_setting_save('app_key_dev', trim((string) ($_POST['app_key_dev'] ?? '')));
    gpc_setting_save('cod_revenda', trim((string) ($_POST['cod_revenda'] ?? '')));
    gpc_setting_save('app_id', trim((string) ($_POST['app_id'] ?? '11')));
    gpc_setting_save('auto_register_days', (string) max(1, (int) ($_POST['auto_register_days'] ?? 365)));
    $autoMac = (string)($_POST['auto_mac_enabled'] ?? '1');
    $autoMac = $autoMac === '1' ? '1' : '0';
    gpc_setting_save('auto_mac_enabled', $autoMac);
    gpc_flash('ok', 'Salvo');
    header('Location: ' . $self);
    exit;
}

$csrf = gpc_csrf_token();
?>

<div class="card">
    <div class="card-body">
        <form method="post">
            <input type="hidden" name="csrf" value="<?= gpc_h($csrf) ?>">
            <div class="form-grid">
                <div class="field">
                    <label>Painel</label>
                    <input type="text" name="panel_name" value="<?= gpc_h(gpc_setting('panel_name')) ?>">
                </div>
                <div class="field">
                    <label>app_key_dev</label>
                    <input type="text" name="app_key_dev" required value="<?= gpc_h(gpc_setting('app_key_dev')) ?>">
                </div>
                <div class="field">
                    <label>codRevenda</label>
                    <input type="text" name="cod_revenda" value="<?= gpc_h(gpc_setting('cod_revenda')) ?>">
                </div>
                <div class="field">
                    <label>app_id</label>
                    <input type="number" name="app_id" min="1" value="<?= gpc_h(gpc_setting('app_id', '11')) ?>">
                </div>
                <div class="field">
                    <label>Auto MAC</label>
                    <select name="auto_mac_enabled">
                        <option value="1" <?= gpc_setting('auto_mac_enabled', '1') === '1' ? 'selected' : '' ?>>Ativado</option>
                        <option value="0" <?= gpc_setting('auto_mac_enabled', '1') === '0' ? 'selected' : '' ?>>Desativado</option>
                    </select>
                </div>
                <div class="field">
                    <label>Dias (auto MAC)</label>
                    <input type="number" name="auto_register_days" min="1"
                           value="<?= gpc_h(gpc_setting('auto_register_days', '365')) ?>">
                </div>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn"><i data-lucide="save"></i> Salvar</button>
            </div>
        </form>
    </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
