<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Models\Company;
use App\Models\Product;

class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'company_name',
        'phone',
        'company_id',
        'role',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var list<string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    // กำหนดชื่อ timestamp columns
    const CREATED_AT = 'DtmIns';
    const UPDATED_AT = 'DtmUpd';

    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    /**
     * Get the products created by this user.
     */
    public function products()
    {
        return $this->hasMany(Product::class);
    }

    /**
     * Get all products from users in the same company.
     */
    public function getCompanyProductsAttribute()
    {
        if (!$this->company_id) {
            return collect();
        }

        return Product::whereHas('user', function($query) {
            $query->where('company_id', $this->company_id);
        })->with('user')->get();
    }

    /**
     * Check if user is in a company.
     */
    public function isInCompany()
    {
        return !is_null($this->company_id);
    }
}
