<?php
declare(strict_types=1);

// Wspólne helpery dla admin API (Dashboard: czat + notatki)

require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/session_bootstrap.php';

header('Cache-Control: no-store');

function admin_json_response(array $payload, int $status = 200): void
{
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}

function admin_json_error(string $message, int $status = 400, array $extra = []): void
{
    admin_json_response(['success' => false, 'error' => $message] + $extra, $status);
}

function admin_require_auth(?PDO $pdo = null): array
{
    if (empty($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
        admin_json_error('Brak autoryzacji', 401);
    }
    if (empty($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
        admin_json_error('Brak uprawnień', 403);
    }

    $userId = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;
    $username = isset($_SESSION['username']) ? (string)$_SESSION['username'] : 'admin';

    // Jeśli system logowania nie ustawia user_id w sesji, spróbuj dopasować po username.
    if ($userId <= 0 && $username !== '') {
        try {
            $pdo = $pdo ?: admin_get_pdo();
            $stmt = $pdo->prepare('SELECT id FROM users WHERE username = :u LIMIT 1');
            $stmt->execute([':u' => $username]);
            $resolved = (int)($stmt->fetchColumn() ?: 0);
            if ($resolved > 0) {
                $userId = $resolved;
                $_SESSION['user_id'] = $resolved;
            }
        } catch (Throwable $e) {
            // jeśli się nie uda, zostaw 0
        }
    }

    return [
        'user_id' => $userId,
        'username' => $username,
    ];
}

function admin_get_pdo(): PDO
{
    // Utrzymujemy spójne dane logowania z panelu admina.
    $host = "localhost";
    $db = "togethere_cloud";
    $user = "root";
    $pass = "HasloDoSQL";

    try {
        $pdo = new PDO(
            "mysql:host=$host;dbname=$db;charset=utf8mb4",
            $user,
            $pass,
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
        );
        $pdo->exec("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");
        return $pdo;
    } catch (PDOException $e) {
        admin_json_error('Błąd połączenia z bazą danych', 500);
    }
}

function admin_read_json_body(): array
{
    $raw = file_get_contents('php://input');
    if ($raw === false || trim($raw) === '') {
        return [];
    }

    $decoded = json_decode($raw, true);
    if (!is_array($decoded)) {
        admin_json_error('Nieprawidłowy JSON', 400);
    }

    return $decoded;
}
