<?php

namespace App\Http\Controllers\PermitsReminder;

use App\Models\PermitsReminder;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ListPermitsReminderController
{
    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function list(Request $request): JsonResponse
    {
        $perPage = 10; // Number of items per page
        $page = $request->query('page', 1); // Get the current page from the request

        // Paginate the PermitsReminder model
        $paginator = PermitsReminder::orderBy('reminder_date')->paginate($perPage, ['*'], 'page', $page);

        // Get current date and time
        $currentDateTime = now();

        // Define date range
        $startRange = $currentDateTime->subDays(3)->startOfDay();
        $endRange = $currentDateTime->copy()->addDays(6)->endOfDay();

        // Process paginated items
        $data = $paginator->items();
        foreach ($data as &$item) {
            // Check if the reminder_date is within the date range or after the current date
            $reminderDate = Carbon::parse($item->reminder_date);
            $item->show_remind = $reminderDate->between($startRange, $endRange) || $reminderDate->isBefore($currentDateTime);
        }

        // Create pagination links
        $links = [
            "first" => $paginator->url(1),
            "last" => $paginator->url($paginator->lastPage()),
            "prev" => $paginator->previousPageUrl(),
            "next" => $paginator->nextPageUrl(),
        ];

        // Prepare response
        $response = [
            "title" => "List Permits Reminder",
            "message" => "You have successfully retrieved a list of Permits Reminder",
            "payload" => [
                'data' => $data,
                "links" => $links,
                "meta" => [
                    "current_page" => $paginator->currentPage(),
                    "from" => $paginator->firstItem(),
                    "last_page" => $paginator->lastPage(),
                    "path" => $request->path(),
                    "per_page" => $paginator->perPage(),
                    "to" => $paginator->lastItem(),
                    "total" => $paginator->total(),
                ]
            ]
        ];

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