<?php

namespace App\Http\Controllers\Admin\Api;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\libs\Response\GlobalApiResponse;
use App\libs\Response\GlobalApiResponseCodeBook;
use App\Services\Admin\CategoryService;
use Illuminate\Http\Request;

class CategoriesController extends Controller
{
    private $categoryService;

    public function __construct(CategoryService $categoryService) {
        $this->categoryService = $categoryService;
    }

    public function categoriesList(){
        $data = $this->categoryService->categoriesList();
        return (new GlobalApiResponse())->success('Categories list',1,$data);
    }

    public function getCategoryDetail($id){
        $data = $this->categoryService->getCategoryDetail($id);
        return (new GlobalApiResponse())->success('Categories Details',1,$data);
    }

    public function createCategory(Request $request){
        $this->categoryService->createCategory($request->all());
        if($this->categoryService->hasError()) {
            return (new GlobalApiResponse())->error(GlobalApiResponseCodeBook::INVALID_FORM_INPUTS, $this->categoryService->getErrors()[0]['message'], $this->categoryService->getErrors());
        }
        return (new GlobalApiResponse())->success('Category successfully created');
    }

    public function updateCategory(Request $request, $id){
        $this->categoryService->updateCategory($request->all(), $id);
        if($this->categoryService->hasError()) {
            return (new GlobalApiResponse())->error(GlobalApiResponseCodeBook::INVALID_FORM_INPUTS, $this->categoryService->getErrors()[0]['message'], $this->categoryService->getErrors());
        }
        return (new GlobalApiResponse())->success('Category successfully updated');
    }

    public function deleteCategory(Request $request){
        if (empty($request->category_ids)) {
            return (new GlobalApiResponse())->error(GlobalApiResponseCodeBook::INVALID_FORM_INPUTS, "IDs not found!");
        }
        Category::whereIn('id', $request->category_ids)->delete();
        return (new GlobalApiResponse())->success("Category successfully deleted");
    }

    public function updateCategoryStatus(Request $request)
    {
        if (empty($request->category_ids)) {
            return (new GlobalApiResponse())->error(GlobalApiResponseCodeBook::INVALID_FORM_INPUTS, "IDs not found!");
        }
        $cats = Category::whereIn('id', $request->category_ids)->get();
        if ($cats) {
            foreach ($cats as $cat) {
                $cat->update([$request->column => $request->status]);
            }
            return (new GlobalApiResponse())->success("Status successfully updated");
        } else {
            return (new GlobalApiResponse())->error(GlobalApiResponseCodeBook::RECORD_NOT_EXIST, "Category not found!");
        }
    }
}
