<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "order".
 *
 * @property int $id
 * @property int $restaurant_id
 * @property int $total_price
 * @property int $count
 * @property int $courier_id
 * @property int $user_id
 * @property string $order_time
 * @property string $status
 * @property string $created_at
 *
 * @property Courier $courier
 * @property MenuItem $menuItem
 * @property Restaurant $restaurant
 * @property User $user
 */
class Order extends \yii\db\ActiveRecord
{
    const STATUS_COMPLETED = 'completed';  // <--- сюда
    const STATUS_PICKED_UP = 'picked_up'; // <-- добавляем
    const STATUS_NEW = 'new';


    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'order';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['user_id', 'restaurant_id', 'total_price'], 'required'],
            [['user_id', 'restaurant_id', 'count', 'courier_id', 'created_at'], 'integer'],
            [['total_price'], 'number'], 
            [['status'], 'string', 'max' => 20],
            [['order_time'], 'safe'],
            [['order_details'], 'string'],
            [['delivery_type'], 'string', 'max' => 20],
            [['delivery_address'], 'string'],
            [['count', 'courier_id'], 'default', 'value' => null],
            [['status'], 'default', 'value' => 'new'],
            [['order_time'], 'default', 'value' => date('Y-m-d H:i:s')],
            [['created_at'], 'default', 'value' => time()],
        ];
    }
    

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'restaurant_id' => 'Restaurant ID',
            'total_price' => 'Total Price',
            'count' => 'Count',
            'courier_id' => 'Courier ID',
            'user_id' => 'User ID',
            'order_time' => 'Order Time',
            'status' => 'Status',
            'created_at' => 'Created At',
        ];
    }

    /**
     * Gets query for [[Courier]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getCourier()
    {
        return $this->hasOne(Courier::class, ['id' => 'courier_id']);
    }


    /**
     * Gets query for [[Restaurant]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getRestaurant()
    {
        return $this->hasOne(Restaurant::class, ['id' => 'restaurant_id']);
    }

    /**
     * Gets query for [[User]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(User::class, ['id' => 'user_id']);
    }

    public function getDelivery()
    {
        return $this->hasOne(Delivery::class, ['order_id' => 'id']);
    }


    public function createDelivery($deliveryType, $deliveryAddress = null)
    {
        $delivery = new Delivery();
        $delivery->order_id = $this->id;
        $delivery->delivery_type = $deliveryType;
        $delivery->delivery_address = $deliveryAddress;
        $delivery->delivery_time = $this->getEstimatedDeliveryTime();
        
        return $delivery->save();
    }

    private function getEstimatedDeliveryTime()
    {
        $time = strtotime($this->order_time);
        
        if ($this->delivery_type === 'pickup') {
            $deliveryTime = date('H:i', $time + 20 * 60);
            return "к {$deliveryTime}";
        } else {
            $deliveryTime = date('H:i', $time + 45 * 60);
            return "примерно к {$deliveryTime}";
        }
    }

    public function saveOrderDetails($bucket)
    {
        $details = [];
        foreach ($bucket as $dishId => $quantity) {
            $dish = MenuItem::findOne($dishId);
            if ($dish) {
                $details[] = [
                    'dish_id' => $dishId,
                    'name' => $dish->name,
                    'quantity' => $quantity,
                    'price' => $dish->getDynamicPrice(),
                    'total' => $dish->getDynamicPrice() * $quantity
                ];
            }
        }
        
        $this->order_details = json_encode($details, JSON_UNESCAPED_UNICODE);
        return $this->save(false);
    }
}
