<?php

namespace App\Http\Controllers\Reports\CycleCount;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\ReportHistoryVarience;
use Facades\App\Services\Reports\CycleCount\CycleCountHistoryService;

class CycleCountHistoryController extends Controller
{
    public $excludedAssetTypes;

    public $excludedAssetStatuses;

    public function __construct()
    {
        $this->excludedAssetTypes = config('cycle-count.excluded-asset-types');
        $this->excludedAssetStatuses = config('cycle-count.excluded_asset_statuses');
    }

    /**
     * Displaying Variance Histories
     *
     * @return view file
     */
    public function index()
    {
        return view('reports.cycle-count.cycle-count-history');
    }

    /**
     * Content for cycleCount history page Data table
     *
     * @param integer $request->location     Location ID
     */
    public function cycleCountHistoryData(Request $request)
    {
        $request->validate([
            'form.date_from' => 'nullable|date_format:' . config('date.formats.read_date_format'),
            'form.date_to' => 'nullable|date_format:' . config('date.formats.read_date_format'),
        ]);
        $filteredData = CycleCountHistoryService::data();

        $histories =  $filteredData['histories'];
        $totalData = $filteredData['count'];
        $totalFiltered = $totalData;

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

        if (!empty($histories)) {
            $data = CycleCountHistoryService::getReportData($histories, $start);
        }

        $jsonData = [
            "draw"            => intval($request->input('draw')),
            "recordsTotal"    => intval($totalData),
            "recordsFiltered" => intval($totalFiltered),
            "data"            => $data,
            'average'         => $filteredData['average'],
            'heighestAccuracy' =>  $filteredData['heighestAccuracy'],
            'heighestDate'     => $filteredData['heighestDate'] ? $filteredData['heighestDate'] : '<span>&nbsp;</span>',
            'lowestAccuracy' => $filteredData['lowestAccuracy'],
            'lowestDate' => $filteredData['lowestDate'],
            'graphData' => $filteredData['graphData']
        ];

        return response()->json($jsonData);
    }

    /**
     * cycleCount History Details
     *
     * @param integer $id      cycleCount History ID
     *
     * @return view file
     */
    public function cycleCountHistoryDetails($id)
    {
        $history = ReportHistoryVarience::find($id);
        // dd($history);
        $assetTypes = "";
        if (!empty($history->asset_type_ids)) {
            $assetTypes = CycleCountHistoryService::getSelectedAssetTypes($history->asset_type_ids);
        }

        return view('reports.cycle-count.cycle-count-result-history', compact('history', 'assetTypes'));
    }
}
