<?php

namespace App;

use App\Mail\MailResetPassword;
use App\Models\PaymentMethod;
use Carbon\Carbon;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Mail;
use Util;

/**
 * App\User
 *
 * @property-read \Illuminate\Notifications\DatabaseNotificationCollection|\Illuminate\Notifications\DatabaseNotification[] $notifications
 * @property-read int|null $notifications_count
 * @method static \Illuminate\Database\Eloquent\Builder|User newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|User newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|User query()
 * @mixin \Eloquent
 * @property int $id
 * @property string $email
 * @property \Illuminate\Support\Carbon|null $email_verified_at
 * @property string $password
 * @property int|null $account_id
 * @property int|null $m_level
 * @property int|null $m_sponsor
 * @property int $admin
 * @property int $wizard
 * @property int $blocked
 * @property int $confirmed
 * @property string|null $confirmation_code
 * @property string|null $confirmation_date
 * @property string|null $confirmation_code_to
 * @property int $confirmation_code_remider
 * @property int $active
 * @property string|null $active_date
 * @property string|null $agreement
 * @property string $lang
 * @property string|null $notes
 * @property string|null $last_login
 * @property string|null $release_account
 * @property string|null $account_payment
 * @property string|null $payment_methods
 * @property int|null $next_m_level
 * @property int $abo_options
 * @property int $test_mode
 * @property string|null $settings
 * @property string|null $remember_token
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property string|null $deleted_at
 * @method static \Illuminate\Database\Eloquent\Builder|User whereAboOptions($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereAccountId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereAccountPayment($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereActive($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereActiveDate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereAdmin($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereAgreement($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereBlocked($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereConfirmationCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereConfirmationCodeRemider($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereConfirmationCodeTo($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereConfirmationDate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereConfirmed($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereDeletedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereEmail($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereEmailVerifiedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereLang($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereLastLogin($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereMLevel($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereMSponsor($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereNextMLevel($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereNotes($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User wherePassword($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User wherePaymentMethods($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereReleaseAccount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereRememberToken($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereSettings($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereTestMode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereWizard($value)
 * @property-read \App\Models\UserAccount|null $account
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\File[] $files
 * @property-read int|null $files_count
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\UserHistory[] $user_histories
 * @property-read int|null $user_histories_count
 * @property-read \App\Models\UserLevel|null $user_level
 * @property-read User|null $user_sponsor
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\UserUpdateEmail[] $user_update_email
 * @property-read int|null $user_update_email_count
 * @property string|null $payment_account
 * @property-read \App\Models\UserLevel|null $next_user_level
 * @method static \Illuminate\Database\Eloquent\Builder|User wherePaymentAccount($value)
 * @property string|null $payment_credit
 * @method static \Illuminate\Database\Eloquent\Builder|User wherePaymentCredit($value)
 */
