<?php

namespace App\Http\Controllers\api\v1;

use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CategoryController extends Controller
{
    public function getParentCategoryList(Request $request){

        $status = "1";
        $message = "Category list fetched successfully";
        $o_data = [];
        $errors = [];

        $limit = isset($request->limit) ? $request->limit : 10;
        $offset = isset($request->page) ? ($request->page - 1) * $request->limit : 0;
        $categories = Category::whereNull('parent_id')
            ->where('status', 1)
            ->orderBy('sort_order', 'asc')
            ->limit($limit)
            ->offset($offset)
            ->get();

        $categories = $categories->map(function ($category) {
            $category->has_children = Category::where('parent_id', $category->id)->exists() ? 1 : 0;
            return $category;
        });

        $o_data['parent_categories'] = convert_all_elements_to_string($categories);

        return response()->json(['status' => $status, 'error' => $errors, 'message' => $message, 'oData' => $o_data], 200);   
    }

    public function getSubCategoryList(Request $request){

        $status = "1";
        $message = "Sub Category list fetched successfully";
        $o_data = [];
        $errors = [];

        $validator = Validator::make($request->all(), [
            'parent_id' => 'required|exists:categories,id',
        ]);
        
        if ($validator->fails()) {
            return response()->json([
                'status' => "0",
                'message' => "Kindly fill all the mandatory fields",
                'error' => (object) $validator->messages(),
            ], 200);
        }

        $categories = Category::where(['parent_id'=>$request->parent_id,'status'=>1])->orderBy('id', 'asc')->get();
        $o_data['sub_categories'] = convert_all_elements_to_string($categories);

        return response()->json(['status' => $status, 'error' => $errors, 'message' => $message, 'oData' => $o_data], 200);   
    }
}