<?php

namespace OtomaticAi\Controllers\OneClick;


use OtomaticAi\Vendors\Illuminate\Support\Arr;
use OtomaticAi\Controllers\Controller;

class CategoriesController extends Controller
{
    /**
     * Create categories
     *
     * @return void
     */
    public function createCategories()
    {
        $this->verifyNonce();

        $this->validate([
            "categories" => ["required", "array"],
        ]);

        $output = [];
        foreach ($this->input("categories", []) as $category) {
            $cat = null;
            if (Arr::get($category, "existing", false)) {
                $id = Arr::get($category, "id");
                $id = str_replace("cat_", "", $id);
                $cat = get_category($id, ARRAY_A);
            }

            if (empty($cat)) {
                $cat = $this->getOrCreateCategory($category, $this->input("categories", []));
            }

            if (!empty($cat)) {
                $cat["old_id"] = Arr::get($category, "id");
                $output[] = $cat;
            }
        }

        $output = Arr::map($output, function ($category) {
            return [
                "id" => Arr::get($category, "term_id"),
                "old_id" => Arr::get($category, "old_id"),
                "name" => Arr::get($category, "name"),
            ];
        });

        $this->response($output);
    }

    /**
     * Get or create a category
     *
     * @param array $category
     * @param array $categories
     * @return array|null
     */
    private function getOrCreateCategory(array $category, array $categories): ?array
    {
        // get the category id by name
        $id = get_cat_ID(Arr::get($category, "name"));

        // the category does not exist, we create it
        if ($id === 0) {

            // get the parent id
            $storedParentCategory = null;
            $parentCategory = Arr::first($categories, function ($cat) use ($category) {
                return Arr::get($cat, "id") === Arr::get($category, "parent_id");
            });

            if (!empty($parentCategory)) {
                $storedParentCategory = $this->getOrCreateCategory($parentCategory, $categories);
            }

            if (!empty($storedParentCategory)) {
                $id = wp_create_category(Arr::get($category, "name"), Arr::get($storedParentCategory, "term_id"));
            } else {
                $id = wp_create_category(Arr::get($category, "name"));
            }
        }

        if (!is_wp_error($id)) {
            return get_category($id, ARRAY_A);
        }
    }
}