class User extends Authenticatable
{
    use Notifiable;

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

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

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'settings' => 'array',
        'payment_methods' => 'array'
    ];

    public function account(){
        return $this->belongsTo('App\Models\UserAccount', 'account_id');
    }

    public function user_level(){
        return $this->belongsTo('App\Models\UserLevel', 'm_level');
    }

    public function next_user_level(){
        return $this->belongsTo('App\Models\UserLevel', 'next_m_level');
    }

    public function user_sponsor(){
        return $this->belongsTo('App\User', 'm_sponsor');
    }

    public function files(){
        return $this->hasMany('App\Models\File', 'user_id', '');
    }

    public function user_histories(){
        return $this->hasMany('App\Models\UserHistory', 'user_id', '');
    }

    public function user_update_email()
    {
        return $this->hasMany('App\Models\UserUpdateEmail', 'user_id', 'id');
    }

    public function getMUserSponsor(){
        if($this->user_sponsor && $this->user_sponsor->account){
            return $this->user_sponsor->account->first_name." ".$this->user_sponsor->account->last_name." | ".$this->user_sponsor->email;

        }
    }
    public function getFullName($email=true){
        $ret = "";
        if($this->account){
            $ret = $this->account->first_name." ".$this->account->last_name;

        }
        if($email && $this->id > 1){
            $ret .= " | ".$this->email;
        }
        return $ret;
    }

    /**
     * @return bool
     */
    public function isAdmin()
    {
        if($this->admin >= 1){
            return true;
        }
        return false;
    }

    /**
     * @return bool
     */
    public function isSuperAdmin()
    {
        if($this->admin >= 2){
            return true;
        }
        return false;
    }

    /**
     * @return bool
     */
    public function isSySAdmin()
    {
        if($this->admin >= 3){
            return true;
        }
        return false;
    }

    /**
     * @return bool
     */
    public function isApiUser()
    {
        if($this->admin >= 4){
            return true;
        }
        return false;
    }

    /**
     * @return bool
     */
    public function isTestMode()
    {
        return $this->test_mode ? true : false;
    }


    /**
     * @return bool
     */
    public function showSideNav()
    {
        if($this->active == 1 && $this->blocked == 0 && $this->wizard >= 10){
            return true;
        }
        return false;
    }

    public function isActive(){
        return ($this->active == 1 && $this->blocked == 0) ? true : false;
    }

    public function isActiveAccount(){
        return $this->payment_account ? Carbon::parse($this->payment_account)->gt(Carbon::now()) : false;
    }


    public function isRenewalAccount(){
        if ($this->payment_account) {
            return Carbon::parse($this->payment_account)->modify('-'.(config('main.renewal_days')+1).' days')->lt(Carbon::now());
        }
        return false;
    }

    public function nextRenewalAccount(){
        return $this->payment_account ? Carbon::parse($this->payment_account)->modify('-'.config('main.renewal_days').' days')->format(\Util::formatDateTimeDB()) : false ;
    }

    public function daysActiveAccount(){
        return Carbon::now()->diffInDays(Carbon::parse($this->payment_account), false);
    }

    public function modifyActiveAccount($add = "1 year"){
        return Carbon::parse($this->payment_account)->modify($add)->format(\Util::formatDateTimeDB());
    }

    public function daysHumansActiveAccount(){
        return Carbon::now()->diffForHumans(Carbon::parse($this->payment_account));
    }

    public function daysActiveShop(){
        return Carbon::now()->diffInDays(Carbon::parse($this->payment_shop), false);
    }

    public function modifyActiveShop($add = "1 year"){
        return Carbon::parse($this->payment_shop)->modify($add)->format(\Util::formatDateTimeDB());
    }

    public function daysHumansActiveShop(){
        return Carbon::now()->diffForHumans(Carbon::parse($this->payment_shop));
    }

    /**
     * @return string
     */
    public function getConfirmationDateFormat(){
        if(!$this->attributes['confirmation_date']){ return ""; }
        return Carbon::parse($this->attributes['confirmation_date'])->format(\Util::formatDateTimeDB());
    }

    /**
     * @return string
     */
    public function getActiveDateFormat(){
        if(!$this->attributes['active_date']){ return ""; }
        return Carbon::parse($this->attributes['active_date'])->format(\Util::formatDateTimeDB());
    }

    /**
     * @return string
     */
    public function getAgreementFormat(){
        if(!$this->attributes['agreement']){ return ""; }
        return Carbon::parse($this->attributes['agreement'])->format(\Util::formatDateTimeDB());
    }

    public function getPaymentAccountDateFormat($time = true){
        if(!$this->attributes['payment_account']){ return ""; }
        if(!$time){
            return Carbon::parse($this->attributes['payment_account'])->format(\Util::formatDateDB());
        }
        return Carbon::parse($this->attributes['payment_account'])->format(\Util::formatDateTimeDB());
    }

    public function getPaymentShopDateFormat($time = true){
        if(!$this->attributes['payment_shop']){ return ""; }
        if(!$time){
            return Carbon::parse($this->attributes['payment_shop'])->format(\Util::formatDateDB());
        }
        return Carbon::parse($this->attributes['payment_shop'])->format(\Util::formatDateTimeDB());
    }

    public function getReleaseAccountFormat($time = true){
        if(!$this->attributes['release_account']){ return ""; }
        if(!$time){
            return Carbon::parse($this->attributes['release_account'])->format(\Util::formatDateDB());
        }
        return Carbon::parse($this->attributes['release_account'])->format(\Util::formatDateTimeDB());
    }

    public function getFormattedPaymentCredit()
    {
        return isset($this->attributes['payment_credit']) ? Util::formatNumber($this->attributes['payment_credit']) : "0";
    }

    public function setSetting(array $revisions, bool $save = true){
        if(!$this->settings){
            $this->settings = [];
        }
        $this->settings = array_merge($this->settings, $revisions);
        if ($save) {
            $this->save();
        }
        return $this;
    }

    public function getSetting($key, $default = null){
        return isset($this->settings[$key]) ? $this->settings[$key] : $default;
    }

    public function getPaymentMethodsShort(){
        $ret = "";
        if($this->payment_methods !== null){
            foreach ($this->payment_methods as $payment_method){
                if($find = PaymentMethod::find($payment_method)){
                    $ret .= $find->short." | ";
                }
            }
            $ret = rtrim($ret, " | ");
        }
        return $ret;
    }
    /**
     * @return string
     */
    public function getLandByCountry(){
        if($this->account  && $this->account->country_id){
            $code = $this->account->country->code;
            if($code == "FR"){
                return 'fr';
            }
            if($code == "CH"){
                return 'de';
            }
            if($code == "NL"){
                return 'nl';
            }
            if($code == "DE"){
                return 'de';
            }
        }
        return "de";
    }

    /**
     * Send the password reset notification.
     *
     * @param  string  $token
     * @return void
     */
    public function sendPasswordResetNotification($token)
    {
        Mail::to($this->email)->send(new MailResetPassword($token, $this));
        // $this->notify(new ResetPasswordNotification($token));
    }
}
