<?php
// cron_demo.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$db_file = __DIR__ . "/api/.db.db";

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

    $now = time();

    // Asegurar formato de los tiempos en la tabla IBOF
    $db->exec("
        UPDATE ibof
        SET demo_start = CAST(trim(demo_start) AS INTEGER),
            demo_duration = CAST(trim(demo_duration) AS INTEGER)
        WHERE is_demo = 1
    ");

    // Buscar demos expirados
    $stmt = $db->query("
        SELECT id, username, password, demo_start, demo_duration
        FROM ibof
        WHERE is_demo = 1
          AND demo_start IS NOT NULL
          AND demo_duration IS NOT NULL
    ");
    $allDemos = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($allDemos as $row) {
        $id = $row['id'];
        $username = $row['username'];
        $password = $row['password'];

        $demo_start = intval($row['demo_start']);
        $demo_duration = intval($row['demo_duration']);
        $expire_time = $demo_start + $demo_duration;

        if ($expire_time <= $now) {
            // Bloquear demo agregando "_" a la clave
            if (substr($password, -1) !== "_") {
                $newPassword = $password . "_";

                $upd = $db->prepare("
                    UPDATE ibof
                    SET password = :password,
                        udate = :udate
                    WHERE id = :id
                ");
                $upd->execute([
                    ':password' => $newPassword,
                    ':udate' => date('Y-m-d'),
                    ':id' => $id
                ]);

                // Guardar un registro de lo que se bloqueó
                file_put_contents(__DIR__ . "/cron_demo.log",
                    "[" . date("Y-m-d H:i:s") . "] Bloqueado demo ID=$id (user=$username)\n",
                    FILE_APPEND
                );
            }
        }
    }

} catch (Exception $e) {
    file_put_contents(__DIR__ . "/cron_demo.log", "ERROR: " . $e->getMessage() . "\n", FILE_APPEND);
}
?>