<?php

declare(strict_types=1);

require __DIR__ . '/_lib.php';

// Leaving the console with a private line open hangs it up properly
// (1.5.5): the caller on that node is told instead of left talking
// to a dead wire.
$uid = (int)($_SESSION['admin_uid'] ?? 0);
$talk = (int)($_SESSION['talk_node'] ?? 0);
if ($uid > 0 && $talk > 0 && atdt_installed()) {
    try {
        $db = atdt_db();
        $live = $db->one(
            'SELECT node FROM sessions WHERE active = 1 AND user_id IS NOT NULL AND node = ?',
            [$talk]
        );
        if ($live !== null) {
            $handle = (string)($db->val('SELECT handle FROM users WHERE id = ?', [$uid]) ?? 'Sysop');
            \Atdt\Chat::post($db, 0, $handle, 'hung up the private line', 'sysophup', $talk);
        }
    } catch (\Throwable $e) {
        // Logging out must never fail over a courtesy line.
    }
}
unset($_SESSION['talk_node']);

unset($_SESSION['admin_uid']);
session_regenerate_id(true);
admin_redirect('login.php');
