<?php

namespace App\Model;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Str;

class User extends Authenticatable
{

    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'birthday'
    ];

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

    protected $casts = [
        'facebook_data' => 'array',
        'google_data' => 'array',
    ];

    public static function boot()
    {
        parent::boot();

        static::saving(function ($model) {
            $model->slug = Str::slug($model->getName());

            $model->search = Str::slug(implode(' ', [
                $model->slug,
                $model->email,
            ]), ' ');
        });
    }

    public function contacts()
    {
        return $this->hasMany('App\Model\Contact');
    }

    public function orders()
    {
        return $this->hasMany('App\Model\Order')->orderByDesc('id');
    }

    public function vendorOrders()
    {
        return $this->hasMany('App\Model\Order\OrderVendor', 'vendor_id')
            ->with('order');
//            ->with('products') // cannot be eager loaded because it has 2 cols relationship.
//            ->orderByDesc('id');
    }

    public function products()
    {
        return $this->belongsToMany('App\Model\Product')->with('photo');
    }

    public function setting()
    {
        return $this->hasOne('App\Model\User\UserSetting', 'user_id')->withDefault();
    }

    public function billingContact()
    {
        // do not pick the same contact.

        return $this->hasOne('App\Model\Contact')
            ->orderByDesc('id')
            ->where('id', '!=', $this->deliveryContact->id ?? -1);
    }

    public function deliveryContact()
    {
        return $this->hasOne('App\Model\Contact')
            ->orderBy('id');
    }

    /**
     * Allow setting is_admin flag only if user is actually admin.
     * @param type $value
     */
    public function setIsAdminAttribute($value)
    {
        if (Auth::user() && Auth::user()->isAdmin()) {
            $this->attributes['is_admin'] = $value;
        }
    }

    public function setDiscountAttribute($value)
    {
        if (Auth::check() && Auth::user()->isAdmin()) {
            $this->attributes['discount'] = $value;
        }
    }

    public function isAdmin()
    {
        return $this->is_admin;
    }

    public function isSuperAdmin()
    {
        return $this->is_admin;
    }


    public function isActive()
    {
        return $this->is_active;
    }

    public function getName()
    {
        return $this->name;
    }



}
