<?php
// api/boards.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. Please login.'], 401);
}

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

if ($method === 'GET') {
    // Vrátí všechny boards, ke kterým má uživatel přístup
    $stmt = $db->prepare('
        SELECT b.id, b.title, b.description, b.created_at, bm.role, bm.position 
        FROM boards b
        JOIN board_members bm ON b.id = bm.board_id
        WHERE bm.user_id = ?
        ORDER BY bm.position ASC, b.created_at DESC
    ');
    $stmt->execute([$userId]);
    $boards = $stmt->fetchAll();
    sendResponse(['boards' => $boards]);
} 
elseif ($method === 'POST') {
    // Vytvoření nového boardu
    $title = trim($input['title'] ?? '');
    $description = trim($input['description'] ?? '');

    if (empty($title)) {
        sendResponse(['error' => 'Board title is required.'], 400);
    }

    try {
        $db->beginTransaction();

        $stmt = $db->prepare('INSERT INTO boards (title, description, created_by) VALUES (?, ?, ?)');
        $stmt->execute([$title, $description, $userId]);
        $boardId = $db->lastInsertId();

        // Nastavení výchozí pozice pro tvůrce v levém menu
        $stmtMaxPos = $db->prepare('SELECT MAX(position) as max_pos FROM board_members WHERE user_id = ?');
        $stmtMaxPos->execute([$userId]);
        $rowPos = $stmtMaxPos->fetch();
        $newMemberPos = ($rowPos['max_pos'] !== null) ? $rowPos['max_pos'] + 1 : 0;

        // Přidání tvůrce jako vlastníka
        $stmtMember = $db->prepare('INSERT INTO board_members (board_id, user_id, role, position) VALUES (?, ?, "owner", ?)');
        $stmtMember->execute([$boardId, $userId, $newMemberPos]);

        // Přidání výchozích sloupců
        $stmtCol = $db->prepare('INSERT INTO columns (board_id, title, position) VALUES (?, ?, ?)');
        
        $defaultColumns = $input['default_columns'] ?? ['To Do', 'In Progress', 'Done'];
        foreach ($defaultColumns as $index => $colTitle) {
            $stmtCol->execute([$boardId, trim($colTitle), $index]);
        }

        $db->commit();

        sendResponse([
            'message' => 'Board created successfully.',
            'board' => ['id' => $boardId, 'title' => $title, 'description' => $description, 'role' => 'owner']
        ], 201);
    } catch (Exception $e) {
        $db->rollBack();
        sendResponse(['error' => 'Failed to create board.'], 500);
    }
}
elseif ($method === 'DELETE') {
    // Smazání boardu (pouze 'owner')
    $boardId = $input['id'] ?? null;
    if (!$boardId) sendResponse(['error' => 'Board ID is required.'], 400);

    // Kontrola oprávnění ownera
    $stmtCheck = $db->prepare('SELECT role FROM board_members WHERE board_id = ? AND user_id = ?');
    $stmtCheck->execute([$boardId, $userId]);
    $member = $stmtCheck->fetch();

    if (!$member || $member['role'] !== 'owner') {
        sendResponse(['error' => 'You do not have permission to delete this board.'], 403);
    }

    $stmtDel = $db->prepare('DELETE FROM boards WHERE id = ?');
    $stmtDel->execute([$boardId]);

    sendResponse(['message' => 'Board deleted successfully.']);
}
elseif ($method === 'PUT') {
    $action = $input['action'] ?? '';

    if ($action === 'move') {
        // Reordering boards for the current user
        $boardIdToMove = $input['board_id'] ?? null;
        $newPosition = $input['new_position'] ?? 0;

        if (!$boardIdToMove) sendResponse(['error' => 'Board ID is required.'], 400);

        try {
            $db->beginTransaction();
            // Shift other boards down
            $stmtShift = $db->prepare('UPDATE board_members SET position = position + 1 WHERE user_id = ? AND position >= ? AND board_id != ?');
            $stmtShift->execute([$userId, $newPosition, $boardIdToMove]);

            // Update the moved board's position
            $stmtMove = $db->prepare('UPDATE board_members SET position = ? WHERE user_id = ? AND board_id = ?');
            $stmtMove->execute([$newPosition, $userId, $boardIdToMove]);

            $db->commit();
            sendResponse(['message' => 'Board moved successfully.']);
        } catch (Exception $e) {
            $db->rollBack();
            sendResponse(['error' => 'Failed to move board.'], 500);
        }
    } else {
        // Úprava boardu (přejmenování / popis)
        $boardId = $input['id'] ?? null;
        $title = trim($input['title'] ?? '');
        $description = isset($input['description']) ? trim($input['description']) : null;

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

        $stmtCheck = $db->prepare('SELECT role FROM board_members WHERE board_id = ? AND user_id = ?');
        $stmtCheck->execute([$boardId, $userId]);
        $member = $stmtCheck->fetch();

        if (!$member || ($member['role'] !== 'owner' && $member['role'] !== 'editor')) {
            sendResponse(['error' => 'Permission denied.'], 403);
        }

        if ($description !== null) {
            $stmt = $db->prepare('UPDATE boards SET title = ?, description = ? WHERE id = ?');
            $stmt->execute([$title, $description, $boardId]);
        } else {
            $stmt = $db->prepare('UPDATE boards SET title = ? WHERE id = ?');
            $stmt->execute([$title, $boardId]);
        }

        sendResponse(['message' => 'Board updated successfully.']);
    }
}
else {
    sendResponse(['error' => 'Invalid method.'], 405);
}
