<?php
// Simple config and DB bootstrap

function pdo()
{
    static $pdo = null;
    if ($pdo !== null) return $pdo;

    $host = 'localhost';
    $dbname = 'yaetfswo_digital';
    $username = 'yaetfswo_digital';
    $password = 'et.8PJ9ikUnuVG2';

    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);

    // Ensure schema
    $pdo->exec("CREATE TABLE IF NOT EXISTS categories (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(50) NOT NULL UNIQUE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS channels (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        uri VARCHAR(255) NOT NULL,
        category_id INT,
        logo VARCHAR(255),
        drm_scheme VARCHAR(50),
        drm_license_uri VARCHAR(255),
        headers TEXT,
        webview ENUM('yes','no') DEFAULT 'no',
        isMagis TINYINT(1) DEFAULT 0,
        default_KID VARCHAR(255),
        adultos TINYINT(1) DEFAULT 0,
        claroandina TINYINT(1) DEFAULT 0,
        groupid VARCHAR(255),
        FOREIGN KEY (category_id) REFERENCES categories(id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    // In case table existed without these columns
    try { $pdo->exec("ALTER TABLE channels ADD COLUMN adultos TINYINT(1) DEFAULT 0"); } catch (Throwable $e) { /* ignore */ }
    try { $pdo->exec("ALTER TABLE channels ADD COLUMN claroandina TINYINT(1) DEFAULT 0"); } catch (Throwable $e) { /* ignore */ }
    try { $pdo->exec("ALTER TABLE channels ADD COLUMN groupid VARCHAR(255)"); } catch (Throwable $e) { /* ignore */ }

    return $pdo;
}

function h($s) { return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }

