<?php

namespace App\Models;

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

class LibraryBookCopy extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'library_book_id',
        'copy_number',
        'barcode',
        'status',
        'condition',
        'acquisition_date',
        'price',
        'remarks',
    ];

    protected $casts = [
        'acquisition_date' => 'date',
        'price' => 'decimal:2',
    ];

    // Relationships
    public function libraryBook()
    {
        return $this->belongsTo(LibraryBook::class, 'library_book_id');
    }

    public function currentIssue()
    {
        return $this->hasOne(BookIssue::class, 'library_book_copy_id')
                    ->where('status', 'issued')
                    ->latest();
    }

    // Scopes
    public function scopeAvailable($query)
    {
        return $query->where('status', 'available');
    }

    public function scopeIssued($query)
    {
        return $query->where('status', 'issued');
    }

    public function scopeForBook($query, $bookId)
    {
        return $query->where('library_book_id', $bookId);
    }

    public function scopeByCondition($query, $condition)
    {
        return $query->where('condition', $condition);
    }

    // Accessors
    public function getIsAvailableAttribute()
    {
        return $this->status === 'available';
    }

    public function getIsIssuedAttribute()
    {
        return $this->status === 'issued';
    }
}
