<?php

namespace App\Http\Controllers\DiscoveryTools\ChromeBook;

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

class NotCheckingInManagedController extends Controller
{


    protected $chromebookService;

    public function __construct(NotCheckingInManaged $chromebookService, Generator $reportGenerator)
    {
        $this->chromebookService = $chromebookService;
        $this->reportGenerator = $reportGenerator;
    }

    /**
     * Showing the Mobile Number Report
     * @return Http\Response
     */
    public function index()
    {
        $lastSync = IntegrationSyncHistory::getLastSync(config('integration-sync-histories.chromebook'))->first();
        $lastSyncDate = $lastSync?->created_at;

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

    /**
     * Taking the data to the `Mobile Number` report
     *
     * @param Illuminate\Http\Request $request
     * @return Http\Response
     */
    public function data(Request $request)
    {
        setUnlimitedExecutionTimeAndMemoryLimit();
        
        $filteredData = $this->chromebookService->data();
        $assets = $filteredData['assets'];

        $start = request('start');
        $data = [];

        if (!empty($assets)) {
            $data = $this->chromebookService->getReportData($assets, $start, $data);
        }

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


    /**
     * Taking the data to the `Mobile Number` report
     *
     * @return Http\Response
     */
    public function export()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();
        
        $data = [];
        $datas = collect();
        $requiredColumns = config('discovery-tools-export-columns.chromebook.Common');
        $filteredData = $this->chromebookService->exportData();
        $filteredData->chunk(5000, function ($filteredDataChunks) use ($data, $datas, $requiredColumns) {
            $datas->push($this->chromebookService->getReportExportData($filteredDataChunks, 0, $data, $requiredColumns));
        });

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