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

    public static function getOffices($filters = array(), $paginate = false)
    {
        $query = Office::query();
        return $paginate ? $query->paginate($paginate) : $query->get();
    }

    public static function getOffice($office_id)
    {
        return Office::find($office_id);
    }

    public static function save($data)
    {
        $office_id = $data['office_id'] ?? null;
        $office = OfficeModel::getOffice($office_id);
        if ($office) {
            $office->update($data);
        } else {
            $office = Office::create($data);
        }

        return $office;
    }

    public static function delete($office_id)
    {
        $office = OfficeModel::getOffice($office_id);
        if ($office) {
            return $office->delete();
        }
        return false;
    }

    public static function getOfficeQuery($request)
    {
        $query = Office::query();

        $query->where('company_id', $request->company_id);

        if (isset($request->keyword)) {
            $query->where(function ($sQuery) use ($request) {
                $sQuery->where('name', 'like', "%{$request->keyword}%");
                $sQuery->where('email', 'like', "%{$request->keyword}%");
                $sQuery->where('phone', 'like', "%{$request->keyword}%");
                $sQuery->where('agentName', 'like', "%{$request->keyword}%");
                $sQuery->where('agentPhone', 'like', "%{$request->keyword}%");
            });
        }

        return $query;
    }

    public static function getValidator($data)
    {

        $rules = [
            'company_id' => ['required', 'exists:companies,company_id'],
            'name' => ['required', 'max:255'],
            'email' => ['email', 'max:255'],
            'phone' => ['max:255'],
            'agentName' => ['max:255'],
            'agentPhone' => ['max:255'],

        ];

        $messages = ModelUtils::getMessages();

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

        $niceNames = array(
            'name' => 'Nombre',
            'email' => 'Email',
            'phone' => 'Teléfono',
            'agentName' => 'Nombre representante',
            'agentPhone' => 'Teléfono representante',
        );
        $validator->setAttributeNames($niceNames);

        return $validator;
    }
}
