<?php

namespace App\Http\Controllers\DiscoveryTools\ChromeBook;

use App\Http\Controllers\Controller;
use App\Http\Responses\ReportJsonResponse;
use App\Http\Traits\DiscoveryToolsAssetUpdateTrait;
use App\Models\AssetStatus;
use App\Models\Chromebook;
use App\Models\IntegrationSyncHistory;
use App\Services\DiscoveryTools\Chromebook\CheckingInNotCreated;
use App\Services\Reports\Generator;
use Illuminate\Http\Request;

class CheckingInNotCreatedController extends Controller
{

    protected $chromebookService;
    use DiscoveryToolsAssetUpdateTrait;

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

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

        return view('discovery-tools.chromebook.checking-in-not-created', compact('assetStatuses', '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();
        $filteredData = $this->chromebookService->exportData();
        $requiredColumns = config('discovery-tools-export-columns.chromebook.Common');
        $filteredData->chunk(5000, function ($filteredDataChunks) use ($data, $datas, $requiredColumns) {
            $datas->push($this->chromebookService->getReportExportData($filteredDataChunks, 0, $data, $requiredColumns));
        });

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

    /**
     * create
     *
     * @return void
     */
    public function create()
    {
        $chromebookAsset = Chromebook::find(request('chromebook-asset-id'));
        $this->CreateAsset($chromebookAsset);
        return redirect('/discovery-tools/chrome-devices/checking-in-not-created')->with('message', 'Asset created successfully.');
    }
}
