<?php

namespace App\Http\Controllers\DiscoveryTools\Jamf;

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

class NotCheckingInManagedController extends Controller
{

    /**
     * Constructor for the SomeService class.
     *
     * @param NotCheckingInManaged $jamfService Service for managing devices not checking in.
     */
    public function __construct(protected NotCheckingInManaged $jamfService)
    {
    }

    /**
     * Display the page showing devices not checking in.
     *
     * @return \Illuminate\View\View The view for the not-checking-in-managed page.
     */
    public function index()
    {
        $lastSync = IntegrationSyncHistory::getLastSync(config('integration-sync-histories.jamf'))->first();
        $lastSyncDate = $lastSync?->created_at;

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

    /**
     * Retrieve and return filtered data for the report.
     *
     * @param Request $request The incoming request instance.
     *
     * @return ReportJsonResponse JSON response with the filtered data for the report.
     */
    public function data(Request $request)
    {
        $filteredData = $this->jamfService->data();

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

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

    /**
     * Export data to a CSV file.
     *
     * @return \Symfony\Component\HttpFoundation\StreamedResponse The response containing the CSV file.
     */
    public function export()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();

        $data = [];
        $datas = collect();

        $assetsNotCreated = $this->jamfService->exportData();
        $requiredColumns = config('discovery-tools-export-columns.jamf.Common');

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

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