<?php

namespace App\Http\Controllers;

use App\Exports\EnquiriesByTypeExport;
use App\Exports\EnquiriesByUtmExport;
use App\Exports\EnquiryTimingBreakdownExport;
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') && $request->input('from') !== "null"
            ? Carbon::parse($request->input('from'))->startOfDay()
            : Carbon::now()->subDays(180)->startOfDay();
        $to = $request->filled('to') && $request->input('to') !== "null"
            ? 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 utmBreakdown(Request $request, CRMReportRepository $repository)
    {
        $dimension = $repository->resolveDimension($request->input('dimension'));
        $from = $request->filled('from') && $request->input('from') !== "null"
            ? Carbon::parse($request->input('from'))->startOfDay()
            : Carbon::now()->subDays(180)->startOfDay();
        $to = $request->filled('to') && $request->input('to') !== "null"
            ? Carbon::parse($request->input('to'))->endOfDay()
            : Carbon::now()->endOfDay();

        $results = $repository->utmBreakdown($dimension, $from, $to);

        if ($request->input('export')) {
            return Excel::download(
                new EnquiriesByUtmExport($results, $dimension),
                'enquiry_utm_breakdown.xlsx'
            );
        }

        return [
            'dimension' => $dimension,
            'results' => $results,
        ];
    }

    public function crmWeekdayBreakdown(Request $request, CRMReportRepository $repository)
    {
        [$from, $to] = $this->resolveRange($request, 90);
        $results = $repository->weekdayBreakdown($from, $to);

        if ($request->input('export')) {
            return Excel::download(
                new EnquiryTimingBreakdownExport($results, __('labels.day')),
                'enquiry_weekday_breakdown.xlsx'
            );
        }

        return [
            'results' => $results,
        ];
    }

    public function crmTimeOfDayBreakdown(Request $request, CRMReportRepository $repository)
    {
        [$from, $to] = $this->resolveRange($request, 90);
        $results = $repository->timeOfDayBreakdown($from, $to);

        if ($request->input('export')) {
            return Excel::download(
                new EnquiryTimingBreakdownExport($results, __('labels.hour')),
                'enquiry_time_of_day_breakdown.xlsx'
            );
        }

        return [
            'results' => $results,
        ];
    }

    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()),
        ];
    }

    /**
     * Resolve the report date range from the request, defaulting to the last $defaultDays days when
     * either bound is missing. The frontend sends the literal string "null" for an empty picker, so
     * that is treated the same as an absent value.
     *
     * @return array{0: Carbon, 1: Carbon}
     */
    private function resolveRange(Request $request, int $defaultDays): array
    {
        $from = $request->filled('from') && $request->input('from') !== "null"
            ? Carbon::parse($request->input('from'))->startOfDay()
            : Carbon::now()->subDays($defaultDays)->startOfDay();
        $to = $request->filled('to') && $request->input('to') !== "null"
            ? Carbon::parse($request->input('to'))->endOfDay()
            : Carbon::now()->endOfDay();

        return [$from, $to];
    }
}
