<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace App\Models;

use Validator;

/**
 * Description of IndicatorEntryModel
 *
 * @author jehm2
 */
class IndicatorEntryModel
{

    public static function getIndicatorEntries($filters = array(), $paginate = false)
    {
        $query = IndicatorEntry::query();
        if (isset($filters['office_id'])) {
            $query->where('office_id', $filters['office_id']);
        }
        if (isset($filters['year'])) {
            $query->where('year', $filters['year']);
        }
        if (isset($filters['indicator_id'])) {
            $query->where('indicator_id', $filters['indicator_id']);
        }

        return $paginate ? $query->paginate($paginate) : $query->get();
    }

    public static function getIndicatorEntry($indicator_entry_id)
    {
        return IndicatorEntry::find($indicator_entry_id);
    }

    public static function getIndicatorEntryByData($data)
    {
        $query = IndicatorEntry::query();
        $query->where('office_id', $data['office_id'] ?? null);
        $query->where('indicator_id', $data['indicator_id'] ?? null);
        $query->where('year', $data['year'] ?? null);
        $query->where('month', $data['month'] ?? null);

        return $query->first();
    }

    public static function save($data)
    {
        $indicatorEntry = IndicatorEntryModel::getIndicatorEntryByData($data);
        if ($indicatorEntry) {
            $indicatorEntry->update($data);
        } else {
            $indicatorEntry = IndicatorEntry::create($data);
        }

        return $indicatorEntry;
    }

    public static function delete($indicator_entry_id)
    {
        $indicatorEntry = IndicatorEntryModel::getIndicatorEntry($indicator_entry_id);
        if ($indicatorEntry) {
            return $indicatorEntry->delete();
        }
        return false;
    }

    public static function getIndicatorsByOffice($office_id)
    {
        $query = IndicatorEntry::query();
        return $query->get();
    }

    public static function addNewIndicator($data)
    {
        $indicator_id = $data['indicator_id'];
        $year = $data['year'] ?? date('y');
        if ($indicator_id) {
            $filters = ['indicator_id' => $indicator_id, 'year' => $year];
            $indicatorEntries = IndicatorEntryModel::getIndicatorEntries($filters);
            if (!$indicatorEntries->count()) {
                $newIndicatorEntry = array(
                    'indicator_id' => $indicator_id,
                    'user_id' => $data['user_id'],
                    'office_id' => $data['office_id'],
                    'year' => $year,
                    'month' => date('m')
                );
                IndicatorEntryModel::save($newIndicatorEntry);
            }
        }
    }
}
