<?php

namespace App\Http\Controllers\DiscoveryTools\MobileIron;

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

/**
 * Controller Claass for Devices Not Active
 */
class NotCheckingInManagedController extends Controller
{
    protected $service;

    public function __construct(NotCheckingInManaged $mobileIronService)
    {
        $this->service = $mobileIronService;
    }

    /**
     * Showing the Devices that are not in teqtivity but in MobileIron
     * @return Http\Response
     */
    public function index()
    {
        $lastSync = IntegrationSyncHistory::getLastSync(config('integration-sync-histories.mobile-iron'))->first();
        $lastSyncDate = $lastSync?->created_at;

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

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


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

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

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


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

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