<?php

namespace App\Http\Controllers;

use App\Models\Marca;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class MarcaController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request): JsonResponse
    {
        $marca=Marca::where(['estatus'=>'activo'])->get();
        return response()->json([
            'data' =>$marca
        ], JsonResponse::HTTP_OK);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'marca' => ['required', 'string','max:150'],
            'estatus' => ['required', 'string','max:10']
        ]);

        $marca = Marca::create($request->only([
            'marca',
            'estatus',
        ]));

        return response()->json([
            'data' => $marca,
        ], JsonResponse::HTTP_OK);
    }


    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Marca $marca): JsonResponse
    {
        return response()->json([
            'data' => $marca,
        ], JsonResponse::HTTP_OK);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Marca $marca): JsonResponse
    {
        $request->validate([
            'marca' => ['required', 'string','max:150'],
            'estatus' => ['required', 'string','max:10']
        ]);

        $marca->update($request->only([
            'marca',
            'estatus',
        ]));

        return response()->json([
            'data' => $marca,
        ], JsonResponse::HTTP_OK);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Marca $marca): JsonResponse
    {
        if (\count($marca->productos) > 0) {
            $marca->update([
                'estatus' => 'inactivo',
            ]);
        } else {
            $marca->delete();
        }

        return response()->json(null, JsonResponse::HTTP_NO_CONTENT);
    }
}
