<?php
// api/tasks.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 práva k boardu přes ID sloupce
 */
function checkColumnAccess($db, $columnId, $userId) {
    $stmt = $db->prepare('
        SELECT bm.role, c.board_id 
        FROM columns c
        JOIN board_members bm ON c.board_id = bm.board_id
        WHERE c.id = ? AND bm.user_id = ?
    ');
    $stmt->execute([$columnId, $userId]);
    return $stmt->fetch();
}

/**
 * Zkontroluje práva k boardu přes ID boardu
 */
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;
    
    if ($boardId) {
        $access = checkBoardAccess($db, $boardId, $userId);
        if (!$access) sendResponse(['error' => 'Access denied.'], 403);

        $stmt = $db->prepare('
            SELECT t.id, t.column_id, t.title, t.description, t.assigned_to, t.due_date, t.position, t.created_at, u.username as assigned_username,
                   (SELECT COUNT(*) FROM task_comments tc1 WHERE tc1.task_id = t.id) as comment_count,
                   (SELECT COUNT(*) FROM task_comments tc2 WHERE tc2.task_id = t.id AND tc2.user_id != :uid1 AND tc2.id > COALESCE((SELECT tr.last_read_comment_id FROM task_reads tr WHERE tr.task_id = t.id AND tr.user_id = :uid2), 0)) as unread_comment_count
            FROM tasks t
            JOIN columns c ON t.column_id = c.id
            LEFT JOIN users u ON t.assigned_to = u.id
            WHERE c.board_id = :bid
            ORDER BY t.position ASC
        ');
        $stmt->execute(['uid1' => $userId, 'uid2' => $userId, 'bid' => $boardId]);
        $tasks = $stmt->fetchAll();
        sendResponse(['tasks' => $tasks]);
    } else {
        sendResponse(['error' => 'Missing board_id parameter.'], 400);
    }
}
elseif ($method === 'POST') {
    $columnId = $input['column_id'] ?? 0;
    $title = trim($input['title'] ?? '');
    $description = trim($input['description'] ?? '');
    $assignedTo = !empty($input['assigned_to']) ? intval($input['assigned_to']) : null;
    $dueDate = !empty($input['due_date']) ? trim($input['due_date']) : null;

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

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

    $stmtPos = $db->prepare('SELECT MAX(position) as max_pos FROM tasks WHERE column_id = ?');
    $stmtPos->execute([$columnId]);
    $row = $stmtPos->fetch();
    $newPos = ($row['max_pos'] !== null) ? $row['max_pos'] + 1 : 0;

    $stmt = $db->prepare('INSERT INTO tasks (column_id, title, description, assigned_to, due_date, position, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)');
    $stmt->execute([$columnId, $title, $description, $assignedTo, $dueDate, $newPos, $userId]);

    sendResponse([
        'message' => 'Task created.',
        'task' => [
            'id' => $db->lastInsertId(),
            'column_id' => $columnId,
            'title' => $title,
            'description' => $description,
            'assigned_to' => $assignedTo,
            'due_date' => $dueDate,
            'position' => $newPos,
            'created_by' => $userId
        ]
    ], 201);
}
elseif ($method === 'PUT') {
    $action = $input['action'] ?? '';

    // Drag and Drop reordering (multiple tasks or single task move)
    if ($action === 'move') {
        $taskId = $input['task_id'] ?? null;
        $newColumnId = $input['new_column_id'] ?? null;
        $newPosition = $input['new_position'] ?? 0;

        if (!$taskId || !$newColumnId) sendResponse(['error' => 'Missing parameters.'], 400);
        
        // Ověření, že uživatel může přistupovat do tohoto boardu (nového i starého sloupce)
        $access = checkColumnAccess($db, $newColumnId, $userId);
        if (!$access || $access['role'] === 'viewer') sendResponse(['error' => 'Permission denied.'], 403);

        try {
            $db->beginTransaction();
            // Upravíme pozice ve stejném sloupci apod. Zde pro jednoduchost updatujeme napřímo.
            // Posuneme všechny tasky s pozicí >= newPosition o jedna dolů
            $stmtShift = $db->prepare('UPDATE tasks SET position = position + 1 WHERE column_id = ? AND position >= ? AND id != ?');
            $stmtShift->execute([$newColumnId, $newPosition, $taskId]);

            // Upravíme přesunutý task
            $stmtMove = $db->prepare('UPDATE tasks SET column_id = ?, position = ? WHERE id = ?');
            $stmtMove->execute([$newColumnId, $newPosition, $taskId]);

            // Normalizovat zbylé tasky v původním i novém sloupci (optional robustnost)
            $db->commit();
            sendResponse(['message' => 'Task moved.']);
        } catch (Exception $e) {
            $db->rollBack();
            sendResponse(['error' => 'Failed to move task.'], 500);
        }
    } 
    elseif ($action === 'update') {
        $taskId = $input['id'] ?? null;
        $title = trim($input['title'] ?? '');
        $description = trim($input['description'] ?? '');
        $assignedTo = !empty($input['assigned_to']) ? intval($input['assigned_to']) : null;
        $dueDate = !empty($input['due_date']) ? trim($input['due_date']) : null;

        if (!$taskId || empty($title)) sendResponse(['error' => 'Missing ID or title.'], 400);

        // Security check
        $stmtCheck = $db->prepare('SELECT column_id FROM tasks WHERE id = ?');
        $stmtCheck->execute([$taskId]);
        $task = $stmtCheck->fetch();

        if (!$task) sendResponse(['error' => 'Task not found.'], 404);
        
        $access = checkColumnAccess($db, $task['column_id'], $userId);
        if (!$access || $access['role'] === 'viewer') sendResponse(['error' => 'Permission denied.'], 403);

        $stmt = $db->prepare('UPDATE tasks SET title = ?, description = ?, assigned_to = ?, due_date = ? WHERE id = ?');
        $stmt->execute([$title, $description, $assignedTo, $dueDate, $taskId]);

        sendResponse(['message' => 'Task updated.']);
    }
    else {
        sendResponse(['error' => 'Unknown action.'], 400);
    }
}
elseif ($method === 'DELETE') {
    $taskId = $input['id'] ?? null;
    if (!$taskId) sendResponse(['error' => 'Missing ID.'], 400);

    $stmtCheck = $db->prepare('SELECT column_id FROM tasks WHERE id = ?');
    $stmtCheck->execute([$taskId]);
    $task = $stmtCheck->fetch();

    if (!$task) sendResponse(['error' => 'Task not found.'], 404);
    
    $access = checkColumnAccess($db, $task['column_id'], $userId);
    if (!$access || $access['role'] === 'viewer') sendResponse(['error' => 'Permission denied.'], 403);

    $stmt = $db->prepare('DELETE FROM tasks WHERE id = ?');
    $stmt->execute([$taskId]);

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