<?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',
        'quantity',
        'unit_price',
        'cost_price',
        'discount',
        'discount_percent',
        'final_price',
        'total',
        'warranty_date',
        'repair_notes',
    ];

    protected $casts = [
        'quantity' => 'integer',
        'unit_price' => 'decimal:2',
        'cost_price' => 'decimal:2',
        'discount' => 'decimal:2',
        'discount_percent' => 'decimal:2',
        'final_price' => 'decimal:2',
        'total' => 'decimal:2',
        'warranty_date' => 'date',
    ];

    protected static function boot()
    {
        parent::boot();

        static::saving(function ($item) {
            // Calculate discount from percent if not set
            if ($item->discount_percent > 0 && $item->discount == 0) {
                $item->discount = $item->unit_price * ($item->discount_percent / 100);
            }
            
            // Calculate final price
            $item->final_price = $item->unit_price - $item->discount;
            
            // Calculate total
            $item->total = $item->final_price * $item->quantity;
        });
    }

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

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

    /**
     * Get profit for this item
     */
    public function getProfit(): float
    {
        return ($this->final_price - $this->cost_price) * $this->quantity;
    }

    /**
     * Check if item has warranty
     */
    public function hasWarranty(): bool
    {
        return $this->warranty_date !== null && $this->warranty_date->isFuture();
    }
}
