<?php
// api/comments.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);

/**
 * Zkontroluje, zda má uživatel právo číst/psát do daného úkolu.
 */
function checkTaskAccess($db, $taskId, $userId) {
    $stmt = $db->prepare('
        SELECT bm.role, c.board_id 
        FROM tasks t
        JOIN columns c ON t.column_id = c.id
        JOIN board_members bm ON c.board_id = bm.board_id
        WHERE t.id = ? AND bm.user_id = ?
    ');
    $stmt->execute([$taskId, $userId]);
    return $stmt->fetch();
}

if ($method === 'GET') {
    $taskId = isset($_GET['task_id']) ? intval($_GET['task_id']) : 0;
    if (!$taskId) sendResponse(['error' => 'Missing task_id parameters.'], 400);

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

    // Načteme komentáře se jmény uživatelů
    $stmt = $db->prepare('
        SELECT tc.id, tc.task_id, tc.user_id, tc.content, tc.created_at, u.username
        FROM task_comments tc
        JOIN users u ON tc.user_id = u.id
        WHERE tc.task_id = ?
        ORDER BY tc.created_at ASC
    ');
    $stmt->execute([$taskId]);
    $comments = $stmt->fetchAll();
    
    // Zapíšeme uložení přečtení
    if (!empty($comments)) {
        $maxId = end($comments)['id'];
        $stmtUpd = $db->prepare('INSERT INTO task_reads (user_id, task_id, last_read_comment_id) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE last_read_comment_id = VALUES(last_read_comment_id)');
        $stmtUpd->execute([$userId, $taskId, $maxId]);
    }

    sendResponse(['comments' => $comments]);
}
elseif ($method === 'POST') {
    $taskId = $input['task_id'] ?? 0;
    $content = trim($input['content'] ?? '');

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

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

    $stmt = $db->prepare('INSERT INTO task_comments (task_id, user_id, content) VALUES (?, ?, ?)');
    $stmt->execute([$taskId, $userId, $content]);

    // Odeslat obratem nově vložený komentář
    $newId = $db->lastInsertId();
    $stmtGet = $db->prepare('
        SELECT tc.id, tc.task_id, tc.user_id, tc.content, tc.created_at, u.username
        FROM task_comments tc
        JOIN users u ON tc.user_id = u.id
        WHERE tc.id = ?
    ');
    $stmtGet->execute([$newId]);
    $newComment = $stmtGet->fetch();

    $stmtUpd = $db->prepare('INSERT INTO task_reads (user_id, task_id, last_read_comment_id) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE last_read_comment_id = VALUES(last_read_comment_id)');
    $stmtUpd->execute([$userId, $taskId, $newId]);

    sendResponse([
        'message' => 'Comment added.',
        'comment' => $newComment
    ], 201);
}
else {
    sendResponse(['error' => 'Invalid method.'], 405);
}
