<?php
session_start();

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header('Location: index.php');
    exit;
}

include('includes/header.php');

$dns_list = $db->select('dns', 'id, title, url', '', 'title ASC');

// ------------------ JSON CONFIG (MÉTODO DIRECTO) ------------------
$jsonFile = __DIR__ . "/api/config_test.json";
$jsonData = [];
if (file_exists($jsonFile)) {
    $jsonData = json_decode(file_get_contents($jsonFile), true);
}

// ------------------ GUARDAR MÉTODO DIRECTO ------------------
if (isset($_POST['submit_directo'])) {
    $jsonSave = [
        'username'      => $_POST['username'] ?? '',
        'password'      => $_POST['password'] ?? '',
        'dns_url'       => $_POST['dns_url'] ?? '',
        'payUrl'        => $_POST['payUrl'] ?? '',
        'status'        => $_POST['status'] ?? 'Desactivado',
        'demo_duration' => intval($_POST['demo_duration'] ?? 3600) // por defecto 1h
    ];

    // Validar campos obligatorios
    $missing = [];
    foreach (['username', 'password', 'dns_url', 'payUrl'] as $field) {
        if (empty($jsonSave[$field])) $missing[] = $field;
    }

    if ($missing) {
        $msg = "❌ Faltan campos obligatorios: " . implode(", ", $missing);
        echo "<script>alert('$msg'); window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "';</script>";
        exit;
    }

    // Guardar en JSON
    if (file_put_contents($jsonFile, json_encode($jsonSave, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES))) {
        echo "<script>alert('✅ Configuración guardada correctamente.'); window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "';</script>";
    } else {
        echo "<script>alert('❌ Error al guardar config_test.json'); window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "';</script>";
    }
    exit;
}

?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Configuración Directa</title>
    <style>
        :root {
            --primary-gray: #2c2c2c;
            --dark-gray: #1a1a1a;
            --light-gray: #f5f5f5;
            --medium-gray: #444;
            --accent: #888;
        }
       
        .page-container { display: flex; flex-direction: column; min-height: 100vh; }
        .main-content { flex: 1; padding: 20px; display: flex; flex-direction: column; gap: 30px; align-items: center; }
        .card-custom {
            background: rgba(255,255,255,0.05);
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.4);
            border: 1px solid rgba(255,255,255,0.1);
            width: 100%;
            max-width: 800px;
        }
        .card-header-custom {
            background: linear-gradient(90deg, var(--medium-gray), var(--dark-gray));
            padding: 20px;
            border-bottom: 2px solid var(--accent);
            text-align: center;
        }
        .card-body-custom { padding: 30px; }
        .form-group { margin-bottom: 20px; }
        .form-label { font-weight: 600; color: var(--light-gray); margin-bottom: 8px; display: block; }
        .form-control {
            background-color: rgba(255,255,255,0.1);
            border: 1px solid rgba(255,255,255,0.2);
            color: white;
            border-radius: 8px;
            padding: 10px 15px;
            width: 100%;
            min-height: 45px;
            line-height: 1.5;
            font-size: 16px;
            box-sizing: border-box;
        }
        select.form-control {
            height: 45px;
            padding: 0 40px 0 15px;
            line-height: normal;
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='white' viewBox='0 0 24 24'%3e%3cpath d='M7 10l5 5 5-5z'/%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right 12px center;
            background-size: 18px;
        }
        .btn-custom {
            background: linear-gradient(45deg, var(--medium-gray), var(--dark-gray));
            border: none;
            border-radius: 8px;
            padding: 12px 25px;
            font-weight: bold;
            color: white;
            transition: 0.3s;
            cursor: pointer;
        }
        .btn-custom:hover {
            background: linear-gradient(45deg, var(--dark-gray), var(--medium-gray));
            transform: translateY(-2px);
        }
        h2 { font-weight: 700; margin: 0; }
        .emoji { margin-right: 6px; }
        .duration-group {
            margin-bottom: 20px;
        }
        .duration-select {
            width: 100%;
        }
        .duration-help {
            font-size: 12px;
            color: #aaa;
            margin-top: 5px;
            display: block;
        }
    </style>
</head>
<body>
<div class="page-container">
    <div class="main-content">
        <!-- CARD MÉTODO DIRECTO -->
        <div class="card-custom">
            <div class="card-header-custom">
                <h2><span class="emoji">⚡</span> Configurar Demo</h2>
            </div>
            <div class="card-body-custom">
                <form method="post">
                    <div class="form-group">
                        <label class="form-label">👤 Usuario</label>
                        <input class="form-control" name="username" type="text" value="<?= $jsonData['username'] ?? '' ?>" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">🔑 Contraseña</label>
                        <input class="form-control" name="password" type="text" value="<?= $jsonData['password'] ?? '' ?>" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">🌐 Seleccionar DNS</label>
                        <select class="form-control" name="dns_url" required>
                            <option value="">Seleccione una DNS</option>
                            <?php foreach ($dns_list as $dns): ?>
                                <option value="<?= $dns['url'] ?>" <?= isset($jsonData['dns_url']) && $jsonData['dns_url'] == $dns['url'] ? 'selected' : '' ?>>
                                    <?= $dns['title'] ?> (<?= $dns['url'] ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group duration-group">
                        <label class="form-label">⏳ Duración del Demo</label>
                        <select class="form-control duration-select" name="demo_duration" required>
                            <option value="3600"  <?= isset($jsonData['demo_duration']) && $jsonData['demo_duration'] == 3600 ? 'selected' : '' ?>>1 Hora</option>
                            <option value="10800" <?= isset($jsonData['demo_duration']) && $jsonData['demo_duration'] == 10800 ? 'selected' : '' ?>>3 Horas</option>
                            <option value="86400" <?= isset($jsonData['demo_duration']) && $jsonData['demo_duration'] == 86400 ? 'selected' : '' ?>>1 Día</option>
                            <option value="604800" <?= isset($jsonData['demo_duration']) && $jsonData['demo_duration'] == 604800 ? 'selected' : '' ?>>7 Días</option>
                            <option value="1296000" <?= isset($jsonData['demo_duration']) && $jsonData['demo_duration'] == 1296000 ? 'selected' : '' ?>>15 Días</option>
                            <option value="2592000" <?= isset($jsonData['demo_duration']) && $jsonData['demo_duration'] == 2592000 ? 'selected' : '' ?>>30 Días</option>
                        </select>
                        <small class="duration-help">💡 1 día = 24 horas | 7 días = 168 horas | 15 días = 360 horas | 30 días = 720 horas</small>
                    </div>

                    <div class="form-group">
                        <label class="form-label">💬 Link/ QR para Activación</label>
                        <input class="form-control" name="payUrl" type="text" value="<?= $jsonData['payUrl'] ?? '' ?>" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">📊 Estado</label>
                        <select class="form-control" name="status" required>
                            <option value="Activo" <?= isset($jsonData['status']) && $jsonData['status'] == 'Activo' ? 'selected' : '' ?>>Activo ✅</option>
                            <option value="Desactivado" <?= isset($jsonData['status']) && $jsonData['status'] == 'Desactivado' ? 'selected' : '' ?>>Desactivado ❌</option>
                        </select>
                    </div>
                    <div class="form-group text-center">
                        <button class="btn-custom" name="submit_directo" type="submit">💾 Actualizar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include('includes/footer.php'); ?>
</body>
</html>