<?php

namespace App;

use App\Facades\Feature;
use App\Facades\Settings;
use App\Modules\PlaceholderImages\ImaginStudio;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Mtc\Filter\Contracts\FilterObject;
use Mtc\Filter\Contracts\FilterSeoContract;
use Mtc\MercuryDataModels\KeyloopLeaseVehicleVariant;

class LeaseVehicleFilter extends Filter
{
    /**
     * Filter constructor
     *
     * @param Request $request
     * @param FilterObject $product_handler
     * @param FilterSeoContract $seo
     */
    public function __construct(Request $request, FilterObject $product_handler, FilterSeoContract $seo)
    {
        $this->request = $request;
        $this->seo = $seo;
        $this->config = Config::get('filter');
        $this->product_handler = App::make(LeaseVehicleFilterObject::class);
        $this->selections = $this->groupSelectionsByType($request->input('selections') ?? []);
        $this->active_sort_option_name = $this->config['default_sort_choice'];
        $this->target_model = KeyloopLeaseVehicleVariant::class;
    }

    /**
     * Handle Ajax request, perform filtering
     *
     * @return array
     */
    #[\Override]
    public function handle(): array
    {
        $this->request = request();

        if ($this->request->has('slug')) {
            $this->filter_url_elements = explode('/', (string) $this->request->input('slug'));
            $this->matchSortFromUrlElements();
            $this->matchSelectedFilters();
            $this->matchCustomSelections();
            $this->checkForSearchTerm();
        } else {
            $this->selections = $this->groupSelectionsByType($this->request->input('selections') ?? []);
        }

        // build the query
        $this->run();

        /*
         * If model is set, get all variants for that model.
         * If model is not set, get the cheapest variant whose model contains the matching filter results.
         * This allows us to show a search result with a "from" price,
         * which has at least one variant matching the selected filters.
         * We shouldn't have to search on both make and model,
         * because model IDs should be unique across makes.
         */
        if (!array_key_exists('model', $this->selections)) {
            $query = clone $this->query;
            $this->query = KeyloopLeaseVehicleVariant::query()
                ->active()
                ->withRelationshipsForCardView()
                ->whereIn(
                    'model_id',
                    function ($sub_query) use ($query) {
                        $sub_query->select('result.model_id')->fromSub($query->select('model_id'), 'result');
                    },
                )
                ->where('is_cheapest_variant', true);
        }

        // retrieve the query results
        $results = $this->getResults();

        return [
            'results' => $results,
            'filters' => $this->getCachedFilterResults(),
            'sort_options' => $this->getSortOptions(),
            'sort_by' => $this->active_sort_option_name,
            'selections' => $this->getSelectionList(),
            'url' => $this->getPageUrl(),
            'seo' => $this->fillSeo(),
            'finance_example' => $this->getRepresentativeFinance($results),
            'imagin_studio_base_url' => Feature::isEnabled('imagin-studio-placeholders')
                ? new ImaginStudio()->getBaseUrl()
                : null,
            'load_more' => [
                'enabled' => Settings::get('automotive-enable_load_more', false),
                'text' => Settings::get('automotive-load_more_text'),
                'previous_text' => Settings::get('automotive-load_more_previous_text'),
            ]
        ];
    }
}
