<?php

namespace Modules\PurchaseRequisition\Entities;

use Illuminate\Database\Eloquent\Model;

class PrSetting extends Model
{
    protected $table = 'pr_settings';

    protected $fillable = ['business_id', 'value'];

    protected $casts = [
        'value' => 'array',
    ];

    /**
     * Get the business that owns this setting.
     */
    public function business()
    {
        return $this->belongsTo(\App\Business::class);
    }

    /**
     * Scope to filter by business.
     */
    public function scopeForBusiness($query, $businessId)
    {
        return $query->where('business_id', $businessId);
    }

    /**
     * Get settings for a business with defaults.
     */
    public static function getSettings($businessId)
    {
        $settings = self::where('business_id', $businessId)->first();

        $defaults = [
            'selling_interval' => 365,
            'stock_cover_interval' => 180,
            'margin_ratio' => 20,
            'avg_cost_period' => 'all',
            'bg_color_no_purchase' => '#FFF3CD',
            'bg_color_no_purchase_no_stock' => '#FFDDC1',
            'bg_color_zero_qty' => '#D1ECF1',
            'bg_color_low_margin' => '#F8D7DA',
        ];

        if ($settings) {
            return array_merge($defaults, $settings->value);
        }

        return $defaults;
    }

    /**
     * Update or create settings for a business.
     */
    public static function updateSettings($businessId, array $values)
    {
        return self::updateOrCreate(
            ['business_id' => $businessId],
            ['value' => $values]
        );
    }
}
