<?php

namespace App\Http\Controllers;

use App\Models\Abandon;
use App\Models\Personne;
use Illuminate\Http\Request;

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

        return [
            'size' => sizeof($dataAbandon),
            'data' => $dataAbandon
        ];
    }
    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $req)
    {
        $champs = $req->validate([
            'motif' => 'required|string|max:255',
            'observation' => 'required|string|max:255',
            'date' => 'required|date',
            'personne_id' => 'required|exists:personnes,id'
        ]);
        $dataPersonne = Personne::find($req->personne_id);
        $dataAbandon = Abandon::create($champs);
        $dataPersonne->update(['isAbandon' => true]);

        return $dataAbandon;
    }

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $req, $id)
    {
        $dataAbandon = Abandon::find($id);
        if (!$dataAbandon) {
            return response()->json(['message' => 'Abandon not found'], 404);
        }
        $champs = $req->validate([
            'motif' => 'required|string|max:255',
            'observation' => 'required|string|max:255',
            'date' => 'required|date',
            'personne_id' => 'required|exists:personnes,id'
        ]);
        $dataAbandon->update($champs);
        return $dataAbandon;
    }

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

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