<?php
/*
 * Copyright (c) 2023.
 *
 * Aidyn Sapargaliyev
 * ТОО Дизайн лаборатория А7
 *
 */

namespace App\Modules\main\Components;

use A7kz\Platform\Models\UniModel;
use A7kz\Platform\Modules\Platform\Core\Services\Base\Component;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Http;

class Main extends Component
{
    public function __construct(array $params = [], $module = 'Platform.Core')
    {
        parent::__construct($params, $module);
        $this->template = 'pipicar::main.views.main';

        $request = request();

        $response = $this->getAuto($request);

        $this->params['cars'] = collect($response)->filter(function ($item) {
            return !empty($item['tariffs']);
        })->values();

//        $response = Http::get('https://cvm10.a7.kz/api/mobile/getAvailableMarksList', [
//            'started_at' => $started_at ?? Carbon::now()->toDateString(),
//            'ended_at' => $ended_at ?? Carbon::now()->addDays(3)->toDateString(),
//            'class' => $class_filters ?? null,
//            'bodywork' => $bodywork_filters ?? null,
//        ]);
//
//        $this->params['cars'] = collect($response->json())->filter(function ($item) {
//            return !empty($item['tariffs']);
//        })->values();
    }

    private function getAuto($request)
    {
        $started_at = $request->query('started_at');
        $ended_at = $request->query('ended_at');
        $class = $request->query('class');
        $bodywork = $request->query('bodywork');

        $marks = UniModel::model('pipi_brand_models')->get();

        $availableMarks = [];

        if ($class) {
            $class_id = UniModel::model('pipi_auto_classes')->where('name', $class)->first()?->id;
            $marks = $marks->where('class_id', $class_id);
        }
        if ($bodywork) {
            $bodywork_id = UniModel::model('pipi_auto_bodywork')->where('name', $bodywork)->first()?->id;
            $marks = $marks->where('bodywork_id', $bodywork_id);
        }

        foreach ($marks as $mark) {
            if ($mark->name === 'Ввод остатков') {
                continue;
            }

            $tariffs = UniModel::model('pipi_auto_tariffs')->where('model_id', $mark->id)->get();
            if ($tariffs->isEmpty()) {
                continue;
            }

            $cars = UniModel::model('pipi_auto')->where('model_id', $mark->id)->get();


            if ($cars->isEmpty()) {
                continue;
            }

            $brand = UniModel::model('pipi_auto_brands')->find($mark->brand_id);
            $tariffs = UniModel::model('pipi_auto_tariffs')->where('model_id', $mark->id)->get();
            $equipment = UniModel::model('pipi_auto_equipment')->where('id', $mark->equipment_id)->first();
            $class = UniModel::model('pipi_auto_classes')->find($mark->class_id);
            $bodywork = UniModel::model('pipi_auto_bodywork')->find($mark->bodywork_id);
            $photo = UniModel::model('core_files')->find($mark?->photo_id);

            $path = null;
            if ($photo) {
                $path = url('api/files/file/' . ltrim($photo->path, '/'));
            }

            $tariffs_new = [];
            foreach ($tariffs as $tariff) {
                $tariffs_new[] = [
                    'name'          => $tariff?->name,
                    'price'         => $tariff?->base_rate,
                    'min'           => $tariff?->day_range_start,
                    'max'           => $tariff?->day_range_end,
                    'deposit'       => $tariff?->deposit,
                ];
            }
            $carsByColor = $cars->groupBy('color_id');

            foreach ($carsByColor as $carColor => $carsOfColor) {
                $carColor = UniModel::model('pipi_auto_colors')->find($carColor);

                $colorPath = $path;
                if ($carsOfColor->first()->photo_id) {
                    $photo = UniModel::model('core_files')->find($carsOfColor->first()->photo_id);
                    $colorPath = url('api/files/file/' . ltrim($photo->path, '/'));
                }

                $key = $mark->name . '-' . $mark->year . '-' . $carColor->code;

                $availableMarks[$key] = [
                    'id' => $mark->id,
                    'brand' => $brand?->name,
                    'mark' => $mark->name,
                    'year' => $mark->year,
                    'color' => $carColor->code,
                    'configuration' => $equipment?->name,
                    'people' => $mark?->people ?? '5',
                    'actuator' => $mark?->actuator ?? 'Передний',
                    'fuel_type' => $mark?->fuel_type ?? 'АКПП',
                    'hp' => $mark?->hp ?? '1.6',
                    'engine_capacity' => $mark?->engine_capacity ?? '1591',
                    'fuel_tank' => $mark?->fuel_tank ?? '50',
                    'class' => $class->name ?? 'Эконом',
                    'bodywork' => $bodywork->name ?? 'Седан',
                    'deposit'   => $tariffs_new[0]['deposit'] ?? 30000,
                    'conditioner' => $mark?->conditioner,
                    'photo' => $colorPath,
                    'free' => $this->checkAvailableCar($started_at, $ended_at, $mark->id, $carColor),
                    'tariffs' => $tariffs_new,
                ];
            }
        }

        if (empty($availableMarks)) {
            $availableMarks = (object) [];
        }
        return $availableMarks;
    }

    private function checkAvailableCar($started_at = null, $ended_at = null, $modelId = null, $color = null): bool {
        if (!$started_at || !$ended_at || !$modelId) {
            $request = request();
            $started_at = $started_at ?? $request->input('started_at');
            $ended_at = $ended_at ?? $request->input('ended_at');
            $modelId = $modelId ?? $request->input('model_id');
        }

        if (is_null($started_at) or is_null($ended_at)) {
            $started_at = Carbon::now()->format('Y-m-d');
            $ended_at = Carbon::now()->addDays(3)->format('Y-m-d');
        }

        $started_at = Carbon::parse($started_at)->format('Y-m-d');
        $ended_at = Carbon::parse($ended_at)->format('Y-m-d');
        $cars = UniModel::model('pipi_auto')
            ->where('is_inactive', '=', false)
            ->where('model_id', $modelId)
            ->where('color_id', $color->id)
            ->get();
        $busyCars = UniModel::model('pipi_auto_calendar')
            ->whereBetween('date', [$started_at, $ended_at])
            ->pluck('auto_id')
            ->toArray();

        $availableCars = $cars->reject(fn($car) => in_array($car->id, $busyCars));

        return $availableCars->isNotEmpty();
    }

    public function action_rent()
    {
        $request = Request::input();
        dd($request);
    }
}
