<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Resources\SubCategoryResource;
use App\Models\Store;
use App\Models\SubCategory;

class SubcategoryController extends Controller
{
    public function getList(Request $request)
    {
        $store = SubCategory::mySubcategory();

        $per_page = config('constant.PER_PAGE_LIMIT');
        if( $request->has('per_page') && !empty($request->per_page)){
            if(is_numeric($request->per_page))
            {
                $per_page = $request->per_page;
            }
            if($request->per_page == -1 ){
                $per_page = $store->count();
            }
        }

        $store = $store->orderBy('id', 'asc')->paginate($per_page);

        $items = SubCategoryResource::collection($store);
        $status = 200;

        $response = [
            'status'        => $status,
            'pagination'    => json_pagination_response($items),
            'data'          => $items,
        ];

        return json_custom_response($response);
    }


    public function getDetail(Request $request)
    {
        $id = $request->id;
        $subCategory = SubCategory::where('id',$id)->withTrashed()->first();

        if(empty($subCategory))
        {
            $message = __('message.not_found_entry',[ 'name' => __('message.subcategory') ]);
            return json_message_response($message,400);   
        }
        
        $category_detail = new SubCategoryResource($subCategory);

        $response = [
            'data' => $category_detail
        ];
        
        return json_custom_response($response);
    }
    public function multipleDeleteRecords(Request $request)
    {
        $multi_ids = $request->ids;
        $message = __('message.msg_fail_to_delete', ['item' => __('message.subcategory')]);

        foreach ($multi_ids as $id) {
            $subcategory = SubCategory::withTrashed()->where('id',$id)->first();
            if ($subcategory) {
                if( $subcategory->deleted_at != null ) {
                    $subcategory->forceDelete();
                } else {                        
                    $subcategory->delete();
                }
                $message = __('message.msg_deleted', ['name' => __('message.subcategory')]);
            }
        }

        return json_custom_response(['message'=> $message , 'status' => true]);

    }

}
