<?php

namespace App\Http\Controllers\DiscoveryTools\Intune;

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

class NotCheckingInNotManagedController extends Controller
{

    protected $intuneService;

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


    /**
     * Showing the assets that are Deployed - Active, not Managed
     * @return Http\Response
     */
    public function index()
    {
        $lastSync = IntegrationSyncHistory::getLastSync(config('integration-sync-histories.intune'))->first();
        $lastSyncDate = $lastSync?->created_at;

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

    /**
     * Taking the data to the `Deployed - Active, not Managed` report data table
     * @return Http\Response
     */
    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']);
    }

    /**
     * Taking the data for Export
     * @return Http\Response
     */
    public function export()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();
        
        $data = [];
        $datas = collect();
        $assetsNotCreated =  $this->intuneService->exportData();
        $requiredColumns = config('discovery-tools-export-columns.intune.DeviceActiveButNotManaged');

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

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