<?php

namespace App\Http\Controllers\Reports;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Responses\ReportJsonResponse;
use App\Services\Reports\AssetsByDepartmentService;

class AssetsByDepartmentController extends Controller
{
    
    protected $service;

    /**
     * Constructs a new instance of the class.
     *
     * @param AssetsByDepartmentService $service the department spend service
     */
    public function __construct(AssetsByDepartmentService $service)
    {
        $this->service = $service;
    }
    
    /**
     * Retrieves the necessary data and renders the 'assets-by-department' report view.
     *
     * @return \Illuminate\View\View
     */
    public function index()
    {
        $departments = $this->service->getAllDepartments();
        
        return view('reports.assets-by-department.index', compact('departments'));
    }

    /**
     * fetch the data for `Department Spend` report
     *
     * @param Illuminate\Http\Request $request
     * @return Http\Response
     */
    public function data(Request $request)
    {
        $filteredData = $this->service->data();
        $assets =  $filteredData['assets'];
        $data = [];

        if (!empty($assets)) { 
            $data = $this->service->getReportData($assets, request('start'));
        }
        
        return new ReportJsonResponse($request->input('draw'), $data, $filteredData['count'], $filteredData['additionalDataForReport']);
    }


    /**
     * Export the data to CSV.
     *
     * @return array The exported data in CSV format.
     */
    public function export()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();
        
        $data = [];
        $datas = collect();
        $assets =  $this->service->exportData();

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

        return exportToCsv($datas->toArray());
    }
}
