<?php

namespace App\Models\Auth;

use App\Models\System\SysCustomer;
use App\Notifications\ResetPasswordNotification;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Kyslik\ColumnSortable\Sortable;
use Hyn\Tenancy\Traits\UsesTenantConnection;
use Hyn\Tenancy\Traits\UsesSystemConnection;

/**
 * App\Models\Auth\User
 *
 * @property int $id
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property int|null $created_uid
 * @property int|null $updated_uid
 * @property string $name
 * @property string $first_name
 * @property string|null $last_name
 * @property string $email
 * @property string $password
 * @property string|null $remember_token
 * @property string|null $avatar
 * @property string|null $expiry_date
 * @property string|null $last_login
 * @property bool $superadmin
 * @property int $sort_order
 * @property bool $status
 * @property int|null $sys_customer_id
 * @property bool $distributor
 * @property int $available_folio
 * @property int|null $company_id
 * @property-read \Illuminate\Notifications\DatabaseNotificationCollection|\Illuminate\Notifications\DatabaseNotification[] $notifications
 * @property-read \App\Models\System\SysCustomer|null $sysCustomer
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User active()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User distributor()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User filter($input = array())
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User notSuperadmin()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User sortable($defaultParameters = null)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User userDistributor()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereAvailableFolio($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereAvatar($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereCompanyId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereCreatedUid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereDistributor($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereEmail($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereExpiryDate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereFirstName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereLastLogin($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereLastName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User wherePassword($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereRememberToken($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereSortOrder($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereSuperadmin($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereSysCustomerId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Auth\User whereUpdatedUid($value)
 * @mixin \Eloquent
 */
class User extends Authenticatable
{
    use Notifiable, Sortable, UsesSystemConnection;

    protected $table = 'users';

    const PATH_AVATARS = 'images/users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'created_uid',
        'updated_uid',
        'name',
        'email',
        'password',
        'expiry_date',
        'avatar',
        'sort_order',
        'status',
        'sys_customer_id',
        'distributor',
        'available_folio',
        'company_id',
        'p_customers',
        'p_products',
        'p_customer_quotations',
        'p_cfdis',
        'p_payrolls',
        'p_tax_mailbox',
        'p_cfdi_downloads',
        'p_bank_reconciliations',
        'p_report_income_expenses',
        'p_catalogs',
        'p_branch_offices',
        'p_companies',
        'p_add_companies',
        'p_edit_companies',
        'p_settings',
        'p_admin',
        'p_users',
        'email_verified_token',
        'p_customer_remissions',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Sortable columns.
     *
     * @var array
     */
    public $sortable = [
        'name',
        'first_name',
        'last_name',
        'email',
        'sort_order',
        'status',
        'distributor',
        'available_folio',
        'last_login'
    ];

    public function sendPasswordResetNotification($token)
    {
        $this->notify(new ResetPasswordNotification($token));
    }

    /**
     * @return string
     */
    public function pathAvatar(){
        return '/app-images/' . self::PATH_AVATARS . '/' . $this->avatar;
    }

    /**
     * Filtros generales
     *
     * @param $query
     * @param array $input
     * @return mixed
     */
    public function scopeFilter($query, array $input = [])
    {
        if (!empty($input['filter_search'])) {
            $search = $input['filter_search'];
            $query->orWhere('name', 'like', '%' . str_replace(' ', '%%', $search) . '%');
            $query->orWhere('email', 'like', '%' . str_replace(' ', '%%', $search) . '%');
            $query->orWhereHas('sysCustomer', function ($q) use ($search) {
                $q->where('sys_customers.name', 'like', '%' . str_replace(' ', '%%', $search) . '%');
                $q->orWhere('sys_customers.taxid', 'like', '%' . str_replace(' ', '%%', $search) . '%');
                $q->orWhere('sys_customers.phone', 'like', '%' . str_replace(' ', '%%', $search) . '%');
            });
        }

        return $query;
    }

    public function getNewUserAttribute()
    {
        $date = \Date::parse($this->created_at);
        $now = \Date::now();

        return $date->diffInDays($now) < 31 ? true : false;
    }

    public function getNameShortAttribute()
    {
        return str_limit($this->name, 20);
    }

    public function scopeActive($query)
    {
        $query->where('status','=','1');

        return $query;
    }

    public function scopeNotSuperadmin($query)
    {
        $query->where('superadmin','=','0');

        return $query;
    }

    public function scopeDistributor($query)
    {
        $query->where('distributor','=','1');

        return $query;
    }

    public function scopeUserDistributor($query)
    {
        $query->whereHas('sysCustomer', function ($q) {
            $q->where('sys_customers.distributor_id', '=', \Auth::user()->id);
        });

        $query->orWhere(function ($q) {
            $q->where('distributor', '0');
            $q->orWhere('id','=',\Auth::user()->id);
        });

        return $query;
    }

    public function sysCustomer()
    {
        return $this->belongsTo(SysCustomer::class);
    }

    public function hasConfirmed() {
        return $this->email_verified_token === null ? true : false;
    }

    public function confirm($token) {

        if ($this->hasConfirmed()) return false;

        if ($token === $this->email_verified_token) {
            $this->email_verified_token = null;
            $this->email_verified_at = \Date::now();
            $this->save();

            return true;
        }

        return false;
    }

}
