<?php

namespace App\Http\Controllers;

use App\Facades\Settings;
use App\Http\Resources\SiteResource;
use App\Services\Geolocation\CurrencyDetector;
use App\Traits\CacheObject;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class SiteController extends Controller
{
    use CacheObject;

    /**
     * Show page detail
     *
     * @param $page
     * @return SiteResource
     */
    public function index(Request $request, CurrencyDetector $detector): SiteResource|Response|JsonResponse|array
    {
        $response = $this->cache('get-site', 5, fn () => new SiteResource([])->toResponse($request));

        return $this->appendDetectedCurrency($response, $detector->detect($request));
    }

    public function checkAccess(Request $request)
    {
        return $request->input('password') === Settings::get('site-access-password')
            ? response('Access Granted')
            : response('Access Denied', 403);
    }

    private function appendDetectedCurrency(
        SiteResource|Response|JsonResponse|array $response,
        ?string $detectedCurrency
    ): SiteResource|Response|JsonResponse|array {
        if (!$response instanceof JsonResponse) {
            return $response;
        }

        $data = $response->getData(true);
        if (!is_array($data)) {
            return $response;
        }

        $data['detected_currency'] = $detectedCurrency;

        return response()->json($data, $response->getStatusCode(), $response->headers->all());
    }
}
