<?php

namespace App\Http\Controllers\PermitsReminder;

use App\Models\PermitsReminder;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class UpdatePermitsReminderController
{
    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function update(Request $request): JsonResponse
    {
        $rules = [
            'model' => 'required|unique:permits_reminders,model,' . $request->route('id'),
            'expiry_date' => 'required|date|after_or_equal:today',
            'reminder_date' => 'required|date|after_or_equal:today',
        ];

        $validator = Validator::make($request->all(), $rules);

        if ($validator->fails()) {
            $validationErrors = $validator->errors()->all();
            $validationError = implode("<br>", $validationErrors);

            return response()->json([
                'title' => 'Update Permits Reminder Failed',
                'message' => $validationError,
                "payload" => []
            ], 422);
        }

        $record = PermitsReminder::findOrFail($request->route('id'));

        $record->model = $request->input('model');
        $record->expiry_date = Carbon::parse($request->input('expiry_date'))->format('Y-m-d');
        $record->reminder_date = Carbon::parse($request->input('reminder_date'))->format('Y-m-d');
        $record->save();

        return response()->json([
            'title' => 'Permits Reminder Updated',
            'message' => 'The permits reminder has been successfully updated.',
            "payload" => $record
        ]);
    }
}
