<?php

namespace App\Http\Controllers;

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

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $req)
    {
        $champs = $req->validate([
            'nom' => 'required|max:255',
            'postnom' => 'required|max:255',
            'prenom' => 'required|max:255',
            'sexe' => 'required|max:25',
            'age' => 'required',
            'telephone' => 'required|max:255',
            'eglise' => 'required|max:255',
            'ville' => 'required|max:255',
            'date' => 'required',
            'observation' => 'required|max:255',
        ]);

        $visiteur = Visiteur::create($champs);

        return $visiteur;
    }

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $req, $id)
    {
        $visiteur = Visiteur::find($id);
        if (!$visiteur) {
            return response()->json(['message' => 'Visiteur not found'], 404);
        }
        $champs = $req->validate([
            'nom' => 'required|max:255',
            'postnom' => 'required|max:255',
            'prenom' => 'required|max:255',
            'sexe' => 'required|max:25',
            'age' => 'required',
            'telephone' => 'required|max:255',
            'eglise' => 'required|max:255',
            'ville' => 'required|max:255',
            'date' => 'required',
            'observation' => 'required|max:255',
        ]);

        $visiteur->update($champs);

        return $visiteur;
    }

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

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