<?php

namespace App\Http\Controllers\DiscoveryTools\Jamf;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Responses\ReportJsonResponse;
use App\Models\AssetStatus;
use App\Services\DiscoveryTools\Jamf\CheckingInNotCreated;
use App\Http\Traits\DiscoveryToolsAssetUpdateTrait;
use App\Models\IntegrationSyncHistory;
use App\Models\JamfComputer;

class CheckingInNotCreatedController extends Controller
{
    use DiscoveryToolsAssetUpdateTrait;
    protected $jamfService;

    public function __construct(CheckingInNotCreated $jamfService)
    {
        $this->jamfService = $jamfService;
    }

    public function index()
    {
        $assetStatuses = AssetStatus::orderBy('slug')->get();
        $lastSync = IntegrationSyncHistory::getLastSync(config('integration-sync-histories.jamf'))->first();
        $lastSyncDate = $lastSync?->created_at;

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

    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 for checking in on-hand assets to a CSV file.
     *
     * This function retrieves data from the Jamf service, processes it in chunks,
     * and exports it to a CSV format. The export includes columns specified in
     * the configuration for Jamf discovery tools.
     *
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse The response containing the CSV file for download
     */
    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);
    }

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