<?php

namespace App\Http\Controllers\PermitsReminder;

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

class CreatePermitsReminderController
{
    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function create(Request $request): JsonResponse
    {
        // Define validation rules
        $rules = [
            'model' => 'required|unique:permits_reminders,model', 
            'expiry_date' => 'required|date|after_or_equal:today',
            'reminder_date' => 'required|date|after_or_equal:today',
        ];

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

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

            // Return validation error response
            return response()->json([
                'title' => 'Create Permits Reminder Failed',
                'message' => $validationError,
                "payload" => []
            ], 422); // 422 Unprocessable Entity status code for validation errors
        }

        // If validation passes, create the record
        $record = PermitsReminder::create([
            'expiry_date' => Carbon::parse($request->input('expiry_date'))->format('Y-m-d'),
            'reminder_date' => Carbon::parse($request->input('reminder_date'))->format('Y-m-d'),
            'model' => $request->input('model'),
        ]);

        $response = [
            "title" => "Create Permits Reminder Successful",
            "message" => "You have successfully created a Permits Reminder",
            "payload" => [
                "data" => $record
            ]
        ];

        return response()->json($response);
    }
}
