<?php
session_start();

// Base de datos
$dbFile = 'codigos.db';
try {
    $pdo = new PDO("sqlite:$dbFile");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec("CREATE TABLE IF NOT EXISTS codigos (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        codigo TEXT NOT NULL,
        username TEXT NOT NULL,
        password TEXT NOT NULL
    )");
} catch (PDOException $e) {
    die("Error BD: " . $e->getMessage());
}

// Procesar formulario
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $codigo   = trim($_POST['codigo'] ?? '');
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');

    $codigo = str_replace('-', '', $codigo);

    if ($codigo && $username && $password) {
        $stmt = $pdo->prepare("INSERT INTO codigos (codigo, username, password) VALUES (?, ?, ?)");
        $stmt->execute([$codigo, $username, $password]);
        $_SESSION['message'] = "Codigo agregado con exito!";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    } else {
        $_SESSION['message'] = "Por favor, completa todos los campos.";
    }
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Agregar Codigo</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" />
    <style>
        /* Reset */
        * { box-sizing: border-box; margin: 0; padding: 0; }

        body {
            background: #000 url('/roku/panel2/img/fondo.jpg') center/cover fixed no-repeat;
            color: #fff;
            font-family: 'Segoe UI', sans-serif;
            min-height: 100vh;
        }

        /* Capa oscura */
        body::before {
            content: '';
            position: fixed; inset: 0;
            background: rgba(0, 0, 0, 0.6);
            z-index: -1;
        }

        /* Topbar */
        .topbar {
            position: fixed; top: 0; left: 50%; transform: translateX(-50%);
            width: 100%; max-width: 110rem;
            display: flex; justify-content: space-between; align-items: center;
            padding: 12px 20px;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(8px);
            border-bottom: 1px solid rgba(0,0,0,0.15);
            z-index: 100;
            border-radius: 0 0 12px 12px;
        }

        .topbar img {
            height: 54px; width: 92px;
        }

        .topbar a {
            background: #e62b27;
            color: white;
            padding: 8px 16px;
            border-radius: 6px;
            text-decoration: none;
            font-weight: bold;
            font-size: 0.9rem;
        }

        /* Contenido */
        .container {
            max-width: 110rem;
            margin: 100px auto;
            padding: 20px;
        }

        .grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 40px;
            align-items: center;
        }

        @media (max-width: 768px) {
            .grid {
                grid-template-columns: 1fr;
            }
        }

        .img-box img {
            width: 100%;
            border-radius: 16px;
            box-shadow: 0 8px 20px rgba(0,0,0,0.3);
        }

        /* Formulario */
        .form-box {
            background: rgba(255, 255, 255, 0.98);
            backdrop-filter: blur(12px);
            padding: 30px;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.25);
            max-width: 400px;
            margin: 0 auto;
        }

        .form-title {
            text-align: center;
            font-size: 1.5rem;
            font-weight: bold;
            color: #333;
            margin-bottom: 20px;
        }

        .form-title span {
            color: #e62b27;
        }

        /* Mensaje */
        .alert {
            padding: 12px;
            border-radius: 8px;
            font-size: 0.9rem;
            text-align: center;
            margin-bottom: 16px;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border-left: 4px solid #28a745;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border-left: 4px solid #dc3545;
        }

        /* Grupo de campo */
        .input-group {
            position: relative;
            margin-bottom: 16px;
        }

        .input-group label {
            display: block;
            margin-bottom: 6px;
            font-weight: 600;
            color: #333;
            font-size: 0.9rem;
        }

        /* Estilo UNICO para inputs y botón */
        .input-field,
        .submit-btn {
            width: 100%;
            max-width: 340px; /* ancho fijo para todos */
            margin: 0 auto;
            display: block;
            height: 42px;
            border: 1px solid #ccc;
            border-radius: 10px;
            font-size: 1rem;
            padding: 0 14px;
            transition: all 0.2s ease;
            background: white;
        }

        /* Icono dentro del input */
        .input-field {
            padding-left: 40px !important;
            position: relative;
        }

        .input-field::before {
            content: "\f023"; /* default: candado */
            font-family: "Font Awesome 6 Free";
            font-weight: 900;
            position: absolute;
            left: 14px;
            top: 50%;
            transform: translateY(-50%);
            color: #999;
        }

        #codigo::before   { content: "\f023"; } /* key */
        #username::before { content: "\f007"; } /* user */
        #password::before { content: "\f023"; } /* lock */

        .input-field:focus {
            outline: none;
            border-color: #e62b27;
            box-shadow: 0 0 0 3px rgba(230, 43, 39, 0.1);
        }

        /* Botón igual que los inputs */
        .submit-btn {
            background: #e62b27;
            color: white;
            font-weight: bold;
            cursor: pointer;
            border: none;
            padding: 0 14px;
            font-size: 1rem;
            box-shadow: 0 4px 12px rgba(230, 43, 39, 0.2);
        }

        .submit-btn:hover {
            background: #c81f1a;
            transform: translateY(-1px);
        }

        .submit-btn i {
            margin-right: 6px;
        }
    </style>
</head>
<body>

    <div class="topbar">
        <div></div>
        <img src="https://i.imgur.com/kWhhJ89.png" alt="Logo">
        <a href="login.php">Panel</a>
    </div>

    <div class="container">
        <div class="grid">
            <!-- Imagen -->
            <div class="img-box">
                <img src="/roku/panel2/img/panel-activacion.jpg" alt="Activacion">
            </div>

            <!-- Formulario -->
            <div class="form-box">
                <h2 class="form-title">Agregar un <span>Nuevo Codigo</span></h2>

                <?php if (isset($_SESSION['message'])): ?>
                    <div class="alert <?= strpos($_SESSION['message'], 'exito') !== false ? 'alert-success' : 'alert-error' ?>">
                        <?= htmlspecialchars($_SESSION['message']) ?>
                    </div>
                    <?php unset($_SESSION['message']); ?>
                <?php endif; ?>

                <form method="POST">
                    <!-- Campo: Código -->
                    <div class="input-group">
                        <label for="codigo">Codigo</label>
                        <input type="text" id="codigo" name="codigo"
                               placeholder="4D7E-65A2-65" maxlength="17" required
                               oninput="formatCodigo(this)" class="input-field">
                    </div>

                    <!-- Campo: Usuario -->
                    <div class="input-group">
                        <label for="username">Usuario</label>
                        <input type="text" id="username" name="username"
                               placeholder="usuario123" maxlength="32" required
                               autocomplete="username" class="input-field">
                    </div>

                    <!-- Campo: Contraseña -->
                    <div class="input-group">
                        <label for="password">Contrasena</label>
                        <input type="password" id="password" name="password"
                               placeholder="Clave" maxlength="64" required
                               autocomplete="new-password" class="input-field">
                    </div>

                    <!-- Botón: Agregar -->
                    <button type="submit" class="submit-btn">
                        <i class="fas fa-plus-circle"></i> Agregar Codigo
                    </button>
                </form>
            </div>
        </div>
    </div>

    <script>
        function formatCodigo(input) {
            let value = input.value.replace(/[^A-Z0-9]/gi, '');
            let formatted = '';
            for (let i = 0; i < value.length; i++) {
                if (i > 0 && i % 4 === 0) formatted += '-';
                formatted += value[i];
            }
            input.value = formatted.toUpperCase();
        }
    </script>

</body>
</html>