<?php

namespace App\Models;

use App\Traits\Multitenantable;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphOne;

class Purchase extends Model
{
    use Multitenantable;

    protected $primaryKey = 'uuid';
    public $incrementing = false;
    protected $keyType = 'string';

    protected $fillable = [
        'uuid', 
        'tenant_id', 
        'purchase_number', 
        'outlet_id', 
        'outlet_name_snapshot',
        'supplier_id', 
        'supplier_name_snapshot', 
        'supplier_email_snapshot',
        'supplier_phone_number_snapshot', 
        'user_id', 'admin_name_snapshot',
        'purchase_status', 
        'total_purchase', 
        'discount', 
        'tax', 
        'payment_status',
        'total_amount', 
        'amount_paid', 
        'change_amount', 
        'under_payment_amount',
        'debt_amount', 
        'payment_proof_url', 
        'notes', 
    ];

    protected $casts = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function items() {
        return $this->hasMany(PurchaseItem::class, 'purchase_id', 'uuid');
    }

    public function supplier() {
        return $this->belongsTo(Supplier::class, 'supplier_id', 'uuid');
    }

    public function transaction(): MorphOne {
        return $this->morphOne(Transaction::class, 'reference', 'reference_type', 'reference_id', 'uuid');
    }
}
