<?php

namespace App\Http\Controllers;

use App\Facades\Settings;
use App\Http\Resources\DealershipList;
use App\Http\Resources\DealershipView;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\Services\LocatingService;

class DealershipController extends Controller
{
    public function index(Request $request, LocatingService $service)
    {
        $orderBy = Settings::get('dealerships-sort-order', 'name') === 'order'
            ? 'order'
            : 'name';
        return new DealershipList(Dealership::query()
            ->where('active', 1)
            ->with([
                'mediaUses.media',
                'franchise.make',
                'departments',
                'primaryDepartment',
                'form',
                'attributeValues',
            ])
            ->when(
                $request->input('custom'),
                function ($query, $customFilters) {
                    foreach ((array) $customFilters as $slug => $value) {
                        if (strtolower($value) === 'true') {
                            $query->whereHas('attributeValues', fn ($q) => $q
                                ->where('slug', $slug)
                                ->where('value_integer', 1));
                        } elseif (strtolower($value) === 'false') {
                            $query->whereDoesntHave('attributeValues', fn ($q) => $q
                                ->where('slug', $slug)
                                ->where('value_integer', 1));
                        } else {
                            $query->whereHas('attributeValues', fn ($q) => $q
                                ->where('slug', $slug)
                                ->where('value', $value));
                        }
                    }
                }
            )
            ->when(
                empty($request->input('postcode')),
                fn ($query) => $query->orderBy($orderBy),
            )
            ->nearPostcode($request->input('postcode'))
            ->get());
    }

    public function show(string $dealership_slug)
    {
        $dealership = Dealership::query()->where('slug', $dealership_slug)->firstOrFail();
        if (!$dealership->active) {
            return response('Not Found', 404);
        }
        return new DealershipView($dealership);
    }
}
