<?php

namespace Miladmodaresi\Taamito\Api;

use Miladmodaresi\Taamito\Services\ProductService as BaseProduct;
use WC_Product;
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 Product
{
    public function create(WP_REST_Request $input)
    {
        $request = $input->get_body_params();
        if (!$request)
            $request = $input->get_json_params();

        $files = $input->get_file_params();
        $product = new BaseProduct();

        if (!isset($request['tags']))
            $request['tags'] = [];

        if (is_string($request['prices']))
            $request['prices'] = json_decode($request['prices'], true);

        if (is_string($request['tags']))
            $request['tags'] = json_decode($request['tags'], true);

        $product->create($request, count($request['prices']) > 1);

        if (count($request['prices']) > 1)
            $product->setAttributes($request);

        // if (count($request['tags']))
        //     $product->setTags($request['tags']);

        // $product->setImages($request, $files);
        $product->setImagesRemote($request);
        // die(var_dump($product));


        return taamitoApp()->view($product->get());
    }

    public function update(WP_REST_Request $input)
    {
        $request = $input->get_body_params();
        if (!$request)
            $request = $input->get_json_params();
        $params = $input->get_query_params();
        $files = $input->get_file_params();
        $product = new BaseProduct();

        if (!isset($request['tags']))
            $request['tags'] = [];

        if (is_string($request['prices']))
            $request['prices'] = json_decode($request['prices'], true);

        if (is_string($request['tags']))
            $request['tags'] = json_decode($request['tags'], true);

        $product->update($params['id'], $request, count($request['prices']) > 1);

        if (count($request['prices']) > 1)
            $product->setAttributes($request);

        if (count($request['tags']))
            $product->setTags($request['tags']);

        // $product->setImages($request, $files);
        $product->setImagesRemote($request);
        // die(var_dump($product));


        return taamitoApp()->view($product->get());
    }
    public function delete(WP_REST_Request $input)
    {   
        $params = $input->get_query_params();
        $product = new BaseProduct();
        $product->delete($params['id']);

        return taamitoApp()->view($product->get());
    }
}
