<?php

namespace App\Http\Controllers;

use App\Exports\EnquiriesByTypeExport;
use App\Exports\VehiclePerformanceExport;
use App\Exports\YearlyEnquiryExport;
use App\Reporting\Repositories\CRMReportRepository;
use App\Reporting\Repositories\VehicleReportRepository;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class ReportController extends Controller
{
    public function crmYearly(Request $request, CRMReportRepository $repository)
    {
        if ($request->input('export')) {
            return Excel::download(new YearlyEnquiryExport($repository->yearlyBreakdown()), 'enquiry_yearly.xlsx');
        }

        return [
            'results' => $repository->yearlyBreakdown(),
        ];
    }

    public function typeBreakdown(Request $request, CRMReportRepository $repository)
    {
        $from = $request->filled('from')
            ? Carbon::parse($request->input('from'))->startOfDay()
            : Carbon::now()->subDays(180)->startOfDay();
        $to = $request->filled('from')
            ? Carbon::parse($request->input('to'))->endOfDay()
            : Carbon::now()->endOfDay();

        if ($request->input('export')) {
            return Excel::download(
                new EnquiriesByTypeExport($repository->typeBreakdown($from, $to)),
                'enquiry_yearly.xlsx'
            );
        }

        return [
            'results' => $repository->typeBreakdown($from, $to),
        ];
    }

    public function vehiclePerformance(Request $request, VehicleReportRepository $repository)
    {
        if ($request->input('export')) {
            return Excel::download(
                new VehiclePerformanceExport($repository->performanceReport($request->input())),
                'vehicle_performance.xlsx'
            );
        }

        return [
            'results' => $repository->performanceReport($request->input()),
        ];
    }

    public function vehicleSegments(Request $request, VehicleReportRepository $repository): array
    {
        return [
            'results' => $repository->segmentReport($request->input()),
        ];
    }
}
