<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class DetailPenggajian extends Model
{
    use HasFactory;

    protected $table = 'detail_penggajians';
    protected $primaryKey = 'id_detail';

    protected $fillable = [
        'id_penggajian',
        'id_penugasan',
        'tanggal_selesai',
        'lokasi',
        'ongkos_penugasan',
        'jumlah_tim',
        'bagian_ongkos',
        'rincian_pekerjaan',
    ];

    protected $casts = [
        'ongkos_penugasan' => 'decimal:2',
        'jumlah_tim' => 'integer',
        'bagian_ongkos' => 'decimal:2',
        'tanggal_selesai' => 'date',
    ];

    /**
     * Relationship with Penggajian
     */
    public function penggajian()
    {
        return $this->belongsTo(Penggajian::class, 'id_penggajian', 'id_penggajian');
    }

    /**
     * Relationship with Penugasan
     */
    public function penugasan()
    {
        return $this->belongsTo(Penugasan::class, 'id_penugasan', 'id_penugasan');
    }

    /**
     * Boot method to update parent totals
     */
    protected static function boot()
    {
        parent::boot();

        static::saved(function ($detail) {
            $detail->updatePenggajianTotals();
        });

        static::deleted(function ($detail) {
            $detail->updatePenggajianTotals();
        });
    }

    public function updatePenggajianTotals()
    {
        $penggajian = $this->penggajian;
        if ($penggajian) {
            $totalOngkos = self::where('id_penggajian', $this->id_penggajian)->sum('bagian_ongkos');
            $biayaMakan  = $penggajian->biaya_makan ?? 0;
            $potongan    = $penggajian->total_potongan ?? $penggajian->total_kasbon ?? 0;
            $penggajian->update([
                'total_ongkos_pekerjaan' => $totalOngkos,
                'gaji_bersih'            => ($totalOngkos - $biayaMakan) - $potongan,
            ]);
        }
    }
}