<?php
/**
 * Execute uma vez para criar o banco e tabelas.
 * Acesse: https://launcher2026.x-ui.shop/install.php
 */
require_once __DIR__ . '/config.php';

$messages = [];

try {
    $pdo = new PDO(
        'mysql:host=' . DB_HOST . ';charset=' . DB_CHARSET,
        DB_USER,
        DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
    $pdo->exec('CREATE DATABASE IF NOT EXISTS `' . DB_NAME . '` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci');
    $pdo->exec('USE `' . DB_NAME . '`');

    $pdo->exec("CREATE TABLE IF NOT EXISTS settings (
        setting_key VARCHAR(64) PRIMARY KEY,
        setting_value TEXT
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS dns_servers (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(120) NOT NULL,
        server_url VARCHAR(512) NOT NULL,
        username VARCHAR(120) DEFAULT NULL,
        password VARCHAR(120) DEFAULT NULL,
        is_active TINYINT(1) DEFAULT 1,
        priority INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS panel_apps (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(120) NOT NULL,
        package_name VARCHAR(255) DEFAULT NULL,
        icon_file VARCHAR(255) NOT NULL,
        apk_file VARCHAR(255) DEFAULT NULL,
        sort_order INT DEFAULT 0,
        is_enabled TINYINT(1) DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS devices (
        id CHAR(36) PRIMARY KEY,
        label VARCHAR(120) DEFAULT NULL,
        device_model VARCHAR(120) DEFAULT NULL,
        app_name VARCHAR(120) DEFAULT 'NEXUS TV',
        logo_file VARCHAR(255) DEFAULT NULL,
        wallpaper_file VARCHAR(255) DEFAULT NULL,
        launcher_blocked TINYINT(1) DEFAULT 0,
        block_message TEXT DEFAULT NULL,
        settings_lock_enabled TINYINT(1) DEFAULT 0,
        settings_lock_hash VARCHAR(64) DEFAULT NULL,
        iptv_reset_nonce INT UNSIGNED NOT NULL DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        last_seen_at TIMESTAMP NULL DEFAULT NULL,
        last_ip VARCHAR(45) DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS device_apps (
        id INT AUTO_INCREMENT PRIMARY KEY,
        device_id CHAR(36) NOT NULL,
        name VARCHAR(120) NOT NULL,
        package_name VARCHAR(255) DEFAULT NULL,
        icon_file VARCHAR(255) NOT NULL,
        apk_file VARCHAR(255) DEFAULT NULL,
        sort_order INT DEFAULT 0,
        is_enabled TINYINT(1) DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_device_apps_device (device_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $defaults = [
        'app_name' => 'NEXUS TV',
        'launcher_blocked' => '0',
        'block_message' => 'Este launcher foi desativado pelo administrador. Entre em contato com o suporte.',
        'settings_lock_enabled' => '0',
        'settings_lock_hash' => '',
    ];
    foreach ($defaults as $k => $v) {
        $stmt = $pdo->prepare('INSERT IGNORE INTO settings (setting_key, setting_value) VALUES (?, ?)');
        $stmt->execute([$k, $v]);
    }
    $stmt = $pdo->prepare('INSERT IGNORE INTO settings (setting_key, setting_value) VALUES (?, ?)');
    $stmt->execute(['admin_username', ADMIN_USER]);
    $stmt = $pdo->prepare('INSERT IGNORE INTO settings (setting_key, setting_value) VALUES (?, ?)');
    $stmt->execute(['admin_password_hash', password_hash(ADMIN_PASS, PASSWORD_DEFAULT)]);

    require_once __DIR__ . '/includes/helpers.php';
    ensure_upload_dirs();

    $messages[] = 'Instalação concluída com sucesso!';
    $messages[] = 'Remova ou proteja install.php em produção.';
    $messages[] = 'Login: ' . ADMIN_USER . ' / ' . ADMIN_PASS;
} catch (Throwable $e) {
    $messages[] = 'Erro: ' . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <title>Instalação - LauncherIO2026</title>
    <link rel="stylesheet" href="assets/css/admin.css">
</head>
<body class="login-page">
<div class="card" style="max-width:520px;margin:80px auto;">
    <h1>Instalação do Painel</h1>
    <?php foreach ($messages as $m): ?>
        <p class="flash info"><?= htmlspecialchars($m) ?></p>
    <?php endforeach; ?>
    <a href="login.php" class="btn primary">Ir para login</a>
</div>
</body>
</html>
