<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class SlipGaji extends Model
{
    protected $table = 'slips_gaji';
    protected $primaryKey = 'id_slip_gaji';
    public $incrementing = false;
    protected $keyType = 'string';

    protected $fillable = [
        'id_slip_gaji',
        'id_user',
        'periode',
        'tanggal_bayar',
        'total_qty_3kg',
        'total_qty_12kg',
        'total_hari_kerja',
        'gaji_pokok_nominal',
        'insentif_nominal',
        'uang_makan_nominal',
        'potongan',
        'total_diterima',
        'status',
        'bukti_transfer',
        'catatan'
    ];

    /**
     * Relasi ke User (Karyawan/Kurir)
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'id_user', 'id_user');
    }

    protected static function booted()
    {
        static::creating(function ($slip) {
            if (!$slip->id_slip_gaji) {
                // Konversi periode e.g. "2026-07" menjadi "202607"
                $cleanPeriode = str_replace('-', '', $slip->periode);
                do {
                    $randomSuffix = str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
                    $newId = "SG-{$cleanPeriode}-{$randomSuffix}";
                } while (self::where('id_slip_gaji', $newId)->exists());
                $slip->id_slip_gaji = $newId;
            }
        });
    }
}
