<?php

declare(strict_types=1);

namespace common\models;

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

/**
 * DietPlan ActiveRecord model.
 *
 * @property int         $id
 * @property int         $customer_id
 * @property string      $title
 * @property string|null $description
 * @property string|null $start_date
 * @property string|null $end_date
 * @property float       $total_calories
 * @property float       $total_protein
 * @property float       $total_carbs
 * @property float       $total_fats
 * @property int         $is_template
 * @property string|null $template_name
 * @property string      $status  draft|active|archived
 * @property int|null    $created_by
 * @property int         $created_at
 * @property int         $updated_at
 *
 * @property Customer       $customer
 * @property DietPlanMeal[] $meals
 */
class DietPlan extends ActiveRecord
{
    public const STATUS_DRAFT    = 'draft';
    public const STATUS_ACTIVE   = 'active';
    public const STATUS_ARCHIVED = 'archived';

    public static function tableName(): string
    {
        return '{{%diet_plans}}';
    }

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

    public function rules(): array
    {
        return [
            [['customer_id', 'title'], 'required'],
            [['customer_id', 'created_by'], 'integer'],
            [['title'], 'string', 'max' => 200],
            [['template_name'], 'string', 'max' => 150],
            [['description'], 'string'],
            [['start_date', 'end_date'], 'date', 'format' => 'php:Y-m-d'],
            [['total_calories', 'total_protein', 'total_carbs', 'total_fats'], 'number', 'min' => 0],
            [['is_template'], 'boolean'],
            [['status'], 'in', 'range' => [self::STATUS_DRAFT, self::STATUS_ACTIVE, self::STATUS_ARCHIVED]],
            [['status'], 'default', 'value' => self::STATUS_DRAFT],
            [['customer_id'], 'exist', 'targetClass' => Customer::class, 'targetAttribute' => ['customer_id' => 'id']],
        ];
    }

    public function attributeLabels(): array
    {
        return [
            'id'             => 'ID',
            'customer_id'    => 'Customer',
            'title'          => 'Plan Title',
            'description'    => 'Description',
            'start_date'     => 'Start Date',
            'end_date'       => 'End Date',
            'total_calories' => 'Total Calories (kcal)',
            'total_protein'  => 'Total Protein (g)',
            'total_carbs'    => 'Total Carbs (g)',
            'total_fats'     => 'Total Fats (g)',
            'is_template'    => 'Save as Template',
            'template_name'  => 'Template Name',
            'status'         => 'Status',
            'created_at'     => 'Created At',
        ];
    }

    public function getCustomer(): \yii\db\ActiveQuery
    {
        return $this->hasOne(Customer::class, ['id' => 'customer_id']);
    }

    public function getMeals(): \yii\db\ActiveQuery
    {
        return $this->hasMany(DietPlanMeal::class, ['diet_plan_id' => 'id'])
            ->orderBy(['meal_type' => SORT_ASC, 'sort_order' => SORT_ASC]);
    }

    /**
     * Recalculate totals from meals. Call before saving.
     */
    public function recalculateTotals(): void
    {
        $this->total_calories = 0;
        $this->total_protein  = 0;
        $this->total_carbs    = 0;
        $this->total_fats     = 0;

        foreach ($this->meals as $meal) {
            $this->total_calories += $meal->calories;
            $this->total_protein  += $meal->protein;
            $this->total_carbs    += $meal->carbs;
            $this->total_fats     += $meal->fats;
        }
    }

    public static function mealTypeOrder(): array
    {
        return ['breakfast', 'morning_snack', 'lunch', 'evening_snack', 'dinner', 'bedtime_snack'];
    }
}
