<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'user_id',
        'sku',
        'name',
        'price',
        'stock',
        'description',
        'is_active',
        'product_type',
        'bundle_items',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'is_active' => 'boolean',
        'bundle_items' => 'array',
    ];

    /**
     * Get the user that owns the product
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Scope to only show active products
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope to filter by user
     */
    public function scopeForUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    /**
     * Check if product is created by admin
     */
    public function isAdminProduct()
    {
        return $this->user && $this->user->role === 'admin';
    }

    /**
     * Scope to get products accessible by a user (their own + admin products)
     */
    public function scopeAccessibleByUser($query, $userId)
    {
        return $query->where(function($q) use ($userId) {
            $q->where('user_id', $userId) // User's own products
              ->orWhereHas('user', function($userQuery) {
                  $userQuery->where('role', 'admin'); // Admin products (global)
              });
        });
    }

    /**
     * Scope to get only admin products (global products)
     */
    public function scopeAdminProducts($query)
    {
        return $query->whereHas('user', function($userQuery) {
            $userQuery->where('role', 'admin');
        });
    }

    /**
     * Scope to filter by product type
     */
    public function scopeOfType($query, $type)
    {
        return $query->where('product_type', $type);
    }

    /**
     * Scope to get only single products
     */
    public function scopeSingleProducts($query)
    {
        return $query->where('product_type', 'single');
    }

    /**
     * Scope to get only bundles
     */
    public function scopeBundles($query)
    {
        return $query->where('product_type', 'bundle');
    }

    /**
     * Check if product is a bundle
     */
    public function isBundle()
    {
        return $this->product_type === 'bundle';
    }

    /**
     * Get bundle items count
     */
    public function getBundleItemsCount()
    {
        if (!$this->isBundle() || !$this->bundle_items) {
            return 0;
        }
        return count($this->bundle_items);
    }
}
