<?php

namespace App\Http\Controllers;

use App\Models\Tache;
use Illuminate\Http\Request;

class TacheController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $dataTache = Tache::all();
        if ($dataTache->isEmpty()) {
            return response()->json(['message' => 'No data found in Database'], 404);
        }

        return [
            'size' => sizeof($dataTache),
            'data' => $dataTache
        ];
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $req)
    {
        $champs = $req->validate([
            'designation' => 'required|string|max:255',
            'code' => 'required|string|max:255'
        ]);

        $dataTache = Tache::create($champs);
        return $dataTache;
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        $tache = Tache::find($id);
        if (!$tache) {
            return response()->json(['message' => 'Tache not found'], 404);
        }
        return response()->json($tache);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $req, $id)
    {
        $tache = Tache::find($id);
        if (!$tache) {
            return response()->json(['message' => 'Tache not found'], 404);
        }
        $champs = $req->validate([
            'designation' => 'required|string|max:255',
            'code' => 'required|string|max:255',
        ]);
        $tache->update($champs);
        return $tache;
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        $tache = Tache::find($id);
        if (!$tache) {
            return response()->json(['message' => 'Tache not found'], 404);
        }
        $tache->delete();

        return [
            'message' => "Tache deleted"
        ];
    }
}
