<?php

namespace App\Models;

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

class ProductReturn extends Model
{
    use HasFactory;

    protected $table = 'returns'; // Keep the original table name

    protected $fillable = [
        'return_no',
        'sale_id',
        'customer_id',
        'return_date',
        'total_amount',
        'refund_amount',
        'refund_method',
        'refund_status',
        'reason',
        'approved_by',
        'processed_by',
    ];

    protected $casts = [
        'return_date' => 'date',
        'total_amount' => 'decimal:2',
        'refund_amount' => 'decimal:2',
    ];

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

    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }

    public function items()
    {
        return $this->hasMany(ReturnItem::class);
    }

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

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

    // Generate return number
    public static function generateReturnNo()
    {
        $date = now()->format('Ymd');
        $lastReturn = self::where('return_no', 'like', "RET-{$date}-%")->orderBy('id', 'desc')->first();
        
        if ($lastReturn) {
            $lastNumber = intval(substr($lastReturn->return_no, -4));
            $newNumber = str_pad($lastNumber + 1, 4, '0', STR_PAD_LEFT);
        } else {
            $newNumber = '0001';
        }
        
        return "RET-{$date}-{$newNumber}";
    }
}