<?php

namespace Modules\User\Models;

use App\Services\Upload\FileService;
use Illuminate\Support\Facades\Auth;
use DB;
use Modules\Country\Models\Country;
use Modules\Sector\Models\Sector;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Modules\ContactList\Enums\ContactStatusEnum;
use Modules\Deal\Models\Deal;
use Modules\Target\Models\Target;
use Modules\User\Enums\UserRoleEnum;
use Modules\User\Services\ModuleService;
use Modules\Deal\Enums\DealStatusEnum;
use Modules\User\Services\UserService;


/**
 * @property mixed role
 * @property mixed Modules
 */
class User extends Authenticatable
{
    use Notifiable;
    use SoftDeletes;

    private UserService $userService;
    private ModuleService $moduleService;
    public function __construct(array $attributes = [] )
    {
        parent::__construct($attributes);
        $this->moduleService = app(ModuleService::class);
        $this->userService = app(UserService::class);
    }
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'phone',
        'photo',
        'lock',
        'password',
        'role',
        'phone_country_id',
        'manager_id',
        'verified'
    ];

    /**
     * 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',
    ];

    public function address()
    {
        return $this->belongsTo(Address::class)->withTrashed();
    }

    /**
     * Get the Modules of this user
     * @return BelongsToMany
     */
    public function modules(): BelongsToMany
    {
        return $this->belongsToMany(Module::class, 'user_modules');
    }

    public function manager()
    {
        return $this->belongsTo(self::class)->withTrashed();
    }

    public function phoneCountry()
    {
        return $this->belongsTo(Country::class)->withTrashed();
    }

    /**
     * Check if the user can access a module
     * @param string, module name
     * @return bool
     */
    public function hasModule($module): bool
    {
        if ($this->modules->contains('path', $module)) {
            return true;
        }
        return false;
    }

    /**
     * Check if the user can access a module
     * @param string, module name
     * @return bool
     */
    public function canAccess($status,$path)
    {
        if(Auth::user()->role == UserRoleEnum::Head_Department->value)
        {
            return true;
        }
        return $this->moduleService->checkModuleAccess([
            'status' => $status,
            'path' => $path
        ],Auth::id());
    }

    public function disabledColumn($column,$module)
    {
        return !$this->userService->disableColumn([
            'column' => $column,
            'module' => $module,
            'user_id' => $this->id,
        ]);
    }

    public function sectors()
    {
        return $this->hasMany(UserSector::class);
    }

    public function setPasswordAttribute($value)
    {
        if($value)
        {
            $this->attributes['password'] = bcrypt($value);
        }
        else
        {
            $this->attributes['password'] = $this->password;
        }
    }
    public function setPhotoAttribute($value)
    {
        if($value)
        {
            if(is_string($value))
            {
                $this->attributes['photo'] = $value;
            }
            else
            {
                $photo = FileService::uploadImage($value);
                $this->attributes['photo'] = $photo;
            }
        }
        else
        {
            $this->attributes['photo'] = request()->method() == 'post'  ? 'logo.png' : $this->photo;
        }
    }



    public function targetEmp($year, $month)
    {
        if($month == 'Q1')
        {
            $month = [1,2,3];
        }
        elseif($month == 'Q2')
        {
            $month = [4,5,6];
        }
        elseif($month == 'S1')
        {
            $month = [1,2,3,4,5,6];
        }
        elseif($month == 'Q3')
        {
            $month = [7,8,9];
        }
        elseif($month == 'YTD')
        {
            $month = [1,2,3,4,5,6,7,8,9];
        }
        elseif($month == 'Q4')
        {
            $month = [10,11,12];
        }
        elseif($month == 'S2')
        {
            $month = [7,8,9,10,11,12];
        }
        elseif($month == 'FY')
        {
            $month = [1,2,3,4,5,6,7,8,9,10,11,12];
        }
        $builder = Target::query();
        $builder->whereHas('product', function ($query) {
            $query->whereNull('deleted_at');
        });
        if(is_array($month))
        {
            $builder->whereIn('month',$month);
        }
        else
        {
            $builder->where('month',$month);
        }
        $target = $builder->where('year',$year)->where('employee_id',$this->id)->sum('target');

        return $target;
    }

    public function totalSales($year)
    {
        return Target::whereHas('product', function ($query) {
            $query->whereNull('deleted_at');
        })->where('year',$year)->where('employee_id',$this->id)->sum('target');
    }
    public function salesEmp($year, $month)
    {
        if($month == 'Q1')
        {
            $month = [1,2,3];
        }
        elseif($month == 'Q2')
        {
            $month = [4,5,6];
        }
        elseif($month == 'S1')
        {
            $month = [1,2,3,4,5,6];
        }
        elseif($month == 'Q3')
        {
            $month = [7,8,9];
        }
        elseif($month == 'YTD')
        {
            $month = [1,2,3,4,5,6,7,8,9];
        }
        elseif($month == 'Q4')
        {
            $month = [10,11,12];
        }
        elseif($month == 'S2')
        {
            $month = [7,8,9,10,11,12];
        }
        elseif($month == 'FY')
        {
            $month = [1,2,3,4,5,6,7,8,9,10,11,12];
        }
        $builder = Deal::query();
        $builder->where('status',DealStatusEnum::Payment_Received->value);
        // $builder->whereHas('contactList',function ($query){
        //     $query->where('status',ContactStatusEnum::PROJECT_WON->value);
        // });
        if(is_array($month))
        {
            $builder->whereIn(DB::raw('MONTH(start_date)'), $month);
        }
        else
        {
            $builder->whereMonth('start_date',$month);
        }
        $sales = $builder->whereYear('start_date',$year)->where('employee_id',$this->id)->sum('amount');

        return $sales;
    }
}
