<?php

namespace App\Http\Controllers;

use App\Exports\ChannelFeedExport;
use App\Exports\FacebookFeedExport;
use App\Exports\GoogleFeedExport;
use App\Exports\EasiChatFeedExport;
use App\Facades\Settings;
use App\Http\Resources\StormEnquiryItemResource;
use App\Http\Resources\StormEnquiryResource;
use App\Support\MultiTablePaginator;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Mtc\MercuryDataModels\Booking;
use Mtc\MercuryDataModels\Enquiry;
use Illuminate\Pagination\LengthAwarePaginator;
use Maatwebsite\Excel\Facades\Excel;
use Mtc\VehicleReservations\Reservation;

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($export->map(...));

            $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 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);
        }
    }

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

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

        $export = new EasiChatFeedExport();

        $fileName = 'easichat_stock.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 stormEnquiries(Request $request)
    {
        $data = new MultiTablePaginator()
            ->addTable('enquiries', Enquiry::class)
            ->addTable('reservations', Reservation::class)
            ->addTable('service_bookings', Booking::class)
            ->filterByCreatedAt(
                $request->filled('From') ? Carbon::parse($request->input('From')) : null,
                $request->filled('To') ? Carbon::parse($request->input('To')) : null
            )
            ->orderBy('created_at', 'desc')
            ->paginate();

        return new StormEnquiryResource($data)->toArray($request);
    }

    public function stormEnquiry(Request $request, string $type, int $id)
    {
        $record = match ($type) {
            'enquiry' => Enquiry::query()->find($id),
            'booking' => Booking::query()->find($id),
            'reservation' => Reservation::query()->find($id),
            default => null,
        };

        if (!$record) {
            return response('Not found', 404);
        }
        return new StormEnquiryItemResource($record);
    }
}
