<?php
/** Minimal PDO singleton — utf8mb4.  Mirrors lib/db.php in the main api. */

function db(): PDO {
    static $pdo = null;
    if ($pdo) return $pdo;

    $dsn = sprintf(
        'mysql:host=%s;port=%d;dbname=%s;charset=utf8mb4',
        DB_HOST, DB_PORT, DB_NAME
    );
    try {
        $pdo = new PDO($dsn, DB_USER, DB_PASS, [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ]);
    } catch (Throwable $e) {
        json_error(500, 'Database connection failed: ' . $e->getMessage());
    }
    return $pdo;
}

/** Idempotent — makes sure the `users` table + `ads_enabled` column exist.
 *  Safe to call on every request because both statements use IF NOT EXISTS
 *  / try-catch guards so they only execute DDL the first time. */
function ensure_schema(): void {
    static $done = false;
    if ($done) return;
    $done = true;

    $create = <<<SQL
CREATE TABLE IF NOT EXISTS `users` (
  `id`              VARCHAR(64)  NOT NULL PRIMARY KEY,
  `username`        VARCHAR(64)  NOT NULL UNIQUE,
  `password_hash`   VARCHAR(255) NOT NULL,
  `role`            VARCHAR(16)  NOT NULL DEFAULT 'user',
  `created_at`      VARCHAR(40)  NOT NULL,
  `expiry_at`       VARCHAR(40)           DEFAULT NULL,
  `xtream_mode`     VARCHAR(16)  NOT NULL DEFAULT 'shared',
  `xtream_server`   VARCHAR(500) NOT NULL DEFAULT '',
  `xtream_username` VARCHAR(255) NOT NULL DEFAULT '',
  `xtream_password` VARCHAR(255) NOT NULL DEFAULT '',
  `note`            TEXT         NOT NULL,
  `ads_enabled`     TINYINT(1)            DEFAULT NULL,
  INDEX `ix_users_role` (`role`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
SQL;
    db()->exec($create);

    // Add the column on pre-existing deployments where the table already
    // existed without ads_enabled.  Ignore duplicate-column errors.
    try {
        db()->exec("ALTER TABLE `users` ADD COLUMN `ads_enabled` TINYINT(1) DEFAULT NULL");
    } catch (Throwable $e) { /* column exists */ }
}
