<?php

declare(strict_types=1);

namespace common\models;

use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\ActiveQuery;

/**
 * FoodLibrary ActiveRecord model.
 * user_id = NULL  → global food visible to all
 * user_id = int   → nutritionist-private food
 *
 * @property int         $id
 * @property int|null    $user_id
 * @property string      $name
 * @property string|null $category
 * @property string|null $tags
 * @property string|null $serving_size
 * @property float       $calories
 * @property float       $protein
 * @property float       $carbs
 * @property float       $fats
 * @property float       $fiber
 * @property int         $is_active
 * @property int         $created_at
 * @property int         $updated_at
 *
 * @property DietPlanMeal[] $dietPlanMeals
 */
class FoodLibrary extends ActiveRecord
{
    public static function tableName(): string
    {
        return '{{%food_library}}';
    }

    public function behaviors(): array
    {
        return [
            TimestampBehavior::class,
        ];
    }

    public function rules(): array
    {
        return [
            [['name', 'calories'], 'required'],
            [['name'], 'string', 'max' => 200],
            [['category'], 'string', 'max' => 80],
            [['tags'], 'string', 'max' => 500],
            [['serving_size'], 'string', 'max' => 50],
            [['calories', 'protein', 'carbs', 'fats', 'fiber'], 'number', 'min' => 0],
            [['protein', 'carbs', 'fats', 'fiber'], 'default', 'value' => 0],
            [['user_id'], 'integer'],
            [['is_active'], 'boolean'],
            [['is_active'], 'default', 'value' => 1],
        ];
    }

    public function attributeLabels(): array
    {
        return [
            'id'           => 'ID',
            'user_id'      => 'Owner',
            'name'         => 'Food Name',
            'category'     => 'Category',
            'tags'         => 'Tags',
            'serving_size' => 'Serving Size',
            'calories'     => 'Calories (kcal)',
            'protein'      => 'Protein (g)',
            'carbs'        => 'Carbs (g)',
            'fats'         => 'Fats (g)',
            'fiber'        => 'Fiber (g)',
            'is_active'    => 'Active',
        ];
    }

    /**
     * Returns foods visible to a given user: global foods + user's own private foods.
     */
    public static function findVisibleToUser(?int $userId): ActiveQuery
    {
        return static::find()
            ->where(['is_active' => 1])
            ->andWhere(['OR', ['user_id' => null], ['user_id' => $userId]])
            ->orderBy(['name' => SORT_ASC]);
    }

    public function getDietPlanMeals(): ActiveQuery
    {
        return $this->hasMany(DietPlanMeal::class, ['food_library_id' => 'id']);
    }

    public function isGlobal(): bool
    {
        return $this->user_id === null;
    }
}
