<?php
// migrate_existing_trials.php
$dbFile = __DIR__ . '/.db.db';

try {
    $pdo = new PDO('sqlite:' . $dbFile);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Migrar trials existentes que no están en la tabla trials
    $stmt = $pdo->query("
        SELECT c.code, c.expires_at, c.created_at
        FROM codes c
        LEFT JOIN trials t ON c.code = t.code
        WHERE c.owner = 'trial' AND t.code IS NULL
    ");
    
    $missing = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "Migrando " . count($missing) . " trials...\n";
    
    foreach ($missing as $trial) {
        $stmt = $pdo->prepare("
            INSERT INTO trials (phone, ip, name, code, created_ts, expires_at, block_until_ts)
            VALUES (:phone, :ip, :name, :code, :created_ts, :expires_at, 0)
        ");
        
        $stmt->execute([
            ':phone' => '0000000000',
            ':ip' => '0.0.0.0',
            ':name' => 'Usuario Anónimo',
            ':code' => $trial['code'],
            ':created_ts' => strtotime($trial['created_at']),
            ':expires_at' => $trial['expires_at']
        ]);
        
        echo "✓ Migrado código: " . $trial['code'] . "\n";
    }
    
    echo "\n✅ Migración completada!\n";
    
} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
}