<?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * Class ReadingForm
 * @package app\models
 *
 * @property string $date
 * @property string $category
 * @property float $current_readings
 * @property float $previous_readings
 * @property float $consumption
 * @property float $tariff
 * @property float $amount
 */
class ReadingForm extends Model
{
    public $date;
    public $category;
    public $current_readings;
    public $previous_readings;
    public $consumption;
    public $tariff;
    public $amount;

    public function rules()
    {
        return [
            [['date', 'category', 'current_readings'], 'required'],
            [['current_readings', 'previous_readings'], 'number', 'min' => 0],
            ['category', 'in', 'range' => array_keys(Application::getCategories())],
            ['date', 'date', 'format' => 'php:Y-m-d'],
            ['current_readings', 'validateCurrentReadings'],
            [['consumption', 'tariff', 'amount'], 'safe'],
        ];
    }

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

    public function validateCurrentReadings($attribute, $params)
    {
        if ($this->current_readings <= $this->previous_readings) {
            $this->addError($attribute, 'Текущие показания должны быть больше предыдущих.');
        }
    }

    public function loadPreviousReadings($userId)
    {
        if ($this->category) {
            $this->previous_readings = Application::getLastReadings($userId, $this->category);
        }
    }

    public function calculate()
    {
        if ($this->current_readings > $this->previous_readings) {
            $this->consumption = $this->current_readings - $this->previous_readings;
            $this->tariff = Application::getTariff($this->category);
            $this->amount = round($this->consumption * $this->tariff, 2);
        } else {
            $this->consumption = 0;
            $this->tariff = Application::getTariff($this->category);
            $this->amount = 0;
        }
    }

    public function save($userId)
    {
        if (!$this->validate()) {
            return false;
        }

        $this->calculate();

        $application = new Application();
        $application->user_id = $userId;
        $application->date = $this->date;
        $application->category = $this->category;
        $application->previous_readings = $this->previous_readings;
        $application->current_readings = $this->current_readings;
        $application->consumption = $this->consumption;
        $application->tariff = $this->tariff;
        $application->amount = $this->amount;

        if ($application->save()) {
            return $application;
        }

        return false;
    }
}