<?php
   
namespace App\Http\Controllers\API;

use App\Http\Controllers\API\BaseController as BaseController;
use App\Http\Resources\ProductResource;
use App\Http\Resources\CategoryResource;
use App\Models\Post;
use App\Models\Taxonomy;
use Illuminate\Http\Request;

class PostController extends BaseController
{
    /**
     * All Posts 
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, int $categoryId = 13)
    {
        // dump($category);
        // $cat = Taxonomy::where('taxonomy', 'category')->slug($category)->first();
        $cat = Taxonomy::where('taxonomy', 'category')->where('term_id', $categoryId)->first();
        $slugs= getCategories($cat->term_id, 'slug');
        $slugs[]= $cat->slug;
        // dump($slugs);

        $posts= Post::published()
        ->type('post')->newest()
        ->taxonomy('category', $slugs)
        ->get();
        // dd($posts->toArray());

        $posts= ProductResource::collection($posts);
        return $this->sendResponse($posts, '');
        // return $this->sendResponse($request->user()->marketers, '');
    }

    /**
     * All Categories 
     *
     * @return \Illuminate\Http\Response
     */
    public function categories(Request $request, int $parent = 13)
    {
        // dd($parent);
        // $cat = Taxonomy::where('taxonomy', 'category')->slug($parent)->first();
        $cat = Taxonomy::where('taxonomy', 'category')->where('term_id', $parent)->first();
        // dd($cat->term_id);
        // $allCategories = Taxonomy::category()->get();
        $categories= getCategories($cat->term_id, 'categories');
        // dd($categories);
        $categories= CategoryResource::collection($categories);
        return $this->sendResponse($categories, '');
    }

    /**
     * Get Categories and childs
     */
    private function getCategories(int $parent = 0, $return= 'slug')
    {
        // dump('parent=> '. $parent);
        $allCategories = Taxonomy::category()->where('parent', $parent)->get();
        $slugs= [];
        $categories= [];
        foreach ($allCategories as $cat) {
            // dump($cat->parent);
            if ($cat->parent == $parent) {
                if ('slug' == $return) {
                    $slugs[] = $cat->term->slug;
                    $slugs= array_merge($slugs, $this->getCategories($cat->term_id, $allCategories, $return));
                } else {
                    $categories= array_merge($categories, [$cat], $this->getCategories($cat->term_id, $allCategories, $return));
                }
                // echo $cat->parent ." == ". $cat->term_id ." == ". $cat->term->name.'<br/>';
            }
        }

        return 'slug' == $return ? $slugs : $categories;
    }
}