<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class PurchaseItem extends Model
{
    use HasFactory;

    protected $table = 'purchase_items';

    protected $fillable = [
        'purchase_id',
        'product_id',
        'item_type',
        'description',
        'quantity',
        'unit_price',
        'tax_percent',
        'tax_amount',
        'discount_percent',
        'discount_amount',
        'total',
        'batch_number',
        'expiry_date',
        'added_to_stock',
        'notes',
    ];

    protected $casts = [
        'quantity' => 'decimal:3',
        'unit_price' => 'decimal:2',
        'tax_percent' => 'decimal:2',
        'tax_amount' => 'decimal:2',
        'discount_percent' => 'decimal:2',
        'discount_amount' => 'decimal:2',
        'total' => 'decimal:2',
        'added_to_stock' => 'boolean',
        'expiry_date' => 'date',
    ];

    /**
     * Relationships
     */
    public function purchase()
    {
        return $this->belongsTo(Purchase::class);
    }

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

    public function batch()
    {
        return $this->hasOne(ProductBatch::class, 'purchase_item_id');
    }

    /**
     * Accessors
     */
    public function getLineTotalAttribute()
    {
        return ($this->quantity * $this->unit_price) - $this->discount_amount + $this->tax_amount;
    }

    public function getIsProductAttribute()
    {
        return $this->item_type === 'product';
    }

    public function getIsServiceAttribute()
    {
        return $this->item_type === 'service';
    }

    public function getCanAddToStockAttribute()
    {
        return $this->is_product && 
               $this->product && 
               $this->product->track_inventory && 
               !$this->added_to_stock;
    }

    /**
     * Update product stock from this item
     */
    public function addToStock(): bool
    {
        if (!$this->can_add_to_stock) {
            return false;
        }

        try {
            $product = $this->product;
            $product->increment('stock', $this->quantity);
            
            // Create or update batch if needed
            if ($product->track_batches || $this->batch_number || $this->expiry_date) {
                $this->createOrUpdateBatch();
            }

            // Update product stock status
            $product->updateStockStatus();

            // Mark as added to stock
            $this->added_to_stock = true;
            $this->save();

            return true;
        } catch (\Exception $e) {
            \Log::error('Failed to add item to stock: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Create or update batch for this item
     */
    private function createOrUpdateBatch()
    {
        $batch = ProductBatch::where('product_id', $this->product_id)
            ->where('batch_number', $this->batch_number)
            ->where('expiry_date', $this->expiry_date)
            ->first();

        if ($batch) {
            // Update existing batch
            $batch->update([
                'current_quantity' => $batch->current_quantity + $this->quantity,
                'updated_at' => now(),
            ]);
        } else {
            // Create new batch
            $batch = ProductBatch::create([
                'product_id' => $this->product_id,
                'supplier_id' => $this->purchase->supplier_id,
                'purchase_id' => $this->purchase_id,
                'purchase_item_id' => $this->id,
                'batch_number' => $this->batch_number ?? 'BATCH-' . date('Ymd') . '-' . strtoupper(substr(md5(uniqid()), 0, 6)),
                'expiry_date' => $this->expiry_date,
                'initial_quantity' => $this->quantity,
                'current_quantity' => $this->quantity,
                'batch_cost_price' => $this->unit_price,
                'batch_sale_price' => $this->product->sale_price,
                'created_by' => auth()->id(),
            ]);
        }

        // Log batch movement
        BatchStockMovement::create([
            'batch_id' => $batch->id,
            'product_id' => $this->product_id,
            'movement_type' => 'in',
            'quantity' => $this->quantity,
            'quantity_before' => $batch->current_quantity - $this->quantity,
            'reason' => 'purchase',
            'reference_number' => $this->purchase->invoice_no,
            'notes' => 'Added from purchase',
            'user_id' => auth()->id(),
        ]);
    }
}