<?php

namespace App\Models;

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

class PurchaseReturn extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'voucher_no', 'purchase_id', 'party_id', 'return_date', 'reason',
        'subtotal', 'deduction', 'grand_total', 'status', 'remarks', 'created_by',
    ];

    protected $casts = [
        'return_date' => 'date',
        'subtotal'    => 'decimal:2',
        'deduction'   => 'decimal:2',
        'grand_total' => 'decimal:2',
    ];

    protected static function booted()
    {
        static::creating(function ($model) {
            if (empty($model->voucher_no)) {
                $model->voucher_no = static::generateVoucherNo();
            }
            $model->grand_total = ($model->subtotal ?? 0) - ($model->deduction ?? 0);
        });
    }

    public static function generateVoucherNo(): string
    {
        $prefix = 'PRR-';
        $year = date('Y');
        $latest = static::where('voucher_no', 'like', "{$prefix}{$year}-%")
            ->orderBy('id', 'desc')->first();
        $num = $latest ? ((int) substr($latest->voucher_no, -4) + 1) : 1;
        return $prefix . $year . '-' . str_pad($num, 4, '0', STR_PAD_LEFT);
    }

    public function party() { return $this->belongsTo(Party::class); }
    public function purchase() { return $this->belongsTo(Purchase::class); }
    public function creator() { return $this->belongsTo(User::class, 'created_by'); }

    public function scopeToday($q) { return $q->whereDate('return_date', today()); }
    public function scopeThisMonth($q) { return $q->whereMonth('return_date', date('m'))->whereYear('return_date', date('Y')); }
    public function scopePosted($q) { return $q->where('status', 'posted'); }
}
