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

/**
 * Pomocná funkce pro ověření, zda má uživatel přístup k boardu.
 * Návratová hodnota je role v daném boardu nebo false.
 */
function getBoardRole($db, $boardId, $userId) {
    $stmt = $db->prepare('SELECT role FROM board_members WHERE board_id = ? AND user_id = ?');
    $stmt->execute([$boardId, $userId]);
    $member = $stmt->fetch();
    return $member ? $member['role'] : false;
}

if ($method === 'GET') {
    $boardId = isset($_GET['board_id']) ? intval($_GET['board_id']) : 0;
    if (!$boardId) sendResponse(['error' => 'Board ID is required.'], 400);

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

    $stmt = $db->prepare('SELECT id, title, position FROM columns WHERE board_id = ? ORDER BY position ASC');
    $stmt->execute([$boardId]);
    $columns = $stmt->fetchAll();

    sendResponse(['columns' => $columns]);
}
elseif ($method === 'POST') {
    // Vytvoření nového sloupce
    $boardId = $input['board_id'] ?? 0;
    $title = trim($input['title'] ?? '');

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

    $role = getBoardRole($db, $boardId, $userId);
    if (!$role || $role === 'viewer') {
        sendResponse(['error' => 'Permission denied.'], 403);
    }

    // Určení poslední pozice
    $stmtPos = $db->prepare('SELECT MAX(position) as max_pos FROM columns WHERE board_id = ?');
    $stmtPos->execute([$boardId]);
    $row = $stmtPos->fetch();
    $newPos = ($row['max_pos'] !== null) ? $row['max_pos'] + 1 : 0;

    $stmt = $db->prepare('INSERT INTO columns (board_id, title, position) VALUES (?, ?, ?)');
    $stmt->execute([$boardId, $title, $newPos]);
    
    sendResponse([
        'message' => 'Column created successfully.',
        'column' => ['id' => $db->lastInsertId(), 'board_id' => $boardId, 'title' => $title, 'position' => $newPos]
    ], 201);
}
elseif ($method === 'PUT') {
    // Úprava sloupce (třeba i pozice pro drag and drop)
    $columnId = $input['id'] ?? null;
    $title = trim($input['title'] ?? '');
    
    // Specifické pro drag'n'drop (případná dávková aktualizace pozic)
    $positions = $input['positions'] ?? null;

    if ($positions && is_array($positions)) {
        // Hromadný update pozic: $positions = [{id: 1, position: 0}, {id: 2, position: 1}]
        try {
            $db->beginTransaction();
            $stmt = $db->prepare('UPDATE columns SET position = ? WHERE id = ?');
            foreach ($positions as $posData) {
                $stmt->execute([$posData['position'], $posData['id']]);
            }
            $db->commit();
            sendResponse(['message' => 'Positions updated.']);
        } catch (Exception $e) {
            $db->rollBack();
            sendResponse(['error' => 'Update failed.'], 500);
        }
    } else {
        // Běžná změna názvu jednoho sloupce
        if (!$columnId || empty($title)) {
            sendResponse(['error' => 'Column ID and title are required.'], 400);
        }

        // Zkontrolujeme oprávnění přes db:
        $stmtCol = $db->prepare('SELECT board_id FROM columns WHERE id = ?');
        $stmtCol->execute([$columnId]);
        $column = $stmtCol->fetch();

        if (!$column) sendResponse(['error' => 'Column not found.'], 404);

        $role = getBoardRole($db, $column['board_id'], $userId);
        if (!$role || $role === 'viewer') {
            sendResponse(['error' => 'Permission denied.'], 403);
        }

        $stmt = $db->prepare('UPDATE columns SET title = ? WHERE id = ?');
        $stmt->execute([$title, $columnId]);
        sendResponse(['message' => 'Column updated.']);
    }
}
elseif ($method === 'DELETE') {
    // Smazání sloupce
    $columnId = $input['id'] ?? null;
    if (!$columnId) sendResponse(['error' => 'Column ID is required.'], 400);

    // Zkontrolujeme oprávnění přes db:
    $stmtCol = $db->prepare('SELECT board_id FROM columns WHERE id = ?');
    $stmtCol->execute([$columnId]);
    $column = $stmtCol->fetch();

    if (!$column) sendResponse(['error' => 'Column not found.'], 404);

    $role = getBoardRole($db, $column['board_id'], $userId);
    if (!$role || $role === 'viewer') {
        sendResponse(['error' => 'Permission denied.'], 403);
    }
    
    $stmt = $db->prepare('DELETE FROM columns WHERE id = ?');
    $stmt->execute([$columnId]);
    sendResponse(['message' => 'Column deleted.']);
}
else {
    sendResponse(['error' => 'Invalid method.'], 405);
}
