<?php

namespace App\Models;

use App\Traits\BelongsToBranch;
use App\Traits\BelongsToOrganization;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Product extends Model
{
    use HasFactory, SoftDeletes, BelongsToOrganization, BelongsToBranch;

    protected $fillable = [
        'category_id',
        'branch_id',
        'name',
        'slug',
        'sku',
        'barcode',
        'description',
        'image',
        'images',
        'cost_price',
        'selling_price',
        'stock_quantity',
        'low_stock_threshold',
        'unit',
        'is_active',
        'track_stock',
        'expiry_date',
    ];

    protected function casts(): array
    {
        return [
            'cost_price' => 'decimal:2',
            'selling_price' => 'decimal:2',
            'stock_quantity' => 'integer',
            'low_stock_threshold' => 'integer',
            'is_active' => 'boolean',
            'track_stock' => 'boolean',
            'images' => 'array',
            'expiry_date' => 'date',
        ];
    }

    // Relationships
    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function purchaseItems()
    {
        return $this->hasMany(PurchaseItem::class);
    }

    public function saleItems()
    {
        return $this->hasMany(SaleItem::class);
    }

    public function inventoryAdjustments()
    {
        return $this->hasMany(InventoryAdjustment::class);
    }

    public function stocks()
    {
        return $this->hasMany(ProductStock::class);
    }

    /**
     * Get the ProductStock record for a specific branch.
     */
    public function stockForBranch(int $branchId): ?ProductStock
    {
        return $this->stocks()->where('branch_id', $branchId)->first();
    }

    /**
     * Aggregate stock across all branches.
     */
    public function getTotalStockAttribute(): int
    {
        return (int) $this->stocks()->sum('quantity');
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeLowStock($query)
    {
        return $query->where('track_stock', true)
                     ->where('low_stock_threshold', '>', 0)
                     ->where('stock_quantity', '>', 0)
                     ->whereRaw('stock_quantity <= low_stock_threshold');
    }

    public function scopeInStock($query)
    {
        return $query->where('stock_quantity', '>', 0);
    }

    public function scopeOutOfStock($query)
    {
        return $query->where('track_stock', true)->where('stock_quantity', '<=', 0);
    }

    public function scopeExpiringWithinDays($query, int $days = 30)
    {
        return $query->whereNotNull('expiry_date')
            ->whereDate('expiry_date', '>=', now()->toDateString())
            ->whereDate('expiry_date', '<=', now()->addDays($days)->toDateString());
    }

    // Accessors
    public function getProfitMarginAttribute()
    {
        if ($this->cost_price == 0) return 0;
        return (($this->selling_price - $this->cost_price) / $this->cost_price) * 100;
    }

    public function getIsLowStockAttribute(): bool
    {
        return $this->track_stock
            && $this->low_stock_threshold > 0
            && $this->stock_quantity > 0
            && $this->stock_quantity <= $this->low_stock_threshold;
    }
}
