<?php

namespace App\Http\Controllers\Charts;

use App\Models\Resource;
use Illuminate\Http\Request;
use App\Services\ChartService;
use Barryvdh\DomPDF\Facade\Pdf;
use App\Http\Controllers\Controller;

class ChartDrillPrintController extends Controller
{
    public $chartService;

    public function __construct(ChartService $chartService)
    {
        $this->chartService = $chartService;
    }

    public function __invoke(Resource $chart)
    {

        if (empty(request()->query()) || !isset(request()->query()['xValue'])) {
            abort(Response::HTTP_NOT_FOUND);
        }

        $xValue = request()->query()['xValue'];

        [$data, $keys, $label] = $this->chartService->drill($chart, request()->query()['xValue']);

        if (count($keys) > 5) {

            $pdf = Pdf::loadView('dashboard.charts.pdf.drill', compact('chart', 'data', 'keys', 'label', 'xValue'))->setPaper('a4', 'landscape');

        } else {

            $pdf = Pdf::loadView('dashboard.charts.pdf.drill', compact('chart', 'data', 'keys', 'label', 'xValue'));

        }

        return $pdf->stream($chart->name . '-' . $xValue . '-page ' . $data->currentPage() . '.pdf');

    }

}