<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory; // WAJIB untuk factory
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $primaryKey = 'id_user';

    protected $fillable = [
        'id_user',
        'name',
        'email',
        'password',
        'role',
        'phone',
        'address',
        'gaji_pokok',
        'insentif_3kg',
        'insentif_12kg',
        'uang_makan_harian'
    ];

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

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    // Non auto-increment karena pakai custom ID
    public $incrementing = false;

    protected $keyType = 'string';

    public function getIdAttribute()
    {
        return $this->attributes[$this->primaryKey] ?? null;
    }

    public function setIdAttribute($value)
    {
        $this->attributes[$this->primaryKey] = $value;
    }

    protected static function booted()
    {
        static::creating(function ($user) {

            // Generate ID jika belum ada
            if (!$user->id_user) {

                do {
                    $randomId = 'USR' . mt_rand(1000, 9999);
                } while (self::where('id_user', $randomId)->exists());

                $user->id_user = $randomId;
            }

            // Auto hash password jika belum di-hash
            if (!Hash::needsRehash($user->password)) {
                return;
            }

            $user->password = Hash::make($user->password);
        });
    }

    // Relasi ke tabel customers (satu user bisa punya satu data pelanggan)
    public function pelanggan()
    {
        return $this->hasOne(Pelanggan::class, 'customers_id', 'id_user');
    }

    // Relasi ke notifikasi milik user ini
    public function notifications()
    {
        return $this->hasMany(Notification::class, 'id_user', 'id_user');
    }

    // Relasi ke slip gaji milik user ini
    public function slipsGaji()
    {
        return $this->hasMany(SlipGaji::class, 'id_user', 'id_user');
    }
}