<?php

namespace Miladmodaresi\Taamito\Api;

use WP_REST_Request;

/**
 * The Singleton class defines the `GetInstance` method that serves as an
 * alternative to constructor and lets clients access the same instance of this
 * class over and over.
 */
class Category
{
    public function create(WP_REST_Request $request)
    {
        $input = $request->get_body_params();
        if (!$input || !count($input))
            $input =   json_decode($request->get_body(), true);
        $category = wp_insert_term($input['category'], 'product_cat', ['parent' => $input['parent_id']]);
        $file = $request->get_file_params();
        if (isset($file['logo'])) {
            $file = taamitoApp()->uploadImage($file['logo'], ['title' => $input['category']]);
            update_term_meta($category['term_id'], 'thumbnail_id', absint($file));
        }

        return taamitoApp()->view($category);
    }
    public function update(WP_REST_Request $request)
    {
        $input = $request->get_body_params();
        
        $params = $request->get_query_params();

        $category = wp_update_term($params['id'], 'product_cat', ['parent' => $input['parent_id'], 'name' => $input['category']]);
        $file = $request->get_file_params();
        if (isset($file['logo'])) {
            $file = taamitoApp()->uploadImage($file['logo'], ['title' => $input['category']]);
            update_term_meta($category['term_id'], 'thumbnail_id', absint($file));
        }

        return taamitoApp()->view($category);
    }
    public function delete(WP_REST_Request $request)
    {
        $params = $request->get_query_params();

        $category = wp_delete_term($params['id'], 'product_cat');
        return taamitoApp()->view($category);
    }
}
