<?php

namespace App\Http\Controllers\Reports;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Traits\DataAndExportControllerTrait;
use App\Services\Reports\BrandNewToAssignedService;
use Carbon\Carbon;
use Exception;

class BrandNewToAssignedController extends Controller
{
    use DataAndExportControllerTrait;

    /**
     * Constructs a new instance of the class, initializing it with the provided service.
     *
     * @param BrandNewToAssignedService $service The service to be assigned to the class.
     */
    public function __construct(protected BrandNewToAssignedService $service) {}

    /**
     * Loading the Page for the report
     *
     * @return view file
     */
    public function index()
    {
        $year = carbon::now()->year;

        return view('reports.brand-new-to-assigned.index', compact('year'));
    }

    /**
     * Show graphical represntation of the report
     * @param Request $request
     *
     * @return json
     */
    public function graphData()
    {
        $datas = $this->service->getGraphData();
        $nonZeroElements = array_filter($datas['datas'], function ($value) {
            return $value !== 0;
        });
        $hasResult = count($nonZeroElements) > 0 ? true : false;
        $chartHtml = view('reports.brand-new-to-assigned.partials.chart', ['hasResult' => $hasResult])->render();
        $graphData = $datas['datas'];
        $monthNames = $datas['months'];

        return json_encode(compact('chartHtml', 'graphData', 'monthNames'));
    }

    /**
     * Export the table report data
     *
     * @return array
     */
    public function export()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();

        $data = [];
        $datas = collect();

        try {
            $assets = $this->service->exportData();
            $assets->chunk(5000, function ($assetChunks) use ($data, $datas) {
                $datas->push($this->service->getReportExportData($assetChunks, $data));
            });

            return $datas->toArray();
        } catch (Exception $e) {
            return redirect('/brandnew-to-assigned')->with('error', 'Some error occurred. Please try again later');
        }
    }

    /**
     * Export the graph with list data.
     *
     * @throws Exception Some error occured. Please try again later
     * @return mixed
     */
    public function exportGraphWithListData()
    {
        try {
            setUnlimitedExecutionTimeAndMemoryLimit();

            $dataCollection = $this->export();
            $excel = $this->service->exportGraphAndDataListToExcel($dataCollection);

            return $excel;
        } catch (Exception $e) {
            return redirect('/brandnew-to-assigned')->with('error', 'Some error occured. Please try again later');
        }
    }
}
