<?php

namespace App\Http\Controllers\DiscoveryTools\ChromeBook;

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

class AllChromeBookController extends Controller
{

    protected $allReport;

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

    /**
     * Showing the `All chromebook report`
     * @return View
     */
    public function index()
    {
        $lastSync = IntegrationSyncHistory::getLastSync(config('integration-sync-histories.chromebook'))->first();
        $lastSyncDate = $lastSync?->created_at;

        return view('discovery-tools.chromebook.all-chromebook-report', compact('lastSyncDate'));
    }

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

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

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

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


    /**
     * Export the data from the `All chromebook` report
     *
     * @return Http\Response
     */
    public function export()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();
        
        $data = [];
        $datas = collect();
        $filteredData = $this->allReport->exportData();

        $requiredColumns = config('discovery-tools-export-columns.chromebook.Common');
        $filteredData->chunk(5000, function ($siteCodeChunks) use ($data, $datas, $requiredColumns) {
            $datas->push($this->allReport->getReportExportData($siteCodeChunks, 0, $data, $requiredColumns));
        });

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