<?php
header('Content-Type: application/json');

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

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

    // Lista de columnas completas que necesitamos
    $required_columns = [
        "id INTEGER PRIMARY KEY",
        "dns_id INTEGER NOT NULL DEFAULT 1",
        "mac_address TEXT NOT NULL",
        "username TEXT",
        "password TEXT",
        "pin TEXT",
        "device_key TEXT",
        "link TEXT",
        "demo_start INTEGER",
        "demo_duration INTEGER",
        "last_used INTEGER DEFAULT (strftime('%s','now'))",
        "is_demo INTEGER DEFAULT 1" // 👈 nueva columna para marcar demos
    ];

    // Crear tabla si no existe
    $db->exec("CREATE TABLE IF NOT EXISTS playlist (id INTEGER PRIMARY KEY)");

    // Obtener columnas actuales
    $existing_columns = [];
    $res = $db->query("PRAGMA table_info(playlist)");
    while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
        $existing_columns[] = $row['name'];
    }

    // Agregar columnas que falten
    foreach ($required_columns as $col_def) {
        preg_match('/^(\w+)/', $col_def, $matches);
        $col_name = $matches[1];
        if (!in_array($col_name, $existing_columns)) {
            // Para la columna id, saltar porque ya existe
            if ($col_name === 'id') continue;
            $db->exec("ALTER TABLE playlist ADD COLUMN $col_def");
        }
    }

    echo json_encode(["success" => true, "message" => "✅ Tabla 'playlist' actualizada correctamente."]);

} catch (Exception $e) {
    echo json_encode(["success" => false, "message" => "❌ Error al actualizar tabla: " . $e->getMessage()]);
}
