<?php

namespace App\Models;

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

class StockIssue extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'school_id',
        'item_id',
        'store_id',
        'quantity',
        'issue_date',
        'issued_to_type',
        'issued_to_id',
        'issued_to_name',
        'purpose',
        'return_expected',
        'expected_return_date',
        'actual_return_date',
        'returned_quantity',
        'issued_by',
        'remarks',
    ];

    protected $casts = [
        'quantity' => 'integer',
        'returned_quantity' => 'integer',
        'issue_date' => 'date',
        'expected_return_date' => 'date',
        'actual_return_date' => 'date',
        'return_expected' => 'boolean',
    ];

    // Relationships
    public function school()
    {
        return $this->belongsTo(School::class);
    }

    public function item()
    {
        return $this->belongsTo(InventoryItem::class, 'item_id');
    }

    public function store()
    {
        return $this->belongsTo(ItemStore::class, 'store_id');
    }

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

    // Scopes
    public function scopeForItem($query, $itemId)
    {
        return $query->where('item_id', $itemId);
    }

    public function scopeForStore($query, $storeId)
    {
        return $query->where('store_id', $storeId);
    }

    public function scopePendingReturn($query)
    {
        return $query->where('return_expected', true)
                     ->whereNull('actual_return_date');
    }

    public function scopeOverdueReturn($query)
    {
        return $query->where('return_expected', true)
                     ->whereNull('actual_return_date')
                     ->where('expected_return_date', '<', now());
    }

    // Accessors
    public function getIsPendingReturnAttribute()
    {
        return $this->return_expected && !$this->actual_return_date;
    }

    public function getIsOverdueAttribute()
    {
        return $this->return_expected
               && !$this->actual_return_date
               && $this->expected_return_date < now();
    }
}
