<?php
declare(strict_types=1);

require_once __DIR__ . '/config.php';

header('Content-Type: text/html; charset=utf-8');

function h(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function schema(PDO $db): void
{
    $db->exec("
        CREATE TABLE IF NOT EXISTS devices (
            id INTEGER PRIMARY KEY,
            device_id TEXT UNIQUE,
            device_name TEXT,
            app_type TEXT,
            app_version TEXT,
            hostname TEXT,
            connection_type TEXT,
            port TEXT,
            available_ports TEXT NULL,
            available_baudrates TEXT NULL,
            baudrate INTEGER,
            last_seen TEXT,
            last_ip TEXT,
            enabled INTEGER DEFAULT 1,
            created_at TEXT,
            updated_at TEXT
        );

        CREATE TABLE IF NOT EXISTS logs (
            id INTEGER PRIMARY KEY,
            device_id TEXT,
            created_at TEXT,
            direction TEXT,
            format TEXT,
            data TEXT,
            level TEXT DEFAULT 'info'
        );

        CREATE TABLE IF NOT EXISTS rules (
            id INTEGER PRIMARY KEY,
            device_id TEXT NULL,
            name TEXT,
            enabled INTEGER DEFAULT 1,
            match_type TEXT,
            pattern TEXT,
            action_email INTEGER DEFAULT 0,
            action_alarm INTEGER DEFAULT 0,
            action_highlight INTEGER DEFAULT 0,
            highlight_level TEXT,
            cooldown_seconds INTEGER DEFAULT 1800,
            last_triggered_at TEXT NULL
        );

        CREATE TABLE IF NOT EXISTS alarms (
            id INTEGER PRIMARY KEY,
            device_id TEXT,
            rule_id INTEGER,
            created_at TEXT,
            message TEXT,
            status TEXT DEFAULT 'active',
            acknowledged_at TEXT NULL,
            acknowledged_by TEXT NULL
        );

        CREATE TABLE IF NOT EXISTS commands (
            id INTEGER PRIMARY KEY,
            device_id TEXT,
            created_at TEXT,
            command TEXT,
            command_type TEXT DEFAULT 'send',
            payload TEXT NULL,
            status TEXT DEFAULT 'pending',
            response TEXT NULL,
            sent_at TEXT NULL,
            done_at TEXT NULL
        );

        CREATE INDEX IF NOT EXISTS idx_logs_device_created ON logs(device_id, created_at);
        CREATE INDEX IF NOT EXISTS idx_alarms_status_created ON alarms(status, created_at);
        CREATE INDEX IF NOT EXISTS idx_rules_enabled ON rules(enabled);
        CREATE INDEX IF NOT EXISTS idx_commands_device_status ON commands(device_id, status);
    ");
}

$messages = [];
$ok = true;

try {
    $dataDir = dirname(DATABASE_PATH);
    if (!is_dir($dataDir)) {
        mkdir($dataDir, 0775, true);
        $messages[] = "Created data directory: " . $dataDir;
    }

    if (!is_writable($dataDir)) {
        throw new RuntimeException("Data directory is not writable: " . $dataDir);
    }

    $db = new PDO('sqlite:' . DATABASE_PATH);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    schema($db);
    $messages[] = "Database ready: " . DATABASE_PATH;

    $htaccess = $dataDir . '/.htaccess';
    if (!file_exists($htaccess)) {
        file_put_contents($htaccess, "Require all denied\nDeny from all\n");
        $messages[] = "Created data/.htaccess protection.";
    }
} catch (Throwable $e) {
    $ok = false;
    $messages[] = $e->getMessage();
}
?>
<!doctype html>
<html lang="cs">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>SST Web Monitor - instalace</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<main class="install">
    <h1>SST Web Monitor - instalace</h1>
    <p class="<?= $ok ? 'status-ok' : 'status-error' ?>"><?= $ok ? 'Instalace proběhla úspěšně.' : 'Instalace selhala.' ?></p>
    <ul>
        <?php foreach ($messages as $message): ?>
            <li><?= h($message) ?></li>
        <?php endforeach; ?>
    </ul>
    <p>Po úspěšné instalaci otevři <a href="index.html">webové rozhraní</a>.</p>
    <p class="muted">Tokeny připrav v SST: Nastavení - SST Web Monitor - Kopírovat config.php. Obsah pak vlož do souboru config.php na webu.</p>
</main>
</body>
</html>
