<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Carbon;
use Laravel\Sanctum\HasApiTokens;
use PhpParser\Node\Expr\Assign;

class User extends Authenticatable
{

    use HasFactory, Notifiable, HasApiTokens;
    protected $table = 'users';

    protected $fillable = [
        'role_id',
        'name',
        'email',
        'password',
        'refreshed',
        'deleted',
        'status',
        'created_by',
        'hex'
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'role_id' => 'integer',
            'id' => 'integer',
            'name' => 'string',
            'email' => 'string',
            'refreshed' => 'integer',
            'deleted' => 'integer',
            'status' => 'integer',
            'created_at' => 'datetime',
            'updated_at' => 'datetime',

        ];
    }

    protected function createdAtWib(): Attribute
    {
        return Attribute::make(
            get: fn($value, $attributes) => Carbon::parse($attributes['created_at'])
                ->timezone('Asia/Jakarta')
                ->format('d/m/Y H:i:s'),
        );
    }

    protected function createdAtDate(): Attribute
    {
        return Attribute::make(
            get: fn($value, $attributes) => Carbon::parse($attributes['created_at'])
                ->timezone('Asia/Jakarta')
                ->format('d/m/Y'),
        );
    }

    protected function createdAtTime(): Attribute
    {
        return Attribute::make(
            get: fn($value, $attributes) => Carbon::parse($attributes['created_at'])
                ->timezone('Asia/Jakarta')
                ->format('H:i:s'),
        );
    }

    public function role(): BelongsTo
    {
        return $this->belongsTo(Role::class);
    }

    /**
     * Get the subordinates assigned to this user.
     * (e.g., FAs assigned to an Agro)
     */
    public function assigns(): BelongsToMany
    {
        return $this->belongsToMany(
            User::class,
            'user_assigns',
            'user_id',
            'assign_user_id'
        );
    }

    /**
     * Get the managers this user is assigned to.
     * (e.g., Agros a FA is assigned to)
     */
    public function managers(): BelongsToMany
    {
        return $this->belongsToMany(
            User::class,
            'user_assigns',
            'assign_user_id',
            'user_id'
        );
    }
}
