<?php

namespace App\Http\Controllers;

use App\Exports\ChannelFeedExport;
use App\Exports\FacebookFeedExport;
use App\Exports\GoogleFeedExport;
use App\Facades\Settings;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Mtc\ContentManager\Models\MediaUse;
use Mtc\MercuryDataModels\Vehicle;
use Illuminate\Pagination\LengthAwarePaginator;
use Maatwebsite\Excel\Facades\Excel;

class FeedController extends Controller
{
    public function channable(Request $request)
    {
        if ($request->input('api_token') != config('auth.api_auth_token')) {
            abort(401);
        }

        if (Settings::get('sales-channels-channel-feed-pagination-enabled', false)) {
            $export = new ChannelFeedExport();
            $vehicleQuery = $export->query();
            $perPage = $request->get('per_page', 15);
            $currentPage = $request->get('page', 1);
            $vehicles = $vehicleQuery->paginate($perPage, ['*'], 'page', $currentPage);
            $mappedVehicles = $vehicles->map(function ($vehicle) use ($export) {
                return $export->map($vehicle);
            });

            $paginatedData = new LengthAwarePaginator(
                $mappedVehicles,
                $vehicles->total(),
                $perPage,
                $currentPage,
                ['path' => $request->url(), 'query' => $request->query()]
            );

            return response()->json($paginatedData);
        } else {
            $tenant = tenant('id');
            return Storage::disk('file-storage')
                ->get("feeds/channel-feed/$tenant.csv");
        }
    }

    public function phyron(Request $request): Response
    {
        if ($request->input('api_token') != config('auth.api_auth_token')) {
            abort(401);
        }
        return response(Vehicle::query()
            ->with([
                'mediaUses.media',
                'dealership',
                'make',
                'model',
                'transmission',
                'fuelType',
                'bodyStyle',
                'drivetrain',
                'features',
                'specs',
                'equipment',
            ])
            ->when(
                Settings::get('image-sync-exclude-sold'),
                fn($query) => $query->where('is_sold', '!=', 1)
            )
            ->when(
                Settings::get('image-sync-exclude-reserved'),
                fn($query) => $query->where('is_reserved', '!=', 1)
            )
            ->exportable()
            ->get()
            ->map(function (Vehicle $vehicle) {
                return [
                    'dealer_ID' => $vehicle->dealership?->data['phyron-dealer-id'] ?? '',
                    'Vehicle_ID' => $vehicle->uuid,
                    'FullRegistration' => str_replace(' ', '', $vehicle->registration_number),
                    'Colour' => $vehicle->colour,
                    'FuelType' => $vehicle->fuelType?->name,
                    'Year' => $vehicle->manufacture_year,
                    'Mileage' => $vehicle->odometer_mi,
                    'Bodytype' => $vehicle->bodyStyle?->name,
                    'Doors' => $vehicle->door_count,
                    'Make' => $vehicle->make?->name,
                    'Model' => $vehicle->model?->name,
                    'Variant' => $vehicle->derivative,
                    'EngineSize' => $vehicle->engine_size_cc,
                    'Price' => $vehicle->price,
                    'Transmission' => $vehicle->transmission?->name,
                    'FourWheelDrive' => $vehicle->drivetrain?->name == 'Four Wheel Drive' ? 'Y' : 'N',
                    'Images' => $vehicle->mediaUses
                        ->map(fn(MediaUse $mediaUse) => $mediaUse->getUrl('large')),
                    'Options' => $vehicle->specs->count()
                        ? $vehicle->specs->pluck('description')
                        : ($vehicle->features->count()
                            ? $vehicle->features->pluck('name')
                            : $vehicle->equipment->pluck('description')),
                ];
            }));
    }

    public function facebook(Request $request)
    {
        if ($request->input('api_token') != config('auth.api_auth_token')) {
            abort(401);
        }

        $export = new FacebookFeedExport();

        $fileName = 'facebook_feed.csv';
        if ($request->input('download') === 'true') {
            return Excel::download($export, $fileName, null, [
                'Content-Type' => 'text/csv; charset=UTF-8',
                'Content-Disposition' => 'attachment; filename=' . $fileName
            ]);
        }

        // Return CSV response to display in the browser
        $path = 'feeds/channel-feed/' . $fileName;
        $disk = config('app.env') == 'local' ? 'public' : 'file-storage';
        if (Excel::store($export, $path, $disk)) {
            return Storage::disk($disk)->get($path);
        }
    }

    public function google(Request $request, GoogleFeedExport $export)
    {
        if ($request->input('api_token') != config('auth.api_auth_token')) {
            abort(401);
        }

        if (!Settings::get('sales-channels-google-enabled', false)) {
            abort(404);
        }

        $fileName = 'google.csv';
        $disk = config('app.env') == 'local' ? 'public' : 'file-storage';

        if ($request->input('download') === 'true') {
            return Excel::download($export, $fileName, null, [
                'Content-Type' => 'text/csv; charset=UTF-8',
                'Content-Disposition' => 'attachment; filename=' . $fileName
            ]);
        }

        $path = 'feeds/google-feed/' . $fileName;
        if (Excel::store($export, $path, $disk)) {
            return Storage::disk($disk)->get($path);
        }
    }
}
