<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\User;
use App\Models\Buku;

class Peminjaman extends Model
{
    use HasFactory;

    protected $table = 'peminjaman'; 
    protected $primaryKey = 'id_peminjaman'; 

    protected $fillable = [
        'id_user',
        'id_anggota',
        'id_buku',
        'tanggal_pinjam',
        'tanggal_kembali',
        'tanggal_dikembalikan',
        'denda',
        'status_peminjaman',
    ];

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

    public function anggota()
    {
        return $this->belongsTo(Anggota::class, 'id_anggota');
    }

    public function buku()
    {
        return $this->belongsTo(Buku::class, 'id_buku');
    }

    /**
     * Hitung denda dinamis (Accessor: $peminjaman->total_denda)
     */
    public function getTotalDendaAttribute()
    {
        $tarif = 1000; // Tarif 1.000 per hari keterlambatan
        $denda = 0;

        if (!$this->tanggal_kembali) return 0;

        $tgl_kembali = \Carbon\Carbon::parse($this->tanggal_kembali)->startOfDay();

        if ($this->status_peminjaman === 'Dikembalikan' && $this->tanggal_dikembalikan) {
            $tgl_dikembalikan = \Carbon\Carbon::parse($this->tanggal_dikembalikan)->startOfDay();
            if ($tgl_dikembalikan->greaterThan($tgl_kembali)) {
                $selisih = $tgl_kembali->diffInDays($tgl_dikembalikan);
                $denda = $selisih * $tarif;
            }
        } elseif ($this->status_peminjaman === 'Dipinjam') {
            $hari_ini = \Carbon\Carbon::now()->startOfDay();
            if ($hari_ini->greaterThan($tgl_kembali)) {
                $selisih = $tgl_kembali->diffInDays($hari_ini);
                $denda = $selisih * $tarif;
            }
        }

        // Return denda kalkulasi atau denda yg sudah tersimpan (jika manual admin entry)
        return max($denda, $this->attributes['denda'] ?? 0);
    }
}