<?php
// api/board_chat.php
require_once __DIR__ . '/db.php';
session_start();

header('Content-Type: application/json');

function sendResponse($data, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode($data);
    exit;
}

if (!isset($_SESSION['user_id'])) {
    sendResponse(['error' => 'Unauthorized.'], 401);
}

$db = Database::getInstance()->getConnection();
$method = $_SERVER['REQUEST_METHOD'];
$userId = $_SESSION['user_id'];
$input = json_decode(file_get_contents('php://input'), true);

function checkBoardAccess($db, $boardId, $userId) {
    $stmt = $db->prepare('SELECT role FROM board_members WHERE board_id = ? AND user_id = ?');
    $stmt->execute([$boardId, $userId]);
    return $stmt->fetch();
}

if ($method === 'GET') {
    $boardId = isset($_GET['board_id']) ? intval($_GET['board_id']) : 0;
    $action = isset($_GET['action']) ? $_GET['action'] : '';

    if (!$boardId) sendResponse(['error' => 'Missing board_id parameter.'], 400);

    $access = checkBoardAccess($db, $boardId, $userId);
    if (!$access) sendResponse(['error' => 'Access denied.'], 403);

    if ($action === 'unread') {
        // Zjistíme, jaké zprávy uživatel ještě nečetl
        $stmt = $db->prepare('SELECT last_read_message_id FROM board_members WHERE board_id = ? AND user_id = ?');
        $stmt->execute([$boardId, $userId]);
        $member = $stmt->fetch();
        $lastReadId = $member ? (int)$member['last_read_message_id'] : 0;

        $stmt2 = $db->prepare('SELECT COUNT(*) as unread_count FROM board_messages WHERE board_id = ? AND user_id != ? AND id > ?');
        $stmt2->execute([$boardId, $userId, $lastReadId]);
        $unreadCount = $stmt2->fetch()['unread_count'];

        sendResponse(['unread_count' => $unreadCount]);
    }

    // Načtení zpráv (limit např. posledních 100 zpráv by dával smysl pro produkci, prozatím vezmeme všechny, pokud jich není tisíce)
    $stmt = $db->prepare('
        SELECT m.id, m.user_id, m.content, m.created_at, u.username as sender_name
        FROM board_messages m
        JOIN users u ON m.user_id = u.id
        WHERE m.board_id = ?
        ORDER BY m.created_at ASC
    ');
    $stmt->execute([$boardId]);
    $messages = $stmt->fetchAll();

    // Po načtení označíme zprávy jako přečtené (updatujeme last_read_message_id na nejvyšší načtené ID)
    if (!empty($messages)) {
        $maxId = end($messages)['id'];
        $stmtUpd = $db->prepare('UPDATE board_members SET last_read_message_id = ? WHERE board_id = ? AND user_id = ?');
        $stmtUpd->execute([$maxId, $boardId, $userId]);
    }

    sendResponse(['messages' => $messages]);
}
elseif ($method === 'POST') {
    $boardId = isset($input['board_id']) ? intval($input['board_id']) : 0;
    $content = trim($input['content'] ?? '');

    if (!$boardId || empty($content)) {
        sendResponse(['error' => 'Board ID and content are required.'], 400);
    }

    $access = checkBoardAccess($db, $boardId, $userId);
    if (!$access || $access['role'] === 'viewer') {
        sendResponse(['error' => 'Permission denied. Viewers cannot post messages.'], 403);
    }

    $stmt = $db->prepare('INSERT INTO board_messages (board_id, user_id, content) VALUES (?, ?, ?)');
    $stmt->execute([$boardId, $userId, $content]);

    sendResponse(['message' => 'Message sent.']);
}
else {
    sendResponse(['error' => 'Invalid method.'], 405);
}
