<?php

namespace App\Models;

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

class Product extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'company_id',
        'name',
        'sku',
        'type',                //Service or Inventory
        'category',            //Service, Raw Material, Finished Good
        'country_of_origin',
        
        // Sales Mapping
        'sales_price',
        'income_account_id',   // Links to Revenue
        'tax_category',        
        
        // Purchasing Mapping
        'purchase_description',
        'cost',                // Cost Price (Fixed: Now included)
        'expense_account_id',  // Links to COGS for Inventory
        'preferred_vendor_id',
        
        // Inventory Tracking
        'qty_on_hand',         // Initial Quantity
        'asset_account_id'     // Inventory Asset Account
    ];

    /**
     * The attributes that should be cast.
     */
    protected $casts = [
        'sales_price' => 'decimal:2',
        'cost' => 'decimal:2',
        'qty_on_hand' => 'integer',
    ];

    /**
     * Relationship to the Company
     */
    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }

    /**
     * Income Account Relationship
     */
    public function incomeAccount(): BelongsTo
    {
        return $this->belongsTo(Account::class, 'income_account_id');
    }

    /**
     * Expense/COGS Account Relationship
     */
    public function expenseAccount(): BelongsTo
    {
        return $this->belongsTo(Account::class, 'expense_account_id');
    }

    /**
     * Asset Account Relationship (for Inventory tracking)
     */
    public function assetAccount(): BelongsTo
    {
        return $this->belongsTo(Account::class, 'asset_account_id');
    }

    /**
     * Relationship to the Preferred Vendor
     */
    public function preferredVendor(): BelongsTo
    {
        return $this->belongsTo(Supplier::class, 'preferred_vendor_id');
    }
    
    
    /**
     * Get all FIFO stock layers for this product.
     */
    public function batches(): HasMany
    {
        return $this->hasMany(StockBatch::class);
    }

    /**
     * Get all historical stock movements (Audit Trail).
     */
    public function stockMovements(): HasMany
    {
        return $this->hasMany(StockMovement::class);
    }

    /**
     * Dynamic Attribute: Real-time Total Stock
     * Usage: $product->total_stock
     */
    public function getTotalStockAttribute()
    {
        return $this->batches()->sum('remaining_qty');
    }
    
}