<?php

namespace App\Http\Controllers\Supplier;

use Illuminate\Http\Request;
use App\Models\Supplier\SupplierCategory;
use App\Http\Controllers\Controller;

class SupplierCategoryController extends Controller
{
    public function index(Request $request)
    {
        $search = $request->get("search");
        $categories = SupplierCategory::where("nombre","like","%".$search."%")->orderBy("idCategoriaProveedor","desc")->paginate(25);

        return response()->json([
            "total" => $categories->total(),
            "paginate" => 25,
            "categories" => $categories->map(function($categorie){
                return [
                    "id" => $categorie->idCategoriaProveedor,
                    "nombre" => $categorie->nombre,
                    "state" => $categorie->state,
                    "created_at" => $categorie->created_at->format("Y/m/d h:i A")
                ];
            }),
        ]);
    }

    public function store(Request $request)
    {
        $is_exits = SupplierCategory::where("nombre",$request->nombre)->first();
        if($is_exits){
            return response()->json([
                "code" => 405,
                "message" => "LA CATEGORIA YA EXISTE"
            ]);
        }
        $categorie = SupplierCategory::create($request->all());

        return response()->json([
            "code" => 200,
            "message" => "La categoria se registro correctamente",
            "categorie" => [
                "id" => $categorie->idCategoriaProveedor,
                "nombre" => $categorie->nombre,
                "state" => $categorie->state,
                "created_at" => $categorie->created_at->format("Y/m/d h:i A")
            ]
        ]);
    }

    public function update(Request $request, string $id)
    {
        $is_exits = SupplierCategory::where("idCategoriaProveedor","<>",$id)->where("nombre",$request->nombre)->first();
        if($is_exits){
            return response()->json([
                "code" => 405,
                "message" => "LA CATEGORIA YA EXISTE"
            ]);
        }
        $categorie = SupplierCategory::find($id);
        $categorie->update($request->all());

        return response()->json([
            "code" => 200,
            "message" => "La categoria se edito correctamente",
            "categorie" => [
                "id" => $categorie->idCategoriaProveedor,
                "nombre" => $categorie->nombre,
                "state" => $categorie->state,
                "created_at" => $categorie->created_at->format("Y/m/d h:i A")
            ]
        ]);
    }

    public function destroy(string $id)
    {
        $categorie = SupplierCategory::find($id);
        $categorie->delete();
        return response()->json([
            "code" => 200,
            "message" => "La categoria se elimino correctamente",
        ]);
    }
}
