<?php

namespace App\Http\Controllers\Reports;

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

class BrandNewAssignedToContractorController extends Controller
{
    use DataAndExportControllerTrait;

    /**
     * Constructor for the BrandNewAssignedToContractorController.
     *
     * @param BrandNewAssignedToContractorService $service
     */
    public function __construct(protected BrandNewAssignedToContractorService $service) {}

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

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


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

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

    /**
     * Export one year asset details
     * @param Request $request
     * @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-assigned-to-contractor')->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-assigned-to-contractor')->with('error', 'Some error occured. Please try again later');
        }
    }
}
