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

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

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

    $now = time();

    // 🔹 Normalizar demo_start y demo_duration a enteros puros
    $db->exec("
        UPDATE playlist
        SET demo_start = CAST(trim(demo_start) AS INTEGER),
            demo_duration = CAST(trim(demo_duration) AS INTEGER)
        WHERE is_demo = 1
    ");

    // 🔹 Traer todos los demos activos
    $stmt = $db->query("
        SELECT id, username, password, demo_start, demo_duration
        FROM playlist
        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 "_" solo una vez
            if (substr($password, -1) !== "_") {
                $newPassword = $password . "_";

                $upd = $db->prepare("
                    UPDATE playlist
                    SET password = :password,
                        last_used = :last_used
                    WHERE id = :id
                ");
                $upd->execute([
                    ':password' => $newPassword,
                    ':last_used' => $now,
                    ':id' => $id
                ]);

                file_put_contents(__DIR__ . "/cron_demo.log",
                    "[" . date("Y-m-d H:i:s") . "] Bloqueado demo ID=$id (user=$username) | demo_start=$demo_start | duration=$demo_duration | expire_time=$expire_time | now=$now\n",
                    FILE_APPEND
                );
            }
        } else {
            // Demo activo
            file_put_contents(__DIR__ . "/cron_demo.log",
                "[" . date("Y-m-d H:i:s") . "] Activo demo ID=$id (user=$username) | demo_start=$demo_start | duration=$demo_duration | expire_time=$expire_time | now=$now\n",
                FILE_APPEND
            );
        }
    }

} catch (Exception $e) {
    file_put_contents(__DIR__ . "/cron_demo.log",
        "[" . date("Y-m-d H:i:s") . "] ERROR: " . $e->getMessage() . "\n",
        FILE_APPEND
    );
}
