<?php

namespace App\Models;

use App\Enums\CommissionType;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class OrderItem extends Model
{
    protected $fillable = [
        'order_id',
        'product_id',
        'product_name',
        'product_image',
        'buy_price',
        'sell_price',
        'commission_type',
        'commission_value',
        'quantity',
        'subtotal',
        'notes',
    ];

    protected function casts(): array
    {
        return [
            'buy_price'        => 'decimal:2',
            'sell_price'       => 'decimal:2',
            'commission_type'  => CommissionType::class,
            'commission_value' => 'decimal:2',
            'subtotal'         => 'decimal:2',
            'quantity'         => 'integer',
        ];
    }

    // ── Relationships ─────────────────────────────────────────────────────

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

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

    // ── Calculations ──────────────────────────────────────────────────────

    /**
     * Nominal komisi per unit berdasarkan snapshot.
     */
    public function commissionPerUnit(): float
    {
        if (! $this->commission_type) {
            return 0;
        }

        return match ($this->commission_type) {
            CommissionType::Percent => round($this->sell_price * $this->commission_value / 100, 2),
            CommissionType::Fixed   => (float) $this->commission_value,
        };
    }

    /**
     * Total komisi untuk item ini (per unit × quantity).
     */
    public function totalCommission(): float
    {
        return $this->commissionPerUnit() * $this->quantity;
    }

    /**
     * Margin Admin untuk item ini:
     * subtotal - (buy_price × qty) - total_commission
     */
    public function totalMargin(): float
    {
        return $this->subtotal
            - ($this->buy_price * $this->quantity)
            - $this->totalCommission();
    }
}
