<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    /**
     * The attributes that aren't mass assignable.
     *
     * NOTE: We are only guarding 'id', so other columns are allowed
     * unless specifically excluded. This is fine.
     */
    protected $guarded = ['id'];

    /**
     * The attributes that are mass assignable.
     *
     * CRITICAL: We include business_id here so that create/update 
     *           can set it. Also keep 'use_serial' or any other 
     *           custom fillable fields that you need.
     */
    protected $fillable = [
        'business_id',  // <-- ADDED to ensure the foreign key is set
        'use_serial',
        'created_by',
        'name'
        // ... any other fields you want explicitly fillable ...
    ];

    /**
     * Append custom attributes for retrieval.
     *
     * @var array
     */
    protected $appends = ['image_url'];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'sub_unit_ids' => 'array',
    ];

    /**
     * Get the products image URL.
     *
     * @return string
     */
    public function getImageUrlAttribute()
    {
        if (! empty($this->image)) {
            $image_url = asset('/uploads/img/'.rawurlencode($this->image));
        } else {
            $image_url = asset('/img/default.png');
        }

        return $image_url;
    }

    /**
     * Get the products image path.
     *
     * @return string|null
     */
    public function getImagePathAttribute()
    {
        if (! empty($this->image)) {
            return public_path('uploads').'/'.config('constants.product_img_path').'/'.$this->image;
        } else {
            return null;
        }
    }

    public function product_variations()
    {
        return $this->hasMany(\App\ProductVariation::class);
    }

    /**
     * Get the brand associated with the product.
     */
    public function brand()
    {
        return $this->belongsTo(\App\Brands::class);
    }

    /**
     * Get the unit associated with the product.
     */
    public function unit()
    {
        return $this->belongsTo(\App\Unit::class);
    }

    /**
     * Get the second (or secondary) unit associated with the product.
     */
    public function second_unit()
    {
        return $this->belongsTo(\App\Unit::class, 'secondary_unit_id');
    }

    /**
     * Get category associated with the product.
     */
    public function category()
    {
        return $this->belongsTo(\App\Category::class);
    }

    /**
     * Get sub-category associated with the product.
     */
    public function sub_category()
    {
        return $this->belongsTo(\App\Category::class, 'sub_category_id', 'id');
    }

    /**
     * Get the tax associated with the product.
     */
    public function product_tax()
    {
        return $this->belongsTo(\App\TaxRate::class, 'tax', 'id');
    }

    /**
     * Get the variations associated with the product.
     */
    public function variations()
    {
        return $this->hasMany(\App\Variation::class);
    }

    /**
     * If product type is modifier, get the products associated with it.
     */
    public function modifier_products()
    {
        return $this->belongsToMany(
            \App\Product::class,
            'res_product_modifier_sets',
            'modifier_set_id',
            'product_id'
        );
    }

    /**
     * If product type is modifier, get the modifier sets associated with it.
     */
    public function modifier_sets()
    {
        return $this->belongsToMany(
            \App\Product::class,
            'res_product_modifier_sets',
            'product_id',
            'modifier_set_id'
        );
    }

    /**
     * Get the purchases associated with the product.
     */
    public function purchase_lines()
    {
        return $this->hasMany(\App\PurchaseLine::class);
    }

    /**
     * Scope a query to only include active products.
     */
    public function scopeActive($query)
    {
        return $query->where('products.is_inactive', 0);
    }

    /**
     * Scope a query to only include inactive products.
     */
    public function scopeInactive($query)
    {
        return $query->where('products.is_inactive', 1);
    }

    /**
     * Scope a query to only include products for sales.
     */
    public function scopeProductForSales($query)
    {
        return $query->where('not_for_selling', 0);
    }

    /**
     * Scope a query to only include products not for sales.
     */
    public function scopeProductNotForSales($query)
    {
        return $query->where('not_for_selling', 1);
    }

    public function product_locations()
    {
        return $this->belongsToMany(
            \App\BusinessLocation::class,
            'product_locations',
            'product_id',
            'location_id'
        );
    }

    /**
     * Scope a query to only include products available for a location.
     */
    public function scopeForLocation($query, $location_id)
    {
        return $query->where(function ($q) use ($location_id) {
            $q->whereHas('product_locations', function ($query) use ($location_id) {
                $query->where('product_locations.location_id', $location_id);
            });
        });
    }

    /**
     * Get warranty associated with the product.
     */
    public function warranty()
    {
        return $this->belongsTo(\App\Warranty::class);
    }

    public function media()
    {
        return $this->morphMany(\App\Media::class, 'model');
    }

    public function rack_details()
    {
        return $this->hasMany(\App\ProductRack::class);
    }
}
