<?php

namespace App\Http\Controllers;

use App\Models\IndicatorCategoryModel;
use App\Models\IndicatorEntryModel;
use Illuminate\Http\Request;
use Auth;
use Session;

// app includes
use App\Services\GridBuilder;
use App\Models\IndicatorModel;
use App\Models\UnitModel;

class IndicatorEntryController extends Controller
{

    public function addIndicatorEntries(Request $request)
    {
        $indicators = IndicatorModel::getindicators([], false);
        $currentYear = intVal(date('Y'));
        $years = [];
        for ($i = 2015; $i < $currentYear + 2; $i++) {
            $years[] = $i;
        }

        return view('indicatorEntries.addIndicator', compact('indicators', 'years', 'currentYear'));
    }

    public function getIndicatorEntriesData(Request $request)
    {

        $indicators = $this->getIndicatorsData($request);
        $months = config('vars.months');

        return view('indicatorEntries.indicatorEntryData', compact('indicators', 'months'));
    }

    private function getIndicatorsData(Request $request)
    {
        $filters = array(
            'office_id' => 1,
            'year' => $request->year
        );
        $indicatorEntries = IndicatorEntryModel::getIndicatorEntries($filters);

        $indicators = array();
        foreach ($indicatorEntries as $indicatorEntry) {
            if (!isset($indicators[$indicatorEntry->indicator_id])) {
                $indicators[$indicatorEntry->indicator_id] = array(
                    'indicator' => $indicatorEntry->indicator,
                    'months' => array()
                );
            }
            $indicators[$indicatorEntry->indicator_id]['months'][$indicatorEntry->month] = $indicatorEntry;
        }
        return $indicators;
    }

    public function saveIndicatorEntriesData(Request $request)
    {
        $user = Auth::user();
        $data = array(
            'office_id' => 1,
            'year' => $request->year,
            'value' => $request->value,
            'indicator_id' => $request->indicator_id,
            'user_id' => $user->user_id
        );
    }

    public function addIndicatorEntry(Request $request){        
        $user = Auth::user();
        $data = $request->all();
        $data['office_id'] = 1;
        $data['user_id'] = $user->user_id;

        IndicatorEntryModel::addNewIndicator($data);
    }

    public function saveIndicatorEntryValue(Request $request){
        $user = Auth::user();
        $data = $request->all();
        $data['office_id'] = $user->office_id ?? $request->office_id;
        $data['user_id'] = $user->user_id;

        $indicatorEntry = IndicatorEntryModel::save($data);


    }
}
