<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class PurchaseOrder extends Model
{
    use HasFactory, LogsActivity;

    protected $fillable = [
        'code',
        'vendor_id',
        'warehouse_id',
        'user_id',
        'status',
        'expected_delivery_date',
        'total_amount',
        'tax_amount',
        'grand_total',
        'remark',
        'invoice_number',
        'invoice_date',
        'invoice_amount',
    ];

    protected $casts = [
        'expected_delivery_date' => 'date:Y-m-d',
        'invoice_date' => 'date:Y-m-d',
        'total_amount' => 'decimal:2',
        'tax_amount' => 'decimal:2',
        'grand_total' => 'decimal:2',
        'invoice_amount' => 'decimal:2',
    ];

    protected $appends = [
        'poNumber',
        'supplierId',
        'supplierName',
        'expectedDate',
        'totalAmount',
        'taxAmount', // Add this
        'grandTotal', // Add this
        'createdBy',
        'warehouse_name',
        'createdAt',
        'invoiceNumber',
        'invoiceDate',
        'invoiceAmount',
    ];

    public function getCreatedAtAttribute()
    {
        return $this->attributes['created_at'];
    }

    public function getPoNumberAttribute(): string
    {
        return $this->code;
    }

    public function getSupplierIdAttribute(): string
    {
        return (string) $this->vendor_id;
    }

    public function getSupplierNameAttribute(): string
    {
        return $this->vendor ? $this->vendor->name : '';
    }

    public function getExpectedDateAttribute(): ?string
    {
        return $this->attributes['expected_delivery_date'] ?? null;
    }

    public function getTotalAmountAttribute(): float
    {
        return (float) ($this->attributes['total_amount'] ?? 0);
    }

    public function getTaxAmountAttribute(): float
    {
        return (float) ($this->attributes['tax_amount'] ?? 0);
    }

    public function getGrandTotalAttribute(): float
    {
        return (float) ($this->attributes['grand_total'] ?? 0);
    }

    public function getCreatedByAttribute(): string
    {
        return $this->user ? $this->user->name : '系統';
    }

    public function getWarehouseNameAttribute(): string
    {
        return $this->warehouse ? $this->warehouse->name : '';
    }

    public function getInvoiceNumberAttribute(): ?string
    {
        return $this->attributes['invoice_number'] ?? null;
    }

    public function getInvoiceDateAttribute(): ?string
    {
        return $this->attributes['invoice_date'] ?? null;
    }

    public function getInvoiceAmountAttribute(): ?float
    {
        return isset($this->attributes['invoice_amount']) ? (float) $this->attributes['invoice_amount'] : null;
    }

    public function vendor(): BelongsTo
    {
        return $this->belongsTo(Vendor::class);
    }

    public function warehouse(): BelongsTo
    {
        return $this->belongsTo(Warehouse::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

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

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logAll()
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }

    public function tapActivity(\Spatie\Activitylog\Contracts\Activity $activity, string $eventName)
    {
        $properties = $activity->properties;
        $attributes = $properties['attributes'] ?? [];
        $snapshot = $properties['snapshot'] ?? [];

        // Snapshot key names
        $snapshot['po_number'] = $this->code;
        $snapshot['vendor_name'] = $this->vendor ? $this->vendor->name : null;
        $snapshot['warehouse_name'] = $this->warehouse ? $this->warehouse->name : null;
        $snapshot['user_name'] = $this->user ? $this->user->name : null;

        $properties['attributes'] = $attributes;
        $properties['snapshot'] = $snapshot;
        $activity->properties = $properties;
    }
}
