<?php

namespace EasyRestaurantManager\Http\Controllers;

use WP_REST_Request;
use EasyRestaurantManager\Http\Requests\StoreCategoryRequest;
use EasyRestaurantManager\Resources\CategoryResource;

class CategoryController
{
    public static function storeCategory(WP_REST_Request $request)
    {
        $data = $request->get_param('data');
        $id = $data['id'];

        $validatedRequest = new StoreCategoryRequest($request);
        if ($validatedRequest->fails()) {
            return rest_ensure_response([
                'message' => 'Validation failed',
                'errors'  => $validatedRequest->errors()
            ], 400);
        }
    
        if ($id) {
        //    return( $data);
            $res = CategoryResource::updateCategory($data);
            if ($res === false) {
                return rest_ensure_response([
                    'message' => 'Failed to update category'
                ], 500);
            }
            return rest_ensure_response([
                'message' => 'Category updated successfully',
                'category_data' => $res
            ]);
        }
    
        $res = CategoryResource::store($validatedRequest->validated());
        if (!$res) {
            return rest_ensure_response([
                'message' => 'Failed to create category'
            ], 500);
        }
        return rest_ensure_response([
            'message' => 'Category created successfully',
            'category_data' => $res
        ]);
    }
    

    public static function getCategory()
    {
        $res = CategoryResource::getCategory();
       
        if (!$res) {
            return rest_ensure_response([
                'message' => 'Failed to create category'
            ], 500);
        }
        return rest_ensure_response([
            'message' => 'Category created successfully',
            'category_data' => $res
        ]);
    }

    public static function deleteCategory(WP_REST_Request $request)
    {
        $id = $request->get_param('id');
        if (!$id) {
            return rest_ensure_response([
                'message' => 'Category id is required'
            ], 400);
        }
        $res = CategoryResource::deleteCategory($id);
       
        if (!$res) {
            return rest_ensure_response([
                'message' => 'Failed to delete category'
            ], 500);
        }
        return rest_ensure_response([
            'message' => 'Category deleted successfully',
            'category_data' => $res
        ]);
    }
}
