// assets/js/api.js

class KanbanAPI {
    constructor() {
        this.baseUrl = 'api/'; // Relativní adresa pro lokální PHP nasazení
    }

    async request(endpoint, method = 'GET', body = null) {
        const options = {
            method,
            headers: {
                'Content-Type': 'application/json'
            }
        };

        if (body) {
            options.body = JSON.stringify(body);
        }

        try {
            const response = await fetch(this.baseUrl + endpoint, options);
            const data = await response.json();

            if (data.message && window.i18n) {
                data.message = window.i18n.t(data.message);
            }

            if (!response.ok) {
                const errMsg = data.error || (window.i18n ? window.i18n.t('alerts.api_request_failed') : 'API Request failed');
                throw new Error(window.i18n ? window.i18n.t(errMsg) : errMsg);
            }

            return data;
        } catch (error) {
            console.error('API Error:', error);
            throw error;
        }
    }

    // --- Authentication ---
    async login(username, password) {
        return this.request('auth.php?action=login', 'POST', { username, password });
    }

    async register(username, email, password) {
        return this.request('auth.php?action=register', 'POST', { username, email, password });
    }

    async logout() {
        return this.request('auth.php?action=logout', 'POST');
    }

    async forgotPassword(usernameOrEmail) {
        return this.request('auth.php?action=forgot_password', 'POST', { username: usernameOrEmail });
    }

    async resetPassword(token, newPassword) {
        return this.request('auth.php?action=reset_password', 'POST', { token, password: newPassword });
    }

    async checkSession() {
        return this.request('auth.php?action=me', 'GET');
    }

    // --- Boards ---
    async getBoards() {
        return this.request('boards.php', 'GET');
    }

    async createBoard(title, description, defaultColumns = null) {
        return this.request('boards.php', 'POST', { title, description, default_columns: defaultColumns });
    }

    async updateBoard(id, title, description) {
        return this.request('boards.php', 'PUT', { id, title, description });
    }

    async moveBoard(boardId, newPosition) {
        return this.request('boards.php', 'PUT', { action: 'move', board_id: boardId, new_position: newPosition });
    }

    async deleteBoard(id) {
        return this.request('boards.php', 'DELETE', { id });
    }

    // --- Columns ---
    async getColumns(boardId) {
        return this.request(`columns.php?board_id=${boardId}`, 'GET');
    }

    async createColumn(boardId, title) {
        return this.request('columns.php', 'POST', { board_id: boardId, title });
    }

    async updateColumn(id, title) {
        return this.request('columns.php', 'PUT', { id, title });
    }

    async updateColumnPos(positionsArr) {
        return this.request('columns.php', 'PUT', { positions: positionsArr });
    }

    async deleteColumn(id) {
        return this.request('columns.php', 'DELETE', { id });
    }

    // --- Tasks ---
    async getTasks(boardId) {
        return this.request(`tasks.php?board_id=${boardId}`, 'GET');
    }

    async createTask(columnId, title, description, assignedTo, dueDate = null) {
        return this.request('tasks.php', 'POST', {
            column_id: columnId,
            title,
            description,
            assigned_to: assignedTo || null,
            due_date: dueDate || null
        });
    }

    async updateTask(id, title, description, assignedTo, dueDate = null) {
        return this.request('tasks.php', 'PUT', {
            action: 'update',
            id,
            title,
            description,
            assigned_to: assignedTo || null,
            due_date: dueDate || null
        });
    }

    async moveTask(taskId, newColumnId, newPosition) {
        return this.request('tasks.php', 'PUT', {
            action: 'move',
            task_id: taskId,
            new_column_id: newColumnId,
            new_position: newPosition
        });
    }

    async deleteTask(id) {
        return this.request('tasks.php', 'DELETE', { id });
    }

    // --- Task Comments ---
    async getTaskComments(taskId) {
        return this.request(`comments.php?task_id=${taskId}`, 'GET');
    }

    async addTaskComment(taskId, content) {
        return this.request('comments.php', 'POST', { task_id: taskId, content });
    }

    // --- Direct Messages ---
    async getDMContacts() {
        return this.request('messages.php?action=contacts', 'GET');
    }

    async getDMConversation(userId) {
        return this.request(`messages.php?action=conversation&with_user_id=${userId}`, 'GET');
    }

    async getUnreadDMCount() {
        return this.request('messages.php?action=unread_count', 'GET');
    }

    async sendDirectMessage(receiverId, content) {
        return this.request('messages.php', 'POST', { receiver_id: receiverId, content });
    }

    async deleteChat(userId) {
        return this.request(`messages.php?action=delete_chat&with_user_id=${userId}`, 'DELETE');
    }

    // --- Board Chat ---
    async getBoardChat(boardId) {
        return this.request(`board_chat.php?board_id=${boardId}`, 'GET');
    }

    async getBoardChatUnread(boardId) {
        return this.request(`board_chat.php?board_id=${boardId}&action=unread`, 'GET');
    }

    async sendBoardChat(boardId, content) {
        return this.request('board_chat.php', 'POST', { board_id: boardId, content });
    }

    async changePassword(oldPassword, newPassword) {
        return this.request('users.php', 'PUT', { old_password: oldPassword, new_password: newPassword });
    }

    // --- Teams / Users ---
    async searchUsers(query) {
        return this.request(`users.php?search=${encodeURIComponent(query)}`, 'GET');
    }

    async getTeam(boardId) {
        return this.request(`teams.php?board_id=${boardId}`, 'GET');
    }

    async addTeamMember(boardId, userId, role) {
        return this.request('teams.php', 'POST', { board_id: boardId, user_id: userId, role });
    }

    async removeTeamMember(boardId, userId) {
        return this.request('teams.php', 'DELETE', { board_id: boardId, user_id: userId });
    }

    async updateTeamMemberRole(boardId, userId, role) {
        return this.request('teams.php', 'PUT', { board_id: boardId, user_id: userId, role });
    }
    // --- Administration ---
    async adminGetUsers() {
        return this.request('admin.php?action=users', 'GET');
    }

    async adminGetPendingUsersCount() {
        return this.request('admin.php?action=pending_users_count', 'GET');
    }

    async adminGetUserBoards(userId) {
        return this.request(`admin.php?action=user_boards&user_id=${userId}`, 'GET');
    }

    async adminToggleActive(userId, isActive) {
        return this.request('admin.php', 'PUT', { action: 'toggle_active', user_id: userId, is_active: isActive ? 1 : 0 });
    }

    async adminChangePassword(userId, newPassword) {
        return this.request('admin.php', 'PUT', { action: 'change_password', user_id: userId, new_password: newPassword });
    }

    async adminChangeUsername(userId, newUsername) {
        return this.request('admin.php', 'PUT', { action: 'change_username', user_id: userId, new_username: newUsername });
    }

    async adminTransferBoardOwnership(boardId, newOwnerUserId) {
        return this.request('admin.php', 'PUT', { action: 'change_board_owner', board_id: boardId, new_owner_user_id: newOwnerUserId });
    }

    async adminDeleteUser(userId, newOwnerId = null) {
        const body = { action: 'delete_user', user_id: userId };
        if (newOwnerId) body.new_owner_id = newOwnerId;
        return this.request('admin.php', 'DELETE', body);
    }

    async adminCheckSoleOwner(userId) {
        return this.request(`admin.php?action=check_sole_owner&user_id=${userId}`, 'GET');
    }
}

// Global API instance
window.api = new KanbanAPI();
