<?php

namespace App\Http\Resources;

use App\Facades\Feature;
use App\Facades\Settings;
use App\Facades\Site;
use App\IntegrationRepository;
use App\Modules\PlaceholderImages\ImaginStudio;
use App\Traits\CacheObject;
use App\Traits\RetrievesContent;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Storage;
use Mtc\Crm\Models\Form;
use Mtc\MercuryDataModels\GlobalContent;
use Mtc\MercuryDataModels\Menu;
use Mtc\MercuryDataModels\SearchFacet;
use Mtc\MercuryDataModels\SeoRedirect;

class SiteResource extends JsonResource
{
    use CacheObject;
    use FranchiseData;
    use PhoneNumberDisplay;
    use RetrievesContent;

    public static $wrap = '';
    private const UI_RESOURCE_PREFIX = 'App\\Http\\Resources\\';

    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        $integrations = new IntegrationRepository();
        $menus = $this->loadMenus();

        return [
            'id' => tenant('id'),
            'name' => Settings::get('app-name'),
            'locale' => 'en-GB',
            'domain' => Site::siteDomain(),
            'logo' => Settings::get('site-alternate-logo'),
            'contact_phone_number' => $this->displayNumber(Settings::get('app-contact-phone_number') ?? ''),
            'contact_whatsapp_number' => $this->displayNumber(Settings::get('app-contact-whastapp-number') ?? ''),
            'contact_email' => Settings::get('app-contact-contact_email'),
            'currency' => Settings::get('app-details-currency'),
            'favicon' => Settings::get('site-favicon'),
            'apple-touch' => Settings::get('site-apple-touch-icon'),
            'suspended' => tenant('suspended_at'),
            'franchises' => $this->getFranchiseList(),
            'branding' => [
                'primaryColour' => '#' . ltrim(Settings::get('app-primary-colour'), '#'),
                'secondaryColour' => '#' . ltrim(Settings::get('app-secondary-colour'), '#'),
                'tertiaryColour' => '#' . ltrim(Settings::get('app-tertiary-colour'), '#'),
                'successColour' => '#' . ltrim(Settings::get('app-success-colour'), '#'),
                'errorColour' => '#' . ltrim(Settings::get('app-error-colour'), '#'),
                'informationColour' => '#' . ltrim(Settings::get('app-information-colour'), '#'),
                'textColour' => '#' . ltrim(Settings::get('app-text-colour'), '#'),
                'subTextColour' => '#' . ltrim(Settings::get('app-subtext-colour'), '#'),
                'layerDarkColour' => '#' . ltrim(Settings::get('app-layer-dark-colour'), '#'),
                'layerAccentColour' => '#' . ltrim(Settings::get('app-layer-accent-colour'), '#'),
                'layerLightColour' => '#' . ltrim(Settings::get('app-layer-light-colour'), '#'),
            ],
            'restricted_access' => Settings::get('site-access-enabled'),
            'scripts' => $this->getScripts(),
            'header' => [
                'siteName' => Settings::get('app-name'),
                'logo' => Settings::get('site-logo'),
                'mainMenu' => new MenuResource($menus['header-main'] ?? []),
                'sidebarMenu' => new MenuResource($menus['header-sidebar'] ?? []),
                'franchiseMenu' => new MenuResource($menus['franchise-menu'] ?? []),
            ],
            'cookie_content' => $this->loadGlobal('cookie-consent'),
            'footer' => [
                'logo' => Settings::get('site-logo'),
                'menu' => new MenuResource($menus['footer'] ?? []),
                'copyright' => $this->loadGlobal('copyright'),
                'footer_data' => $this->loadGlobal('footer'),
                'socials' => $integrations->findNonEmptyValuesForType('socials')
                    ->map(fn($link, $key) => [
                        'key' => $key,
                        'url' => $link,
                    ])->values(),
                'subscribe' => [
                    'enabled' => $integrations->getEnabledForType('newsletters')->isNotEmpty(),
                    'form' => Settings::get('newsletters-form-id')
                        ? new FormViewResource(Form::find(Settings::get('newsletters-form-id')))
                        : null,
                ],
                'calltracks' => Settings::get('crm-calltracks-enabled')
                    ? Settings::get('crm-calltracks-tags')
                    : ''
            ],
            'imagin_studio' => Feature::isEnabled('imagin-studio-placeholders')
                ? (new ImaginStudio())->getBaseUrl()
                : null,
            'liveChat' => $this->liveChat(),
            'distance_measurement' => Settings::get('automotive-distance_measurement'),
            'christmas_enabled' => Settings::get('christmas-enabled'),
            'sitemap_url' => $this->getSitemapUrl(),
            'facets' => $this->getFacets(),
        ];
    }

    private function getSitemapUrl(): ?string
    {
        if (!Feature::isEnabled('sitemap')) {
            return null;
        }

        $path = tenant('id') . '/sitemap.xml';
        if (!Storage::disk('file-storage')->exists($path)) {
            return null;
        }

        return Storage::disk('file-storage')->url($path) . '?t=' . Storage::disk('file-storage')->lastModified($path);
    }

    private function getFacets(): array
    {
        if (!Feature::isEnabled('search-facets')) {
            return [];
        }

        return SearchFacet::query()
            ->orderBy('position')
            ->get()
            ->map(fn($facet) => [
                'position' => $facet->position,
                'filter_type' => $facet->filter_type,
                'robots_index' => $facet->robots_index,
                'robots_follow' => $facet->robots_follow,
            ])
            ->toArray();
    }

    private function liveChat(): ?LiveChatResource
    {
        if ($this->hasLiveChatEnabled() === false) {
            return null;
        }

        return $this->getEnabledLiveChatWidget();
    }

    private function hasLiveChatEnabled(): bool
    {
        return (new IntegrationRepository())->getEnabledForType('chat')->isNotEmpty();
    }

    private function getEnabledLiveChatWidget(): LiveChatResource
    {
        return new LiveChatResource((new IntegrationRepository())->getLiveChat());
    }

    private function getScripts(): array
    {
        $scripts = (new IntegrationRepository())->getEnabledForType('tracking')
            ->filter(fn($integration) => $integration['class'])
            ->map(fn($integration) => App::make($integration['class']))
            ->values()
            ->toArray();

        return collect($scripts)
            ->flatten(1)
            ->toArray();
    }

    private function loadGlobal(string $slug)
    {
        return $this->cache("global-content-$slug", 60, function () use ($slug) {
            /** @var GlobalContent|null $globalContent */
            $globalContent = GlobalContent::query()
                ->with('mediaUses.media')
                ->where('slug', $slug)
                ->first();
            if (!empty($globalContent)) {
                return $this->mapGlobalContent($globalContent);
            } else {
                return null;
            }
        });
    }

    private function loadMenus(): Collection
    {
        return $this->cache("menus", 60, function () {
            return Menu::query()
                ->with([
                    'element.fields',
                    'rootEntries' => function ($query) {
                        $query->where('is_enabled', true)
                            ->with([
                                'children' => function ($query) {
                                    $query->where('is_enabled', true)
                                        ->with([
                                            'children' => function ($query) {
                                                $query->where('is_enabled', true)
                                                    ->with([
                                                        'children' => function ($query) {
                                                            $query->where('is_enabled', true);
                                                        }
                                                    ]);
                                            }
                                        ]);
                                }
                            ]);
                    },
                    'rootEntries.mediaUses.media'
                ])
                ->get()
                ->keyBy('slug');
        });
    }
}
