<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class SaleItem extends Model
{
    protected $fillable = [
        'sale_id',
        'product_id',
        'qty', // Database column is 'qty', not 'quantity'
        'price',
        'price_ex_tax',
        'tax_rate',
        'tax_amount',
        'tax',
        'total',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'qty' => 'integer', // Changed from 'quantity' to 'qty'
        'price' => 'decimal:2',
        'price_ex_tax' => 'decimal:2',
        'tax_rate' => 'decimal:2',
        'tax_amount' => 'decimal:2',
        'tax' => 'decimal:2',
        'total' => 'decimal:2',
    ];

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

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

    /**
     * Accessor for 'quantity' (for backward compatibility)
     */
    public function getQuantityAttribute()
    {
        return $this->qty;
    }

    /**
     * Mutator for 'quantity' (for backward compatibility)
     */
    public function setQuantityAttribute($value)
    {
        $this->attributes['qty'] = $value;
    }

    /**
     * Calculate totals for this item
     */
    public function calculateTotals(): array
    {
        $itemTotal = $this->qty * $this->price;
        $taxAmount = $itemTotal * ($this->tax_rate / 100);
        $total = $itemTotal + $taxAmount;

        return [
            'item_total' => $itemTotal,
            'tax_amount' => $taxAmount,
            'total' => $total,
        ];
    }

    /**
     * Get the product name (for receipt display)
     */
    public function getProductNameAttribute(): string
    {
        return $this->product->name ?? 'Unknown Product';
    }

    /**
     * Get the formatted price
     */
    public function getFormattedPriceAttribute(): string
    {
        return 'KES ' . number_format($this->price, 2);
    }

    /**
     * Get the formatted total
     */
    public function getFormattedTotalAttribute(): string
    {
        return 'KES ' . number_format($this->total, 2);
    }
}