<?php

namespace App\Http\Controllers\DiscoveryTools\Intune;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\DiscoveryTools\Intune\NotCheckingInManaged;
use App\Http\Responses\ReportJsonResponse;
use App\Models\IntegrationSyncHistory;
use Cache;

class NotCheckingInManagedController extends Controller
{
    protected $intuneService;

    public function __construct(NotCheckingInManaged $intuneService)
    {
        $this->intuneService = $intuneService;
    }

    public function index()
    {
        $lastSync = IntegrationSyncHistory::getLastSync(config('integration-sync-histories.intune'))->first();
        $lastSyncDate = $lastSync?->created_at;

        return view('discovery-tools.intune.not-checking-in-managed', compact('lastSyncDate'));
    }

    public function data(Request $request)
    {
        $filteredData = $this->intuneService->data();

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

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

    /**
     * Exports data to a CSV file.
     *
     * This function retrieves data using the Intune service, processes it in chunks,
     * and exports it to a CSV file. It ensures that execution time and memory limits
     * are set to unlimited to handle large data sets.
     *
     * @return \Symfony\Component\HttpFoundation\StreamedResponse
     */
    public function export()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();
        
        $data = [];
        $datas = collect();
        $assetsNotCreated =  $this->intuneService->exportData();
        $requiredColumns = config('discovery-tools-export-columns.intune.Common');

        $assetsNotCreated->chunk(5000, function ($assetChunks) use ($data, $datas, $requiredColumns) {
            $datas->push($this->intuneService->getReportExportData($assetChunks, 0, $data, $requiredColumns));
        });

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