<?php

namespace App\Models;

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

class Order extends Model
{
    use Multitenantable;

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

    protected $fillable = [
        'uuid', 
        'tenant_id', 
        'order_number', 
        'outlet_id', 
        'outlet_name_snapshot',
        'outlet_phone_number_snapshot',
        'outlet_address_snapshot',
        'customer_id', 
        'customer_name_snapshot', 
        'customer_email_snapshot',
        'customer_phone_number_snapshot', 
        'customer_address_snapshot',
        'user_id', 
        'admin_name_snapshot',
        'source', 
        'already_read', 
        'order_status', 
        'is_cancellation',
        'cancellation_accepted', 
        'approval_process', 
        'canceled_by',
        'delivery_type', 
        'delivery_preference', 
        'delivery_fee_type',
        'delivery_fee',
        'total_delivery_fee', 
        'total_order',
        'discount', 
        'tax', 
        'total_amount', 
        'amount_paid', 
        'change_amount',
        'notes', 
        'payment_proof_url', 
        'payment_method', 
        'has_been_assessed'
    ];

    protected $casts = [
        'outlet_address_snapshot' => 'array',
        'customer_address_snapshot' => 'array',
        'already_read' => 'boolean',
        'is_cancellation' => 'boolean',
        'cancellation_accepted' => 'boolean',
        'has_been_assessed' => 'boolean'
    ];

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

    public function items(): HasMany 
    { 
        return $this->hasMany(OrderItem::class, 'order_id', 'uuid'); 
    }
    
    public function customer(): BelongsTo 
    { 
        return $this->belongsTo(Customer::class, 'customer_id', 'uuid'); 
    }

    /**
     * Relasi ke tabel Transactions sebagai polimorfik
     */
    public function transaction(): MorphOne
    {
        return $this->morphOne(Transaction::class, 'reference', 'reference_type', 'reference_id', 'uuid');
    }

    public function getPaymentProofUrlAttribute($value)
    {
        if (!$value) return null;

        return asset('storage/' . $value);
    }
}