<?php

namespace App\Http\Controllers\Security\Crowdstrike\Reports;

use App\Http\Controllers\Controller;
use App\Http\Responses\ReportJsonResponse;
use Illuminate\Http\Request;
use App\Services\Security\Crowdstrike\Reports\SensorVulnerabilityService;

class SensorVulnerabilityReportController extends Controller
{
    
    private $service;   
    
    /**
     * constructor for Crowdstrike Report Controller
     * 
     * @param SensorVulnerabilityService $service
     * 
     */
    public function __construct(SensorVulnerabilityService $service)
    {
        $this->service = $service;
    }

   
    /**
     * List page for sensor vulnerability report
     *
     * @return \Illuminate\View\View
     */
    public function index()
    {
        return view('security.crowdstrike.sensor-vulnerability.index');
    }


    /**
     * Fetch data for sensor vulnerability report
     *
     * @param \Illuminate\Http\Request $request
     * @return object
     */
    public function data(Request $request)
    {
        $filteredData = $this->service->data();

        if (!empty($filteredData['assetVulnerabilities'])) {
            $data = $this->service->getReportData($filteredData['assetVulnerabilities'], request('start'));
        }

        return new ReportJsonResponse($request->input('draw'), $data, $filteredData['count']);
    }

    /**
     * Exports vulnerability data based on the provided request.
     * 
     * @return mixed the exported vulnerability data in CSV format
     */
    public function  export()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();
        
        $data = [];
        $datas = collect();        
        $assetVulnerabilities = $this->service->exportData();

        $assetVulnerabilities->chunk(5000, function ($assetVulnerabilitiesChunks) use ($data, $datas) {
            $datas->push($this->service->getReportExportData($assetVulnerabilitiesChunks, $data));
        });
        
        return exportToCsv($datas->toArray());
    }

}