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

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

$currentUser = $_SESSION['name'];
$role = $_SESSION['role'];
if ($role !== 'master') {
    die('Acceso denegado. Solo el admin puede ver esta configuración.');
}

function cfgv($db, $key, $default = '') {
    return (string) settings_get($db, $key, $default);
}

if (isset($_POST['save_trial_settings'])) {
    $d = max(0, min(365, (int)($_POST['trial_days'] ?? 0)));
    $h = max(0, min(240, (int)($_POST['trial_hours'] ?? 4)));
    $u = trim((string)($_POST['app_download_url'] ?? ''));
    $dc = trim((string)($_POST['app_downloader_code'] ?? ''));
    if ($u !== '' && !preg_match('~^https?://~i', $u) && ($u[0] ?? '') !== '/') {
        $u = '';
    }
    settings_set($db, 'trial_days', (string)$d);
    settings_set($db, 'trial_hours', (string)$h);
    settings_set($db, 'app_download_url', $u);
    settings_set($db, 'app_downloader_code', substr($dc, 0, 120));
    echo "<script>alert('Configuración guardada'); window.location='config_teste.php';</script>";
    exit;
}

if (isset($_POST['save_content_settings'])) {
    $fields = [
        'login_brand_text' => ['default' => 'YouTube'],
        'login_badge_text' => ['default' => 'PREMIUM'],
        'login_subtitle' => ['default' => 'Code Generator Panel'],
        'login_button_text' => ['default' => 'ACCESS GENERATOR'],
        'login_feature_1' => ['default' => 'Generate Codes'],
        'login_feature_2' => ['default' => 'Secure System'],
        'login_feature_3' => ['default' => 'Fast Delivery'],
        'login_footer_text' => ['default' => 'Propiedad de Raffy L'],
        'login_support_url' => ['default' => 'https://MAXREBRANDS-tv.com/'],
        'login_watermark' => ['default' => 'YOUTUBE PREMIUM GENERATOR v2.0'],
        'public_brand_name' => ['default' => 'MyTube'],
        'public_brand_badge' => ['default' => 'PREMIUM'],
        'public_hero_title' => ['default' => 'Prueba Premium Gratis'],
        'public_hero_subtitle' => ['default' => 'Ingresa tu nombre y celular para recibir un código de acceso temporal. Solo se permite una demo por teléfono, IP o dispositivo.'],
        'public_form_title' => ['default' => 'Generar Código de Prueba'],
        'public_form_subtitle' => ['default' => 'Completa tus datos para obtener una prueba gratis. El sistema valida teléfono, IP y dispositivo para evitar múltiples demos.'],
        'reseller_title' => ['default' => 'Planes Reseller'],
        'reseller_lines' => ['default' => "10 créditos|$10 USD
50 créditos|$30 USD
100 créditos|$50 USD
500 créditos|$200 USD
1000 créditos|$300 USD"],
        'reseller_footer' => ['default' => 'Contacta soporte para más info'],
        'download_title' => ['default' => '¿Aún no tienes la app?'],
        'download_text' => ['default' => 'Descarga MyTube Premium y comienza a disfrutar de contenido sin límites'],
        'download_button_text' => ['default' => 'Descargar MyTube Premium'],
    ];

    foreach ($fields as $key => $meta) {
        $value = trim((string)($_POST[$key] ?? $meta['default']));
        if ($key === 'login_support_url' && $value !== '' && !preg_match('~^https?://~i', $value) && ($value[0] ?? '') !== '/') {
            $value = $meta['default'];
        }
        settings_set($db, $key, substr($value, 0, 5000));
    }
    echo "<script>alert('Contenido editable actualizado'); window.location='config_teste.php';</script>";
    exit;
}

$trialDays = (int) cfgv($db, 'trial_days', '0');
$trialHours = (int) cfgv($db, 'trial_hours', '4');
$downloadUrl = cfgv($db, 'app_download_url', '');
$downloaderCode = cfgv($db, 'app_downloader_code', '');

$login_brand_text = cfgv($db, 'login_brand_text', 'YouTube');
$login_badge_text = cfgv($db, 'login_badge_text', 'PREMIUM');
$login_subtitle = cfgv($db, 'login_subtitle', 'Code Generator Panel');
$login_button_text = cfgv($db, 'login_button_text', 'ACCESS GENERATOR');
$login_feature_1 = cfgv($db, 'login_feature_1', 'Generate Codes');
$login_feature_2 = cfgv($db, 'login_feature_2', 'Secure System');
$login_feature_3 = cfgv($db, 'login_feature_3', 'Fast Delivery');
$login_footer_text = cfgv($db, 'login_footer_text', 'Propiedad de Raffy L');
$login_support_url = cfgv($db, 'login_support_url', 'https://MAXREBRANDS-tv.com/');
$login_watermark = cfgv($db, 'login_watermark', 'YOUTUBE PREMIUM GENERATOR v2.0');
$public_brand_name = cfgv($db, 'public_brand_name', 'MyTube');
$public_brand_badge = cfgv($db, 'public_brand_badge', 'PREMIUM');
$public_hero_title = cfgv($db, 'public_hero_title', 'Prueba Premium Gratis');
$public_hero_subtitle = cfgv($db, 'public_hero_subtitle', 'Ingresa tu nombre y celular para recibir un código de acceso temporal. Solo se permite una demo por teléfono, IP o dispositivo.');
$public_form_title = cfgv($db, 'public_form_title', 'Generar Código de Prueba');
$public_form_subtitle = cfgv($db, 'public_form_subtitle', 'Completa tus datos para obtener una prueba gratis. El sistema valida teléfono, IP y dispositivo para evitar múltiples demos.');
$reseller_title = cfgv($db, 'reseller_title', 'Planes Reseller');
$reseller_lines = cfgv($db, 'reseller_lines', "10 créditos|$10 USD
50 créditos|$30 USD
100 créditos|$50 USD
500 créditos|$200 USD
1000 créditos|$300 USD");
$reseller_footer = cfgv($db, 'reseller_footer', 'Contacta soporte para más info');
$download_title = cfgv($db, 'download_title', '¿Aún no tienes la app?');
$download_text = cfgv($db, 'download_text', 'Descarga MyTube Premium y comienza a disfrutar de contenido sin límites');
$download_button_text = cfgv($db, 'download_button_text', 'Descargar MyTube Premium');

$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';
$checkUrl = $proto . $host . $base . '/consulta_codigo.php';
$seconds = ($trialDays * 86400) + ($trialHours * 3600);
$expPreview = date('Y-m-d H:i:s', time() + max(1, $seconds));
?>

<div class="col-md-10 mx-auto">
    <div class="card text-white ctluser-main mb-4" style="background:#1a1a1a;">
        <div class="card-header ctheading text-center">
            <h3 class="mb-0"><i class="fa fa-clock-o"></i> CONFIGURACIÓN DEMO PÚBLICA</h3>
            <small>Nombre + celular + validación por IP/dispositivo para una sola demo</small>
        </div>

        <div class="card-body">
            <div class="alert alert-dark border-secondary">
                <p class="mb-2"><strong>Link público para pedir demo:</strong><br><a href="<?=htmlspecialchars($publicUrl)?>" target="_blank" class="text-info"><?=htmlspecialchars($publicUrl)?></a></p>
                <p class="mb-0"><strong>Link público para consultar código:</strong><br><a href="<?=htmlspecialchars($checkUrl)?>" target="_blank" class="text-info"><?=htmlspecialchars($checkUrl)?></a></p>
            </div>

            <form method="post">
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label>Días (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">Para una demo gratis de 4 horas usa 0 días y 4 horas.</small>
                    </div>
                </div>

                <div class="form-group">
                    <label>Link de descarga de la app</label>
                    <input type="text" name="app_download_url" class="form-control" value="<?=htmlspecialchars($downloadUrl)?>" placeholder="https://seusite.com/app.apk">
                </div>

                <div class="form-group">
                    <label>Código downloader</label>
                    <input type="text" name="app_downloader_code" class="form-control" value="<?=htmlspecialchars($downloaderCode)?>" placeholder="Ej: 123456">
                    <small class="text-muted">Este código se enviará también en el mensaje de WhatsApp y se mostrará en las pantallas públicas.</small>
                </div>

                <button type="submit" name="save_trial_settings" class="btn btn-info"><i class="fa fa-save"></i> Guardar demo</button>
                <a href="<?=htmlspecialchars($publicUrl)?>" target="_blank" class="btn btn-outline-light ml-2">Abrir demo pública</a>
                <a href="<?=htmlspecialchars($checkUrl)?>" target="_blank" class="btn btn-outline-warning ml-2">Abrir verificador</a>
            </form>

            <hr class="border-secondary">
            <small class="text-muted"><i class="fa fa-info-circle"></i> Con la configuración actual, una nueva demo vencería en: <strong><?=htmlspecialchars($expPreview)?></strong></small>
        </div>
    </div>

    <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-pencil"></i> CONTENIDO EDITABLE</h3>
            <small>Login, planes reseller y sección descargar app</small>
        </div>
        <div class="card-body">
            <form method="post">
                <h5 class="mb-3 text-info">Inicio de sesión</h5>
                <div class="form-row">
                    <div class="form-group col-md-4"><label>Marca login</label><input type="text" name="login_brand_text" class="form-control" value="<?=htmlspecialchars($login_brand_text)?>"></div>
                    <div class="form-group col-md-4"><label>Badge login</label><input type="text" name="login_badge_text" class="form-control" value="<?=htmlspecialchars($login_badge_text)?>"></div>
                    <div class="form-group col-md-4"><label>Subtítulo login</label><input type="text" name="login_subtitle" class="form-control" value="<?=htmlspecialchars($login_subtitle)?>"></div>
                </div>
                <div class="form-row">
                    <div class="form-group col-md-4"><label>Texto botón login</label><input type="text" name="login_button_text" class="form-control" value="<?=htmlspecialchars($login_button_text)?>"></div>
                    <div class="form-group col-md-4"><label>Feature 1</label><input type="text" name="login_feature_1" class="form-control" value="<?=htmlspecialchars($login_feature_1)?>"></div>
                    <div class="form-group col-md-4"><label>Feature 2</label><input type="text" name="login_feature_2" class="form-control" value="<?=htmlspecialchars($login_feature_2)?>"></div>
                </div>
                <div class="form-row">
                    <div class="form-group col-md-4"><label>Feature 3</label><input type="text" name="login_feature_3" class="form-control" value="<?=htmlspecialchars($login_feature_3)?>"></div>
                    <div class="form-group col-md-4"><label>Footer login</label><input type="text" name="login_footer_text" class="form-control" value="<?=htmlspecialchars($login_footer_text)?>"></div>
                    <div class="form-group col-md-4"><label>Link soporte login</label><input type="text" name="login_support_url" class="form-control" value="<?=htmlspecialchars($login_support_url)?>"></div>
                </div>
                <div class="form-group"><label>Watermark login</label><input type="text" name="login_watermark" class="form-control" value="<?=htmlspecialchars($login_watermark)?>"></div>

                <hr class="border-secondary">
                <h5 class="mb-3 text-info">Página pública</h5>
                <div class="form-row">
                    <div class="form-group col-md-4"><label>Marca pública</label><input type="text" name="public_brand_name" class="form-control" value="<?=htmlspecialchars($public_brand_name)?>"></div>
                    <div class="form-group col-md-4"><label>Badge pública</label><input type="text" name="public_brand_badge" class="form-control" value="<?=htmlspecialchars($public_brand_badge)?>"></div>
                    <div class="form-group col-md-4"><label>Título hero</label><input type="text" name="public_hero_title" class="form-control" value="<?=htmlspecialchars($public_hero_title)?>"></div>
                </div>
                <div class="form-group"><label>Texto hero</label><textarea name="public_hero_subtitle" rows="3" class="form-control"><?=htmlspecialchars($public_hero_subtitle)?></textarea></div>
                <div class="form-row">
                    <div class="form-group col-md-6"><label>Título formulario</label><input type="text" name="public_form_title" class="form-control" value="<?=htmlspecialchars($public_form_title)?>"></div>
                    <div class="form-group col-md-6"><label>Texto formulario</label><input type="text" name="public_form_subtitle" class="form-control" value="<?=htmlspecialchars($public_form_subtitle)?>"></div>
                </div>

                <hr class="border-secondary">
                <h5 class="mb-3 text-info">Planes reseller</h5>
                <div class="form-group"><label>Título</label><input type="text" name="reseller_title" class="form-control" value="<?=htmlspecialchars($reseller_title)?>"></div>
                <div class="form-group"><label>Planes (uno por línea, formato: nombre|precio)</label><textarea name="reseller_lines" rows="6" class="form-control"><?=htmlspecialchars($reseller_lines)?></textarea></div>
                <div class="form-group"><label>Texto adicional reseller</label><input type="text" name="reseller_footer" class="form-control" value="<?=htmlspecialchars($reseller_footer)?>"></div>

                <hr class="border-secondary">
                <h5 class="mb-3 text-info">Descargar app</h5>
                <div class="form-row">
                    <div class="form-group col-md-4"><label>Título descarga</label><input type="text" name="download_title" class="form-control" value="<?=htmlspecialchars($download_title)?>"></div>
                    <div class="form-group col-md-4"><label>Texto descarga</label><input type="text" name="download_text" class="form-control" value="<?=htmlspecialchars($download_text)?>"></div>
                    <div class="form-group col-md-4"><label>Texto botón descarga</label><input type="text" name="download_button_text" class="form-control" value="<?=htmlspecialchars($download_button_text)?>"></div>
                </div>

                <button type="submit" name="save_content_settings" class="btn btn-success"><i class="fa fa-save"></i> Guardar contenido editable</button>
            </form>
        </div>
    </div>
</div>

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