<?php

namespace Modules\Category\Controllers\Api;

/** Ajax Request */

use App\Services\Response\ResponseService;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use Modules\Category\Models\Resources\CategoryResource;
use Modules\Category\Requests\Admin\CategoryRequest;
use Modules\Category\Services\CategoryService;
use Modules\Currency\Services\CurrencyService;
use Modules\User\Services\AccountService;
use Modules\User\Services\UserService;

class CategoryController extends Controller
{

    public function __construct(
        private AccountService $accountService,
        private CategoryService $categoryService,
        private UserService $userService,
    ){}

    /**
     * Display a listing of the countries.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request):JsonResponse
    {
        $account = $this->accountService->getAccount();
        $user = $account['user'];

        $countries = $this->categoryService->get([
            'type_id'=>$user->type_id,
            'category_id'=>'main'
        ]);
        return ResponseService::response([
            'status'=>200,
            'message'=>'',
            'data'=>CategoryResource::collection($countries)
        ]);
    }

    public function visit(Request $request)
    {
        $account = $this->accountService->getAccount();

        $category = $this->categoryService->getItem($request->category_id);
        if ($category)
        {
            $category_id = $category->category_id ?? $request->category_id;
            $this->userService->createVisit([
                'user_status'=>$account['status'],
                'user_id'=>$account['user']->id,
                'category_id'=>$category_id
            ]);
        }
        return ResponseService::response([
            'status'=>200,
            'message'=>'',
            'data'=>''
        ]);
    }

    /**
     * Show the form for editing the specified Category.
     *
     * @param  int $id
     * @return JsonResponse
     */
    public function show(int $id) : JsonResponse
    {
        $category = $this->categoryService->checkItem($id);
        if (!$category)
        {
            abort(404);
        }
        $category = $this->categoryService->getItem($id);

        return ResponseService::response([
            'status'=>200,
            'message'=>'',
            'data'=>new CategoryResource($category)
        ]);
    }


}
