<?php
// api/a.php  (SEGURO)
// Este script SOLO debe usarse para pruebas. Protegido por token.
// NO afecta a los clientes reales del panel, solo evita que cualquiera cree usuarios falsos.

ini_set('display_errors', 0);
header('Content-Type: text/plain; charset=utf-8');

// ====== CONFIG ======
$dbPath = __DIR__ . '/.db.db';

// Pon un token largo (mínimo 40 caracteres)
$SECRET_TOKEN = 'PON_UN_TOKEN_LARGO_Y_DIFICIL_AQUI_1234567890_ABCDEFG';

// Límite máximo por ejecución (evita spam)
$MAX_TO_CREATE = 50;

// ====== AUTH (TOKEN) ======
$token = $_GET['token'] ?? '';
if (!hash_equals($SECRET_TOKEN, $token)) {
    http_response_code(403);
    exit("forbidden");
}

// (Opcional) Solo permitir tu IP
// $ALLOW_IP = 'TU_IP_AQUI';
// if (($_SERVER['REMOTE_ADDR'] ?? '') !== $ALLOW_IP) {
//     http_response_code(403);
//     exit("forbidden-ip");
// }

// ====== CONNECT ======
try {
    $db = new PDO("sqlite:$dbPath");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Crear usuarios con parent_id = 0 (o 1) para identificar que son "pruebas"
    // Si tu tabla menualuser tiene parent_id, lo insertamos. Si no, omitimos.
    $hasParent = false;
    $cols = $db->query("PRAGMA table_info(menualuser)")->fetchAll(PDO::FETCH_ASSOC);
    foreach ($cols as $c) {
        if (($c['name'] ?? '') === 'parent_id') { $hasParent = true; break; }
    }

    // Evitar duplicados: usamos username único y comprobamos antes
    if ($hasParent) {
        $stmt = $db->prepare("INSERT INTO menualuser (title, username, password, expire_date, created_at, parent_id)
                              VALUES (:title, :username, :password, :expire_date, :created_at, :parent_id)");
    } else {
        $stmt = $db->prepare("INSERT INTO menualuser (title, username, password, expire_date)
                              VALUES (:title, :username, :password, :expire_date)");
    }

    $checkStmt = $db->prepare("SELECT 1 FROM menualuser WHERE username = :u LIMIT 1");

    $created = 0;
    $start = (int)($_GET['start'] ?? 600); // desde
    $count = (int)($_GET['count'] ?? 10);  // cuantos

    if ($count < 1) $count = 1;
    if ($count > $MAX_TO_CREATE) $count = $MAX_TO_CREATE;

    for ($i = $start; $i < $start + $count; $i++) {

        $title = 'Title ' . $i;
        $username = 'User' . $i;
        $password = 'Pass' . $i;

        // Validación simple
        if ($username === '' || $password === '') continue;

        // Si ya existe, saltar
        $checkStmt->execute([':u' => $username]);
        if ($checkStmt->fetchColumn()) continue;

        // Fecha random 2025-2026
        $year  = random_int(2025, 2026);
        $month = str_pad((string)random_int(1, 12), 2, '0', STR_PAD_LEFT);
        $day   = str_pad((string)random_int(1, 28), 2, '0', STR_PAD_LEFT);
        $expire_date = "$year-$month-$day";

        if ($hasParent) {
            $stmt->execute([
                ':title'      => $title,
                ':username'   => $username,
                ':password'   => $password,
                ':expire_date'=> $expire_date,
                ':created_at' => date('Y-m-d H:i:s'),
                ':parent_id'  => 0 // 0 = pruebas
            ]);
        } else {
            $stmt->execute([
                ':title'      => $title,
                ':username'   => $username,
                ':password'   => $password,
                ':expire_date'=> $expire_date
            ]);
        }

        $created++;
    }

    echo "OK. created=$created (max_per_run=$MAX_TO_CREATE)\n";
    echo "Use: a.php?token=TU_TOKEN&start=600&count=10\n";

} catch (Throwable $e) {
    http_response_code(500);
    echo "error";
}
