<?php

namespace App\Http\Controllers\InventoryConsumption;

use App\Http\Controllers\Controller;
use App\Http\Responses\ReportJsonResponse;
use App\Services\InventoryConsumption\ConsumptionTrendsService;
use Illuminate\Http\Request;

class ConsumptionTrendsController extends Controller
{

    protected $service;

    /**
     * Constructor for the class.
     * @param ConsumptionTrendsService $service
     */
    public function __construct(ConsumptionTrendsService $service)
    {
        $this->service = $service;
    }

    /**
     * Loading the Page for the report
     *
     * @return view file
     */
    public function index()
	{
        $filterDataOptions = $this->service->getFilterDataOptions();

        return view('reports.inventory-consumption.consumption-trends', compact('filterDataOptions'));
	}

    /**
     * Show graphical represntation of the report
     * @param Request $request
     *
     * @return json
     */
    public function graphData()
	{
        $inputData = $this->service->getInputData();
        $dateFrom = $this->service->getFromDate($inputData);
        $dateTo = $this->service->getToDate($inputData);
        $months = get_month_year_names($dateFrom, $dateTo);
        $result = $this->service->getCountOfConsumptionTrend();

        $nonZeroElements = array_filter($result['data'], function($value) {
            return $value !== 0;
        });
        $hasResult = count($nonZeroElements) > 0 ? true : false;
        $chartHtml = view('reports.inventory-consumption.partials.chart', ['hasResult' => $hasResult])->render();
        $graphData = $result['data'];
        $monthNames = collect($months)->flatten()->toArray();

        return json_encode(compact('chartHtml', 'graphData', 'monthNames'));
	}

    /**
     * Retrieves data for the report table
     *
     * @param Request $request The HTTP request object.
     *
     */
    public function data(Request $request)
    {
        $filteredData = $this->service->data();
        $assets =  $filteredData['assets'];
        $data = [];

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

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


}
