<?php

namespace App\Http\Resources;

use App\Facades\Settings;
use App\TierHelper;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Mtc\ContentManager\Contracts\MediaUse;
use Mtc\ContentManager\Models\MediaSize;
use Mtc\MercuryDataModels\Franchise;
use Mtc\MercuryDataModels\Menu;

trait FranchiseData
{
    protected function getFranchiseList(): array
    {
        if (!$this->tenantIsAllowedFranchises()) {
            return [];
        }

        return Franchise::query()
            ->with([
                'primaryMediaUse.media',
                'menus',
                'make',
                'dealerships',
            ])
            ->get()
            ->map(function ($franchise) {

                $franchiseData = [
                    'id' => $franchise->id,
                    'name' => $franchise->name,
                    'slug' => $franchise->slug,
                    'make_id' => $franchise->make?->id,
                    'make_slug' => $franchise->make?->slug,
                    'menus' => $franchise->menus->map(fn(Menu $menu) => new MenuResource($menu)),
                    'primary_colour' => $franchise->primary_colour,
                    'secondary_colour' => $franchise->secondary_colour,
                    'dealerships' => $franchise->dealerships?->map(fn($dealership) => [
                        'name' => $dealership->name,
                        'contact_no' => $dealership->contact_no,
                        'email' => $dealership->email,
                    ]),
                ];

                if ($franchise->primaryMediaUse) {
                    $franchiseData['logo'] = $this->sizesForFranchise($franchise, $franchise->primaryMediaUse);
                }

                if (Settings::get('crm-calltracks-enabled')) {
                    $franchiseData['calltracks'] = !empty($franchise->data['crm-calltracks-tags'])
                        ? $franchise->data['crm-calltracks-tags']
                        : Settings::get('crm-calltracks-tags');
                }

                return $franchiseData;
            })
            ->toArray();
    }

    protected function isFranchise(): bool
    {
        if (!$this->tenantIsAllowedFranchises() || empty($this->resource)) {
            return false;
        }

        if (!empty($this->resource->franchise_id)) {
            return true;
        }

        return $this->resource?->template?->slug === 'franchise';
    }

    protected function franchiseData(): ?array
    {
        if ($this->isFranchise() !== true) {
            return null;
        }

        $franchise = Franchise::query()
            ->with([
                'primaryMediaUse.media',
                'menus',
                'make',
                'dealerships',
            ])
            ->find($this->resource->franchise_id);
        if (!$franchise) {
            return null;
        }
        $franchiseData = $franchise?->only([
            'id',
            'name',
            'slug',
            'logo',
            'primary_colour',
            'secondary_colour',
            'menus',
            'make_id',
        ]);

        if ($franchise->primaryMediaUse) {
            $franchiseData['logo'] = $this->sizesForFranchise($franchise, $franchise->primaryMediaUse);
        }
        $franchiseData['menus'] = $franchise->menus->map(fn(Menu $menu) => new MenuResource($menu));
        $franchiseData['make_slug'] = $franchise->make?->slug;

        if (Settings::get('crm-calltracks-enabled')) {
            $franchiseData['calltracks'] = !empty($franchise->data['crm-calltracks-tags'])
                ? $franchise->data['crm-calltracks-tags']
                : Settings::get('crm-calltracks-tags');
        }

        return $franchiseData;
    }


    protected function getFranchiseId(): int
    {
        return 0;
    }

    protected function tenantIsAllowedFranchises(): bool
    {
        return TierHelper::isAllowed(tenant()->tier, 'pro');
    }

    private function sizesForFranchise(Model $model, MediaUse $mediaUse): Collection
    {
        return MediaSize::query()
            ->where('model', $mediaUse->getOwnerType())
            ->get()
            ->keyBy('label')
            ->map(fn(MediaSize $size) => $mediaUse->getUrl($size->label))
            ->put('original', $mediaUse->media->getOriginalUrlAttribute());
    }
}
