<?php
require_once __DIR__ . '/includes/header.php';

/* =======================
   SECURITY
======================= */
if (!isset($_SESSION['loggedin'], $_SESSION['name'], $_SESSION['role'])) {
    header("Location: index.php");
    exit;
}

$currentUser = $_SESSION['name'];
$role        = $_SESSION['role'];

if (!in_array($role, ['master','ultra-reseller','super-reseller'])) {
    die('Access denied');
}

/* =======================
   LOAD DEFAULTS
======================= */
$trialDays  = (int) settings_get($db, 'trial_days', '1');
$trialHours = (int) settings_get($db, 'trial_hours', '0');
$downloadUrl = (string) settings_get($db, 'app_download_url', '');

// clamp
if ($trialDays < 0) $trialDays = 0;
if ($trialDays > 365) $trialDays = 365;
if ($trialHours < 0) $trialHours = 0;
if ($trialHours > 240) $trialHours = 240; // até 10 dias em horas

/* =======================
   SAVE
======================= */
if (isset($_POST['save_trial_settings'])) {
    $d = (int)($_POST['trial_days'] ?? 1);
    $h = (int)($_POST['trial_hours'] ?? 0);
    $u = trim((string)($_POST['app_download_url'] ?? ''));

    if ($d < 0) $d = 0;
    if ($d > 365) $d = 365;
    if ($h < 0) $h = 0;
    if ($h > 240) $h = 240;

    // valida URL (aceita vazio)
    if ($u !== '' && !preg_match('~^https?://~i', $u)) {
        // permite caminhos relativos também (/download/app.apk)
        if ($u[0] !== '/') {
            $u = '';
        }
    }

    settings_set($db, 'trial_days', (string)$d);
    settings_set($db, 'trial_hours', (string)$h);
    settings_set($db, 'app_download_url', $u);

    echo "<script>alert('✅ Configurações salvas!'); window.location='config_teste.php';</script>";
    exit;
}

// Link público
$proto = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
$host  = $_SERVER['HTTP_HOST'] ?? '';
$base  = rtrim(dirname($_SERVER['REQUEST_URI'] ?? '/'), '/\\');
$publicUrl = $proto . $host . $base . '/acesso_livre.php';
?>

<div class="col-md-8 mx-auto">
    <div class="card text-white ctluser-main" style="background:#1a1a1a;">
        <div class="card-header ctheading text-center">
            <h3 class="mb-0"><i class="fa fa-clock-o"></i> CONFIGURAÇÃO DO TEMPO DE TESTE</h3>
            <small>Define o tempo do código gerado na página pública (acesso livre)</small>
        </div>

        <div class="card-body">
            <div class="alert alert-dark border-secondary">
                <div class="d-flex flex-wrap justify-content-between align-items-center">
                    <div>
                        <strong>Link da página pública:</strong><br>
                        <a href="<?=htmlspecialchars($publicUrl)?>" target="_blank" class="text-info">
                            <?=htmlspecialchars($publicUrl)?>
                        </a>
                    </div>
                    <div class="mt-2 mt-md-0">
                        <a class="btn btn-sm btn-outline-info" href="acesso_livre.php" target="_blank">
                            <i class="fa fa-external-link"></i> Abrir página
                        </a>
                    </div>
                </div>
            </div>

            <form method="post">
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label>Dias (0 a 365)</label>
                        <input type="number" name="trial_days" class="form-control" min="0" max="365" value="<?= (int)$trialDays ?>" required>
                    </div>
                    <div class="form-group col-md-6">
                        <label>Horas (0 a 240)</label>
                        <input type="number" name="trial_hours" class="form-control" min="0" max="240" value="<?= (int)$trialHours ?>" required>
                        <small class="text-muted">Ex.: 6 horas, 12 horas, 24 horas, etc.</small>
                    </div>
                </div>

                <div class="form-group">
                    <label>Link/Botão para baixar o app (URL ou caminho /arquivo.apk)</label>
                    <input type="text" name="app_download_url" class="form-control" value="<?=htmlspecialchars($downloadUrl)?>" placeholder="https://seusite.com/app.apk">
                </div>

                <button type="submit" name="save_trial_settings" class="btn btn-info">
                    <i class="fa fa-save"></i> Salvar
                </button>
            </form>

            <hr class="border-secondary">

            <?php
                $seconds = ($trialDays * 86400) + ($trialHours * 3600);
                $expPreview = ($seconds > 0) ? date('Y-m-d H:i:s', time() + $seconds) : date('Y-m-d H:i:s');
            ?>
            <small class="text-muted">
                <i class="fa fa-info-circle"></i>
                Com as configurações atuais, um novo código de teste venceria em: <strong><?=htmlspecialchars($expPreview)?></strong>
            </small>
        </div>
    </div>
</div>

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