<?php

namespace app\models;

use Yii;
use yii\db\ActiveRecord;

class CounterReadings extends ActiveRecord
{
    const STATUS_NEW = 'new';
    const STATUS_ACCEPTED = 'accepted';
    const STATUS_REJECTED = 'rejected';

    const SERVICE_ELECTRICITY = 'electricity';
    const SERVICE_GAS = 'gas';
    const SERVICE_WATER = 'water';

    public static function tableName()
    {
        return '{{%counter_readings}}';
    }

    public function rules()
    {
        return [
            [['user_id', 'date', 'service_type', 'current_readings'], 'required'],
            [['current_readings'], 'number', 'min' => 0],
            ['current_readings', 'validateReadings'],
            ['service_type', 'in', 'range' => array_keys(self::getServiceTypes())],
        ];
    }

    public function validateReadings($attribute, $params)
    {
        $previous = self::find()
            ->where(['user_id' => $this->user_id, 'service_type' => $this->service_type])
            ->orderBy(['date' => SORT_DESC])
            ->one();

        if ($previous && $this->current_readings < $previous->current_readings) {
            $this->addError($attribute, 'Текущие показания не могут быть меньше предыдущих');
        }
    }

    public function beforeSave($insert)
{
    if (parent::beforeSave($insert)) {
        // Логирование для отладки
        Yii::info("Сохранение показаний: user_id={$this->user_id}, service_type={$this->service_type}, readings={$this->current_readings}");
        
        $previous = self::find()
            ->where(['user_id' => $this->user_id, 'service_type' => $this->service_type])
            ->orderBy(['date' => SORT_DESC])
            ->one();

        $this->previous_readings = $previous ? $previous->current_readings : 0;
        $this->consumption = $this->current_readings - $this->previous_readings;
        
        $tariff = Tariff::findOne(['service_type' => $this->service_type]);
        $this->tariff = $tariff ? $tariff->price : 0;
        $this->sum = $this->consumption * $this->tariff;

        if ($insert) {
            $this->status = self::STATUS_NEW;
        }

        return true;
    }
    return false;
}

    public function attributeLabels()
    {
        return [
            'date' => 'Дата передачи',
            'service_type' => 'Услуга',
            'current_readings' => 'Текущие показания',
            'previous_readings' => 'Предыдущие показания',
            'consumption' => 'Расход',
            'tariff' => 'Тариф',
            'sum' => 'Сумма к оплате',
            'status' => 'Статус',
        ];
    }

    public static function getServiceTypes()
    {
        return [
            self::SERVICE_ELECTRICITY => 'Электричество',
            self::SERVICE_GAS => 'Газ',
            self::SERVICE_WATER => 'Вода',
        ];
    }

    public static function getStatuses()
    {
        return [
            self::STATUS_NEW => 'Новая',
            self::STATUS_ACCEPTED => 'Показания приняты',
            self::STATUS_REJECTED => 'Ошибка в показаниях',
        ];
    }

    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    public function getServiceTypeLabel()
    {
        $types = self::getServiceTypes();
        return isset($types[$this->service_type]) ? $types[$this->service_type] : $this->service_type;
    }

    public function getStatusLabel()
    {
        $statuses = self::getStatuses();
        return isset($statuses[$this->status]) ? $statuses[$this->status] : $this->status;
    }
}