<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;
use yii\data\ActiveDataProvider;
use app\models\CounterReadings;
use app\models\User;
use app\models\Tariff;
use yii\web\NotFoundHttpException;

class AdminController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                        'matchCallback' => function ($rule, $action) {
                            return Yii::$app->user->identity->is_admin == 1;
                        }
                    ],
                ],
                'denyCallback' => function ($rule, $action) {
                    Yii::$app->session->setFlash('error', 'Доступ запрещен. Требуются права администратора.');
                    return $this->redirect(['/site/index']);
                }
            ],
        ];
    }

    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => CounterReadings::find()->joinWith('user')->orderBy(['counter_readings.created_at' => SORT_DESC]),
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);

        $stats = [
            'total' => CounterReadings::find()->count(),
            'new' => CounterReadings::find()->where(['status' => CounterReadings::STATUS_NEW])->count(),
            'accepted' => CounterReadings::find()->where(['status' => CounterReadings::STATUS_ACCEPTED])->count(),
            'rejected' => CounterReadings::find()->where(['status' => CounterReadings::STATUS_REJECTED])->count(),
            'users' => User::find()->count(),
        ];

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'stats' => $stats,
        ]);
    }

    public function actionUpdateStatus($id, $status)
    {
        $reading = $this->findModel($id);
        
        if (!in_array($status, [CounterReadings::STATUS_ACCEPTED, CounterReadings::STATUS_REJECTED])) {
            Yii::$app->session->setFlash('error', 'Неверный статус.');
            return $this->redirect(['index']);
        }

        $reading->status = $status;
        if ($reading->save()) {
            Yii::$app->session->setFlash('success', 'Статус показаний успешно обновлен.');
        } else {
            Yii::$app->session->setFlash('error', 'Ошибка при обновлении статуса.');
        }

        return $this->redirect(['index']);
    }

    public function actionUsers()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => User::find()->orderBy(['created_at' => SORT_DESC]),
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);

        return $this->render('users', [
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionTariffs()
    {
        $tariffs = Tariff::find()->all();
        $model = new Tariff();

        if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                Yii::$app->session->setFlash('success', 'Тариф успешно добавлен.');
                return $this->refresh();
            } else {
                Yii::$app->session->setFlash('error', 'Ошибка при добавлении тарифа.');
            }
        }

        return $this->render('tariffs', [
            'tariffs' => $tariffs,
            'model' => $model,
        ]);
    }

    public function actionUpdateTariff($id)
    {
        $tariff = Tariff::findOne($id);
        if (!$tariff) {
            throw new NotFoundHttpException('Тариф не найден.');
        }

        if (Yii::$app->request->isPost && $tariff->load(Yii::$app->request->post())) {
            if ($tariff->save()) {
                Yii::$app->session->setFlash('success', 'Тариф успешно обновлен.');
                return $this->redirect(['tariffs']);
            } else {
                Yii::$app->session->setFlash('error', 'Ошибка при обновлении тарифа.');
            }
        }

        return $this->render('update-tariff', [
            'model' => $tariff,
        ]);
    }

    public function actionDeleteTariff($id)
    {
        $tariff = Tariff::findOne($id);
        if (!$tariff) {
            throw new NotFoundHttpException('Тариф не найден.');
        }

        if ($tariff->delete()) {
            Yii::$app->session->setFlash('success', 'Тариф успешно удален.');
        } else {
            Yii::$app->session->setFlash('error', 'Ошибка при удалении тарифа.');
        }

        return $this->redirect(['tariffs']);
    }

    public function actionUserReadings($userId)
    {
        $user = User::findOne($userId);
        if (!$user) {
            throw new NotFoundHttpException('Пользователь не найден.');
        }

        $dataProvider = new ActiveDataProvider([
            'query' => CounterReadings::find()->where(['user_id' => $userId])->orderBy(['created_at' => SORT_DESC]),
            'pagination' => [
                'pageSize' => 15,
            ],
        ]);

        return $this->render('user-readings', [
            'dataProvider' => $dataProvider,
            'user' => $user,
        ]);
    }

    public function actionReadingDetail($id)
    {
        $reading = $this->findModel($id);
        return $this->render('reading-detail', [
            'reading' => $reading,
        ]);
    }

    // Добавьте этот метод в существующий AdminController
public function actionStatistics()
{
    // Статистика по месяцам
    $monthlyStats = CounterReadings::find()
        ->select([
            'MONTH(date) as month',
            'YEAR(date) as year',
            'COUNT(*) as total',
            'SUM(CASE WHEN status = "accepted" THEN 1 ELSE 0 END) as accepted',
            'SUM(CASE WHEN status = "rejected" THEN 1 ELSE 0 END) as rejected',
            'SUM(sum) as total_sum'
        ])
        ->groupBy('YEAR(date), MONTH(date)')
        ->orderBy('year DESC, month DESC')
        ->asArray()
        ->all();

    // Статистика по услугам
    $serviceStats = CounterReadings::find()
        ->select([
            'service_type',
            'COUNT(*) as total',
            'AVG(consumption) as avg_consumption',
            'SUM(sum) as total_sum'
        ])
        ->groupBy('service_type')
        ->asArray()
        ->all();

    return $this->render('statistics', [
        'monthlyStats' => $monthlyStats,
        'serviceStats' => $serviceStats,
    ]);
}

    protected function findModel($id)
    {
        if (($model = CounterReadings::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('Запись не найдена.');
    }
}