<?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 IndicatorModel
 *
 * @author jehm2
 */
class IndicatorModel
{

    public static function getIndicators($filters = array(), $paginate = 10)
    {
        $query = Indicator::query();
        return $paginate ? $query->paginate($paginate) : $query->get();
    }

    public static function getIndicator($indicator_id)
    {
        return Indicator::find($indicator_id);
    }

    public static function save($data)
    {
        $indicator_id = $data['indicator_id'] ?? null;
        $indicator = IndicatorModel::getIndicator($indicator_id);
        if ($indicator) {
            $indicator->update($data);
        } else {
            $indicator = Indicator::create($data);
        }

        return $indicator;
    }

    public static function delete($indicator_id)
    {
        $indicator = IndicatorModel::getIndicator($indicator_id);
        if ($indicator) {
            return $indicator->delete();
        }
        return false;
    }

    public static function getIndicatorQuery($request)
    {
        $query = Indicator::query();

        if (isset($request->keyword)) {
            $query->where(function ($sQuery) use ($request) {
                $sQuery->where('name', 'like', "%{$request->keyword}%");
                $sQuery->orWhere('description', 'like', "%{$request->keyword}%");
                $sQuery->orWhere('type', 'like', "%{$request->keyword}%");
                $sQuery->orWhereHas('unit', function ($rQuery) use ($request) {
                    $rQuery->where('name', 'like', "%{$request->keyword}%");
                });
                $sQuery->orWhereHas('indicator_category', function ($rQuery) use ($request) {
                    $rQuery->where('name', 'like', "%{$request->keyword}%");
                });
            });
        }

        return $query;
    }

    public static function getValidator($data)
    {

        $rules = [
            'unit_id' => ['required', 'exists:units,unit_id'],
            'indicator_category_id' => ['required', 'exists:indicator_categories,indicator_category_id'],
            'name' => ['required', 'max:255'],
            'type' => ['max:255'],
        ];

        $messages = ModelUtils::getMessages();

        $validator = Validator::make($data, $rules, $messages);

        $niceNames = array(
            'unit_id' => 'Unidad',
            'indicator_category_id' => 'Categoria',
            'name' => 'Nombre',
            'description' => 'Descripción',
            'type' => 'Tipo',
        );
        $validator->setAttributeNames($niceNames);

        return $validator;
    }
}
