<?php

namespace App\Http\Controllers\Reports;

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

class AssetsAssignedByMonthController extends Controller
{
    use DataAndExportControllerTrait;

    /**
     * Constructor for the class.
     *
     * @param AssetsAssignedByMonthService $service The service to be injected.
     */
    public function __construct(protected AssetsAssignedByMonthService $service) {}

    /**
     * Report Page
     *
     * @return Illuminate\View\View The rendered view.
     */
    public function index()
    {
        $year = Carbon::now()->year;

        return view('reports.assets-assigned-by-month.index', compact('year'));
    }

    /**
     * Show graphical represntation of the report
     * @param Request $request
     *
     * @return json
     */
    public function graphData()
    {
        $year = request('year');
        $datas = $this->service->assetsAssignedByMonthData($year);
        $chartHtml = view('reports.assets-assigned-by-month.partials.chart')->render();
        $graphData['assignedCounts'] = $datas['assigned_count'];
        $graphData['brandnewAndUsedCounts'] = $datas['brandnew_and_used_count'];
        $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()->route('assets-assigned-by-month')->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()->route('assets-assigned-by-month')->with('error', 'Some error occured. Please try again later');
        }
    }
}
