<?php

namespace App\Exports;

use App\Facades\Settings;
use App\Facades\Site;
use App\SalesChannelType;
use App\Traits\UsesSalesChannelRules;
use App\VehicleType;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Mtc\ContentManager\Models\MediaUse;
use Mtc\MercuryDataModels\Vehicle;

class InventoryExport implements FromCollection, WithHeadings
{
    use UsesSalesChannelRules;

    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        return Vehicle::query()
            ->with([
                'mediaUses.media',
                'dealership',
                'make',
                'model',
                'transmission',
                'fuelType',
                'bodyStyle',
                'drivetrain',
                'specs',
            ])
            ->exportable()
            ->when(
                $this->hasSalesChannelRules(SalesChannelType::INVENTORY),
                fn($query) => $this->applyQueryConditionsForChannel($query, SalesChannelType::INVENTORY)
            )
            ->get()
            ->map(function (Vehicle $vehicle) {
                $photoTimestamp = $vehicle->mediaUses
                    ->sortByDesc('updated_at')
                    ->first()
                    ?->updated_at
                    ->format('Y-m-d H:i:s');

                return [
                    'Dealer ID' => $vehicle->dealership?->data['inventory-dealer-id'] ?? null,
                    'Dealer Name' => $vehicle->dealership?->name,
                    'Is New' => $vehicle->is_new ? 'N' : 'U',
                    'Status' => $vehicle->is_reserved ? 'Reserved' : 'Instock',
                    'Note' => '',
                    'VIN' => $vehicle->vin,
                    'Stock #' => $vehicle->uuid,
                    'Year' => $vehicle->manufacture_year,
                    'Make' => $vehicle->make?->name,
                    'Model' => $vehicle->model?->name,
                    'Trim' => $vehicle->derivative,
                    'Body Style' => $vehicle->bodyStyle?->name,
                    'Body Type' => $vehicle->type == VehicleType::LCV ? 'VCV' : 'CAR',
                    'Factory Certified' => '',
                    'Dealer Certified' => '',
                    'Model Code' => '',
                    'List Price' => $vehicle->price,
                    'Special Price' => $vehicle->price,
                    'Cost Price' => $vehicle->price,
                    'ExtraPrice1' => '',
                    'ExtraPrice2' => '',
                    'ExtraPrice3' => '',
                    'Mileage' => $vehicle->odometer_mi,
                    'Chrome Style ID' => '',
                    'Fuel Type' => $vehicle->fuelType?->name,
                    'Exterior color' => $vehicle->colour,
                    'Exterior Color Code' => '',
                    'Interior Color' => '',
                    'Interior Color Code' => '',
                    'Interior Material' => '',
                    'Wheelbase' => $vehicle->wheelbase_type,
                    'DoorCount' => $vehicle->door_count,
                    'EngineDisplacement' => $vehicle->engine_size_cc,
                    'Cylinders' => '',
                    'Engine' => '',
                    'Drivetrain' => $vehicle->drivetrain?->name,
                    'Transmission' => $vehicle->transmission?->name,
                    'Transmission Speed' => '',
                    'Option Description' => $vehicle->specs
                        ->pluck('description')
                        ->implode(','),
                    'Option code' => '',
                    'Photo URLs' => $vehicle->mediaUses
                        ->filter(fn($mediaUse) => $mediaUse->media)
                        ->map(fn(MediaUse $mediaUse) => $mediaUse->getUrl('large'))
                        ->implode(','),
                    'Photo Timestamp' => $photoTimestamp ?? '',
                    'Dealer comments on vehicle' => '',
                    'In Stock Date' => $vehicle->date_in_stock,
                    'Last Modified Date' => $vehicle->updated_at->format('Y-m-d H:i:s'),
                    'Video URL' => $vehicle->main_video_url,
                    'City MPG' => $vehicle->mpg,
                    'Hwy MPG' => $vehicle->mpg,
                    'VDP Link' => Site::vehicleUrl($vehicle),
                    'Extra Field 1' => '',
                    'Extra Field 2' => '',
                    'Extra Field 3' => '',
                ];
            });
    }

    /**
     * Heading row
     *
     * @return string[]
     */
    public function headings(): array
    {
        return [
            'Dealer ID',
            'Dealer Name',
            'Is New',
            'Status',
            'Note',
            'VIN',
            'Stock #',
            'Year',
            'Make',
            'Model',
            'Trim',
            'Body Style',
            'Body Type',
            'Factory Certified',
            'Dealer Certified',
            'Model Code',
            'List Price',
            'Special Price',
            'Cost Price',
            'ExtraPrice1',
            'ExtraPrice2',
            'ExtraPrice3',
            'Mileage',
            'Chrome Style ID',
            'Fuel Type',
            'Exterior color',
            'Exterior Color Code',
            'Interior Color',
            'Interior Color Code',
            'Interior Material',
            'Wheelbase',
            'DoorCount',
            'EngineDisplacement',
            'Cylinders',
            'Engine',
            'Drivetrain',
            'Transmission',
            'Transmission Speed',
            'Option Description',
            'Option code',
            'Photo URLs',
            'Photo Timestamp',
            'Dealer comments on vehicle',
            'In Stock Date',
            'Last Modified Date',
            'Video URL',
            'City MPG',
            'Hwy MPG',
            'VDP Link',
            'Extra Field 1',
            'Extra Field 2',
            'Extra Field 3',
        ];
    }
}
