<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

class Koleksi extends Model
{
    use HasFactory;

    protected $table = 'koleksis';
    protected $primaryKey = 'biblio_id';
    public $incrementing = true;
    protected $keyType = 'int';
    public $timestamps = true;

    protected $fillable = [
        'title',
        'sor',
        'edition',
        'isbn_issn',
        'publisher_id',
        'publish_year',
        'tahun_terbit',
        'collation',
        'series_title',
        'call_number',
        'language_id',
        'source',
        'publish_place_id',
        'classification',
        'notes',
        'image',
        'file_att',
        'opac_hide',
        'promoted',
        'labels',
        'frequency_id',
        'spec_detail_info',
        'content_type_id',
        'media_type_id',
        'carrier_type_id',
        'input_date',
        'last_update',
        'uid',
        'kode_eksemplar',
        'qr_code',     
        'barcode',       
        'created_at',
        'updated_at',
    ];

    
    public function getRouteKeyName()
    {
        return 'kode_eksemplar';
    }

    
    public function borrowTransactions()
    {
        return $this->hasMany(BorrowTransaction::class, 'koleksi_id', 'biblio_id');
    }

   
    public function scopeBorrowed($query)
    {
        return $query->whereHas('borrowTransactions', function ($q) {
            $q->whereIn('status', ['dipinjam', 'disetujui', 'pengembalian_menunggu']);
        });
    }

    
    public function scopeAvailable($query)
    {
        return $query->whereDoesntHave('borrowTransactions', function ($q) {
            $q->whereIn('status', ['dipinjam', 'disetujui', 'pengembalian_menunggu']);
        });
    }

   
    public function isBorrowed()
    {
        return $this->borrowTransactions()
            ->whereIn('status', ['dipinjam', 'disetujui', 'pengembalian_menunggu'])
            ->exists();
    }

   
    public function getStatusAttribute()
    {
        return $this->isBorrowed() ? 'Dipinjam' : 'Tersedia';
    }

    
    public function scopeWithStatus($query)
    {
        return $query->with(['borrowTransactions' => function ($q) {
            $q->latest();
        }]);
    }

    
    public function getBarcodeUrlAttribute()
    {
        if ($this->barcode && Storage::disk('public')->exists($this->barcode)) {
            return asset('storage/' . $this->barcode);
        }
        return null;
    }

   
    public function hasBarcode()
    {
        return $this->barcode && Storage::disk('public')->exists($this->barcode);
    }
}

