<?php

namespace App\Modules\VehicleLabels\Http\Resources;

use App\Facades\Labels;
use App\Facades\Settings;
use App\IntegrationRepository;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\Franchise;
use Mtc\MercuryDataModels\FuelType;
use Mtc\MercuryDataModels\TransmissionType;
use Mtc\MercuryDataModels\VehicleMake;
use Mtc\MercuryDataModels\VehicleModel;

class LabelView extends JsonResource
{
    public static $wrap = '';

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        $has_stock_provider = (new IntegrationRepository())->getEnabledForType('stock')->isNotEmpty();
        $this->resource->couldAutomate = Settings::get('vehicle-labels-enabled') || $has_stock_provider;
        $this->resource->data = $this->getDataValues();
        return parent::toArray($request);
    }

    private function getDataValues()
    {
        $data = $this->resource->data ?? [];

        // key options by label_rules.condition_field
        $data['options'] = [];

        if (!isset($data['auto_assign'])) {
            $data['auto_assign'] = false;
            $data['assign_when'] = false;
        }

        if (!isset($data['auto_revoke'])) {
            $data['auto_revoke'] = false;
            $data['revoke_when'] = false;
        }
        $data['automation_options'] = Labels::getAutomationOptions();
        $data['display_type_options'] = [
            [
                'id' => 'all',
                'name' => 'All'
            ],
            [
                'id' => 'srp',
                'name' => 'Search Page Only'
            ],
            [
                'id' => 'fpa',
                'name' => 'Full Page Advert Only'
            ],
        ];

        $data['advanced_rules'] = false;

        if (Settings::get('vehicle-labels-advanced-rules-enabled')) {
            $data['advanced_rules'] = true;
            $data['rules'] = $this->populateAdvancedRules($this->getAdvancedRules(), $this->resource->rules);
            $data['options']['vehicle_is_new'] = [
                [
                    'id' => '0',
                    'name' => 'false'
                ],
                [
                    'id' => '1',
                    'name' => 'true'
                ]
            ];
            $data['options']['vehicle_type'] = Labels::getVehicleTypeOptions();
            $data['options']['transmission_id'] = TransmissionType::orderBy('name')
                ->get()
                ->map(function ($option) {
                    return [
                        'id' => (string) $option->id,
                        'name' => $option->name
                    ];
                })->toArray();
            $data['options']['fuel_type_id'] = FuelType::orderBy('name')
                ->get()
                ->map(function ($option) {
                    return [
                        'id' => (string) $option->id,
                        'name' => $option->name
                    ];
                })->toArray();

            $data['options']['make_ids'] = VehicleMake::orderBy('name')
                ->get()
                ->map(function ($option) {
                    return [
                        'id' => (string) $option->id,
                        'name' => $option->name
                    ];
                })->toArray();
            $data['options']['model_ids'] = VehicleModel::orderBy('name')
                ->get()
                ->map(function ($option) {
                    return [
                        'id' => (string) $option->id,
                        'make_id' => (string) $option->make_id,
                        'name' => $option->name
                    ];
                })->toArray();
            $data['options']['dealership_ids'] = Dealership::query()
                ->where('active', '=', true)
                ->orderBy('name')
                ->get()
                ->map(function ($option) {
                    return [
                        'id' => (string) $option->id,
                        'name' => $option->name
                    ];
                })->toArray();

            $data['options']['franchise_ids'] = Franchise::query()
                ->orderBy('name')
                ->get()
                ->map(function ($option) {
                    return [
                        'id' => (int) $option->id,
                        'name' => $option->name
                    ];
                })->toArray();
        }

        return $data;
    }

    private function getAdvancedRules()
    {
        return [
            'transmission_id' => [
                'name' => 'Transmission Type',
                'value_data_type' => 'id',
                'condition_value' => null,
            ],
            'fuel_type_id' => [
                'name' => 'Fuel Type',
                'value_data_type' => 'id',
                'condition_value' => null,
            ],
            'vehicle_age_min' => [
                'name' => 'Vehicle Age Min',
                'value_data_type' => 'integer',
                'condition_value' => null,
            ],
            'vehicle_age_max' => [
                'name' => 'Vehicle Age Max',
                'value_data_type' => 'integer',
                'condition_value' => null,
            ],
            'vehicle_mileage_min' => [
                'name' => 'Vehicle Mileage Min',
                'value_data_type' => 'integer',
                'condition_value' => null,
            ],
            'vehicle_mileage_max' => [
                'name' => 'Vehicle Mileage Max',
                'value_data_type' => 'integer',
                'condition_value' => null,
            ],
            'vehicle_days_in_stock_min' => [
                'name' => 'Days In Stock Min',
                'value_data_type' => 'integer',
                'condition_value' => null,
            ],
            'vehicle_days_in_stock_max' => [
                'name' => 'Days In Stock Max',
                'value_data_type' => 'integer',
                'condition_value' => null,
            ],
            'vehicle_type' => [
                'name' => 'Vehicle Type',
                'value_data_type' => 'string',
                'condition_value' => null,
            ],
            'vehicle_category' => [
                'name' => 'Vehicle Category',
                'value_data_type' => 'string',
                'condition_value' => null,
            ],
            'vehicle_is_new' => [
                'name' => 'Vehicle Is New',
                'value_data_type' => 'boolean',
                'condition_value' => null,
            ],
            'vehicle_price_min' => [
                'name' => 'Vehicle Price Min',
                'value_data_type' => 'decimal',
                'condition_value' => null,
            ],
            'vehicle_price_max' => [
                'name' => 'Vehicle Price Max',
                'value_data_type' => 'decimal',
                'condition_value' => null,
            ],
            'vehicle_mpg_min' => [
                'name' => 'MPG Min',
                'value_data_type' => 'decimal',
                'condition_value' => null,
            ],
            'vehicle_mpg_max' => [
                'name' => 'MPG Max',
                'value_data_type' => 'decimal',
                'condition_value' => null,
            ],
            'vrms_included' => [
                'name' => 'VRMs included',
                'value_data_type' => 'json',
                'condition_value' => null,
            ],
            'vrms_excluded' => [
                'name' => 'VRMs Excluded',
                'value_data_type' => 'json',
                'condition_value' => null,
            ],
            'make_ids' => [
                'name' => 'Makes',
                'value_data_type' => 'json',
                'condition_value' => null,
            ],
            'model_ids' => [
                'name' => 'Models',
                'value_data_type' => 'json',
                'condition_value' => null,
            ],
            'dealership_ids' => [
                'name' => 'Dealerships',
                'value_data_type' => 'json',
                'condition_value' => null,
            ],
            'active_from' => [
                'name' => 'Active From',
                'value_data_type' => 'date',
                'condition_value' => null,
            ],
            'active_to' => [
                'name' => 'Active To',
                'value_data_type' => 'date',
                'condition_value' => null,
            ],
        ];
    }

    /**
     * set the values of any advanced rules which exist in the label's rules
     *
     * @param array $advanced_rules
     * @param array $label_rules
     * @return array|mixed
     */
    private function populateAdvancedRules($advanced_rules = [], $label_rules = [])
    {
        $label_rules->each(function ($rule) use (&$advanced_rules) {
            $advanced_rules[$rule->condition_field]['condition_value'] = $rule->getValue();
        });

        return $advanced_rules;
    }
}
