<?php

namespace Miladmodaresi\Taamito\Jobs;

use Miladmodaresi\Taamito\Base\BaseJob;
use Miladmodaresi\Taamito\Model\TaamSync;
use Miladmodaresi\Taamito\Services\CategoryService;
use WP_Error;

class CategoryJob implements BaseJob
{
    protected $categories       = [];
    protected $token            = '';
    protected $remoteCategories = [];
    protected $categoryService  = null;

    public function getLocalCategoryIds()
    {
        $syncData = new TaamSync;
        $data = $syncData->where('name', 'category')->where('status', 2)->get();
        $this->categories = $data->pluck('remote_id', 'local_id');
        $user = taamitoApp()->getOption('user');
        $this->token = $user['token'];
    }
    public function __construct($lastSyncModel)
    {
        $this->getLocalCategoryIds();
        $syncData = new TaamSync;
        $this->categoryService = new CategoryService;
        $categoryModel = $syncData->where('name', 'categories')->where('status', 2)->first();
        if (!$categoryModel->exists())
            $categoryModel = (new TaamSync(['name' => 'categories', 'status' => 1]))->create();

        $this->process($categoryModel, 1, isset($lastSyncModel->data['last_sync_at']) ? $lastSyncModel->data['last_sync_at'] : null);
    }

    public function repair()
    {
    }

    public function process($model, $page = 1, $lastSyncAt = null)
    {
        $queryParams = '';

        if ($lastSyncAt)
            $queryParams = 'updated_at=' . $lastSyncAt;

        if ($queryParams)
            $queryParams = $queryParams . '&page_size=20&page=' .  $page;
        else
            $queryParams = $queryParams . 'page_size=20&page=' . $page;

        $domain = taamitoApp()->getOption('domain');
        $response = taamitoApi()->setSubDomain($domain)->setAuth($this->token)
            ->get('wp/categories?' . $queryParams);
        $this->remoteCategories = $response;

        foreach ($this->remoteCategories->entity->data as $category) {
            if (!isset($this->categories[$category->id]) && !$category->deleted_at) {
                $categoryModel = (new TaamSync(['name' => 'category', 'status' => 1, 'remote_id' => $category->id, 'data' => $category]))->create();
                $newCategory = $this->categoryService->create([
                    "category"     => $category->name,
                    "parent_id"    => $category->parent_id ? $this->categories[$category->parent_id] : null,
                ], taamitoApp()->uploadImage($category->icon_url, [
                    "title"     => $category->name,
                    "parent_id" => $category->parent_id ? $this->categories[$category->parent_id] : null,
                ]));
                if ($newCategory instanceof WP_Error)
                    $categoryModel->update(['status' => 0]);
                else {
                    $this->categories[$category->id] = $newCategory['term_id'];
                    $categoryModel->update(['status' => 2, 'local_id' => $newCategory['term_id']]);
                }
            } else if (isset($this->categories[$category->id]) && !$category->deleted_at) {
                $newCategory = $this->categoryService->update($this->categories[$category->id], [
                    "category"              => $category->name,
                    "parent_id"             => $category->parent_id ? $this->categories[$category->parent_id] : null,
                ], taamitoApp()->uploadImage($category->icon_url, [
                    "title"                 => $category->name,
                    "parent_id"             => $category->parent_id ? $this->categories[$category->parent_id] : null,
                ]));
            } else if (isset($this->categories[$category->id]) && $category->deleted_at) {
                $newCategory = $this->categoryService->delete($this->categories[$category->id]);
                $categoryModel = (new TaamSync(['name' => 'categories', 'status' => 1]))->where('remote_id', $category->id)->delete();
            }
        }
        if ($this->remoteCategories->entity->last_page > $page)
            $this->process($model, ++$page, $lastSyncAt);
    }
}
