<?php

namespace App\Http\Controllers\Settings\History;

use App\Http\Responses\ReportJsonResponse;
use Illuminate\Http\Request;
use App\Services\Settings\History\ApiBlockedIpsService;
use App\Http\Controllers\Controller;

class ApiBlockedIpsController extends Controller
{
    /**
     * Constructor for the class.
     *
     * @param ApiBlockedIpsService $service The API blocked IPs object.
     */
    public function __construct(protected ApiBlockedIpsService $service) {}

    /**
     * Load view
     *
     * @return View
     */
    public function index()
    {
        return view('settings.history.api-blocked-ips.api-blocked-ips');
    }

    /**
     * Retrieves the data for the Report.
     *
     * @param Request $request The request object.
     *
     * @return ReportJsonResponse The JSON response.
     */
    public function data(Request $request)
    {
        setUnlimitedExecutionTimeAndMemoryLimit();
        $filteredData = $this->service->data();
        $data = [];

        if (!empty($filteredData['data'])) {
            $data = $this->service->getReportData($filteredData['data'], request('start'), $data);
        }

        return new ReportJsonResponse($request->input('draw'), $data, $filteredData['count']);
    }

    /**
     * Unblock an IP address.
     *
     * @param Request $request The request object.
     *
     * @return RedirectResponse The redirect response.
     */
    public function unblock(Request $request)
    {
        $response = $this->service->unblockIp($request->id);

        if ($response) {
            return redirect()->route('api-blocked-ips.index')->with('message', 'IP unblocked successfully.');
        } else {
            return redirect()->route('api-blocked-ips.index')->with('error', 'Operation failed.');
        }
    }
}
