<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends BaseModel
{
    protected $table = 'products';

    protected $appends = ['totalItem'];

    protected $fillable = ['id', 'category_id', 'manufacturer_id',
                           'sku', 'name', 'slug', 'image', 'description', 'price_from', 'price_to',
                           'discount', 'discount_start_time', 'discount_end_time', 'regular_price_from', 'regular_price_to',
                           'default_price', 'standard_construction_fee', 'shipping_cost',
                           'note', 'policy', 'possible_delivery_time', 'rank', 'wish_list', 'view',
                           'is_pricing_manual', 'is_available_in_stock', 'is_activated', 'is_deleted', 'created_at', 'updated_at'];

    public function category() {
        return $this->belongsTo(Category::class, 'category_id', 'id')->with('parent');
    }

    public function manufacturer() {
        return $this->belongsTo(Manufacturer::class, 'manufacturer_id', 'id')->select('id', 'name', 'slug', 'image');
    }

    public function options() {
        return $this->hasMany(ProductOption::class, 'product_id', 'id')->with('details');
    }

    public function options_public() {
        return $this->hasMany(ProductOptionPublic::class, 'product_id', 'id')
            ->with('details')
            ->where(function($query) {
                $query->where('is_check_all', true)
                    ->orWhere('is_indeterminate', true);
            })
            ->orderBy('name');
    }

    public function keyword_detail() {
        return $this->hasMany(ProductKeyword::class, 'product_id', 'id')->with('keyword');
    }

    public function purchases() {
        return $this->hasMany(ProductPurchaseMethod::class, 'product_id', 'id');
    }

    public function images() {
        return $this->hasMany(ProductImage::class, 'product_id', 'id');
    }

    public function details() {
        return $this->hasMany(ProductDetail::class, 'product_id', 'id')->with('option_detail');
    }

    public function getTotalItemAttribute() {
        return $this->details()->count();
    }

    public function pricing_rules() {
        return $this->hasMany(PricingRule::class, 'product_id', 'id')->with('detail', 'pricing');
    }
}

