
class AjaxManager {

    static async getAll() {
        let categories = await AjaxManager.get('category');
        let articles = await AjaxManager.get('article');
        let article_categories = await AjaxManager.get('article_categories');
        return {articles: articles, categories: categories, article_categories: article_categories};
    }

    static async get(type) {
        let data = {
            type: type,
            action: 'get',
        };
        let response = await $.ajax({
            type: "POST",
            url: "json_ajax.php",
            data: JSON.stringify(data),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
        });
        console.log(response);
        return response['data'];
    }

    static async delete(id, type) {
        let data = {
            type: type,
            action: 'remove',
            data: id,
        };
        let response = await $.ajax({
            type: "POST",
            url: "json_ajax.php",
            data: JSON.stringify(data),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
        });
        console.log(response);
        return response['status'];
    }

    static async save(data, isNew, type) {
        let formattedData = {
            type: type,
            action: isNew ? 'create' : 'update',
            data: data,
        };
        let response = await $.ajax({
            type: "POST",
            url: "json_ajax.php",
            data: JSON.stringify(formattedData),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
        });
        console.log(response);
        return response['data'];
    }

    static async saveArticleImage(image, id) {
        if (image !== undefined) {
            let formData = new FormData();
            formData.append('type', 'image');
            formData.append('data', id);
            formData.append('image', image);
            let response = await $.ajax({
                type: "POST",
                url: "form_ajax.php",
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
            });
            response = JSON.parse(response);
            console.log(response);
            return response['status'];
        } else
            return 1;
    }

    static async saveStockChange(data, isSell) {
        let formattedData = {
            type: 'stock',
            action: isSell ? 'sell' : 'buy',
            data: data,
        };
        let response = await $.ajax({
            type: "POST",
            url: "json_ajax.php",
            data: JSON.stringify(formattedData),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
        });
        console.log(response);
        return response['data'];
    }
}



