<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class BiayaMaster extends Model
{
    protected $table = 'biaya_master';

    protected $fillable = [
        'kampus_id',
        'prodi_id',
        'kode_biaya',
        'komponen',
        'semester',
        'total',
    ];

    protected $casts = [
        'total' => 'integer',
        'semester' => 'integer'
    ];

    public function kampus()
    {
        return $this->belongsTo(Kampus::class);
    }

    public function prodi()
    {
        return $this->belongsTo(Prodi::class);
    }

    /**
     * Mendapatkan jenis dari kode_biaya
     */
    public function getJenisAttribute()
    {
        $kode = $this->kode_biaya;

        if (str_starts_with($kode, 'SPB')) return 'SPB';
        if (str_starts_with($kode, 'SPP')) return 'SPP';
        if (str_starts_with($kode, 'UKT')) return 'UKT';
        if (str_starts_with($kode, 'BL-')) return 'BL';
        if (str_starts_with($kode, 'SP-')) return 'SP';
        if (str_starts_with($kode, 'RUTIN-')) return 'RUTIN';
        if (str_starts_with($kode, 'BT-')) return 'BT';

        return 'LAINNYA';
    }

    /**
     * Mendapatkan nomor urut/angsuran dari kode_biaya
     */
    public function getNomorAttribute()
    {
        $kode = $this->kode_biaya;

        if (str_starts_with($kode, 'SPB')) {
            return (int) preg_replace('/[^0-9]/', '', $kode);
        }

        if (str_starts_with($kode, 'SPP') || str_starts_with($kode, 'UKT')) {
            preg_match('/^[A-Z]+(\d+)_(\d+)$/', $kode, $matches);
            return (int) ($matches[1] ?? 0);
        }

        return 0;
    }
}
