<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class TransaksiPembayaran extends Model
{
    protected $table = 'transaksi_pembayaran';

    protected $fillable = [
        'kode_transaksi',
        'siswa_id',
        'user_id',
        'tahun_ajaran_id',
        'nama_kelas_snapshot',
        'tahun_ajaran_snapshot',
        'tarif_snapshot',
        'tanggal_bayar',
        'total_bayar',
        'metode_pembayaran',
        'keterangan',
        'bukti_bayar',
    ];

    protected function casts(): array
    {
        return [
            'tanggal_bayar' => 'date',
            'total_bayar' => 'decimal:2',
        ];
    }

    public function siswa(): BelongsTo
    {
        return $this->belongsTo(Siswa::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function tahunAjaran(): BelongsTo
    {
        return $this->belongsTo(TahunAjaran::class);
    }

    public function detailPembayaran(): HasMany
    {
        return $this->hasMany(DetailPembayaran::class);
    }

    /**
     * Generate kode transaksi unik
     * Format: TRX-YYYYMMDD-XXXX
     */
    public static function generateKodeTransaksi(): string
    {
        $today = now()->format('Ymd');
        $prefix = "TRX-{$today}-";

        $lastTrx = static::where('kode_transaksi', 'like', $prefix . '%')
            ->orderBy('kode_transaksi', 'desc')
            ->first();

        if ($lastTrx) {
            $lastNumber = (int) substr($lastTrx->kode_transaksi, -4);
            $newNumber = $lastNumber + 1;
        } else {
            $newNumber = 1;
        }

        return $prefix . str_pad($newNumber, 4, '0', STR_PAD_LEFT);
    }
}
