<?php

namespace App\Http\Controllers\DiscoveryTools\WorkspaceOne;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\DiscoveryTools\WorkspaceOne\CheckedInOnHand;
use App\Http\Responses\ReportJsonResponse;
use App\Models\IntegrationSyncHistory;
use Cache;

class CheckedInOnHandController extends Controller
{
    protected $workspaceService;

    public function __construct(CheckedInOnHand $workspaceService)
    {
        $this->workspaceService = $workspaceService;
    }

    /**
     * Devices on hand report page
     * @return [type]
     */
    public function index()
    {
        $lastSync = IntegrationSyncHistory::getLastSync(config('integration-sync-histories.chromebook'))->first();
        $lastSyncDate = $lastSync?->created_at;

        return view('discovery-tools.workspace-one.devices-on-hand-checked-in', compact('lastSyncDate'));
    }

    /**
     * data for showing in table
     * @param Request $request
     *
     * @return [type]
     */
    public function data(Request $request)
    {
        $filteredData = $this->workspaceService->data();
        if (!empty($filteredData['assets'])) {
            $data = $this->workspaceService->getReportData($filteredData['assets'], request('start'));
        }

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

    /**
     * export the report to csv
     * @return [type]
     */
    public function export()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();
        
        $data = [];
        $datas = collect();
        $assetsNotCreated =  $this->workspaceService->exportData('DevicesOnHandCheckedIn');
        $requiredColumns = $requiredColumns = config('discovery-tools-export-columns.workspaceOne.Common');

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

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