<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\AccessControl;
use yii\data\ActiveDataProvider;
use app\models\Application;
use app\models\User;
use app\models\Course;
use app\models\LoginForm;

/**
 * AdminController implements the CRUD actions for admin panel.
 */
class AdminController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                        'matchCallback' => function ($rule, $action) {
                            return Yii::$app->user->identity->isAdmin();
                        }
                    ],
                ],
                'denyCallback' => function ($rule, $action) {
                    if (Yii::$app->user->isGuest) {
                        Yii::$app->session->setFlash('error', 
                            'Для доступа к панели администратора необходимо войти в систему.');
                        return Yii::$app->getResponse()->redirect(['site/login']);
                    }
                    
                    Yii::$app->session->setFlash('error', 
                        'У вас недостаточно прав для доступа к панели администратора.');
                    return Yii::$app->getResponse()->redirect(['site/index']);
                }
            ],
        ];
    }

    /**
     * Admin dashboard.
     *
     * @return string
     */
    public function actionIndex()
    {
        // Статистика
        $stats = [
            'total_applications' => Application::find()->count(),
            'new_applications' => Application::find()->where(['status' => Application::STATUS_NEW])->count(),
            'in_progress_applications' => Application::find()->where(['status' => Application::STATUS_IN_PROGRESS])->count(),
            'completed_applications' => Application::find()->where(['status' => Application::STATUS_COMPLETED])->count(),
            'total_users' => User::find()->count(),
            'total_courses' => Course::find()->count(),
            'active_courses' => Course::find()->where(['is_active' => true])->count(),
        ];

        // Последние заявки
        $recentApplications = Application::find()
            ->with(['user', 'course'])
            ->orderBy(['created_at' => SORT_DESC])
            ->limit(10)
            ->all();

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

    /**
     * Lists all applications.
     *
     * @return string
     */
    public function actionApplications()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Application::find()
                ->with(['user', 'course'])
                ->orderBy(['created_at' => SORT_DESC]),
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);

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

    /**
     * Updates application status.
     *
     * @param integer $id
     * @return string|\yii\web\Response
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdateStatus($id)
    {
        $model = $this->findApplicationModel($id);

        if ($model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                Yii::$app->session->setFlash('success', 'Статус заявки успешно обновлен.');
                return $this->redirect(['applications']);
            } else {
                Yii::$app->session->setFlash('error', 
                    'Произошла ошибка при обновлении статуса.');
            }
        }

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

    /**
     * View application details.
     *
     * @param integer $id
     * @return string
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionViewApplication($id)
    {
        $model = $this->findApplicationModel($id);

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

    /**
     * Lists all users.
     *
     * @return string
     */
    public function actionUsers()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => User::find()
                ->orderBy(['created_at' => SORT_DESC]),
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);

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

    /**
     * View user details.
     *
     * @param integer $id
     * @return string
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionViewUser($id)
    {
        $model = $this->findUserModel($id);
        
        $userApplications = Application::find()
            ->where(['user_id' => $id])
            ->orderBy(['created_at' => SORT_DESC])
            ->all();

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

    /**
     * Update user.
     *
     * @param integer $id
     * @return string|\yii\web\Response
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdateUser($id)
    {
        $model = $this->findUserModel($id);
        $model->scenario = 'update';

        if ($model->load(Yii::$app->request->post())) {
            // Если введен новый пароль
            if (!empty($model->password)) {
                $model->setPassword($model->password);
            }
            
            if ($model->save()) {
                Yii::$app->session->setFlash('success', 'Пользователь успешно обновлен.');
                return $this->redirect(['view-user', 'id' => $model->id]);
            }
        }

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

    /**
     * Lists all courses.
     *
     * @return string
     */
    public function actionCourses()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Course::find()
                ->orderBy(['name' => SORT_ASC]),
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);

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

    /**
     * Create course.
     *
     * @return string|\yii\web\Response
     */
    public function actionCreateCourse()
    {
        $model = new Course();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->session->setFlash('success', 'Курс успешно создан.');
            return $this->redirect(['courses']);
        }

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

    /**
     * Update course.
     *
     * @param integer $id
     * @return string|\yii\web\Response
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdateCourse($id)
    {
        $model = $this->findCourseModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->session->setFlash('success', 'Курс успешно обновлен.');
            return $this->redirect(['courses']);
        }

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

    /**
     * Delete course.
     *
     * @param integer $id
     * @return \yii\web\Response
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDeleteCourse($id)
    {
        $model = $this->findCourseModel($id);
        
        // Проверяем, есть ли заявки на этот курс
        $applicationsCount = $model->getApplications()->count();
        
        if ($applicationsCount > 0) {
            Yii::$app->session->setFlash('error', 
                'Нельзя удалить курс, на который есть заявки. Сначала удалите или перепривяжите заявки.');
            return $this->redirect(['courses']);
        }
        
        if ($model->delete()) {
            Yii::$app->session->setFlash('success', 'Курс успешно удален.');
        } else {
            Yii::$app->session->setFlash('error', 'Произошла ошибка при удалении курса.');
        }

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

    /**
     * View course details.
     *
     * @param integer $id
     * @return string
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionViewCourse($id)
    {
        $model = $this->findCourseModel($id);
        
        $courseApplications = Application::find()
            ->where(['course_id' => $id])
            ->with(['user'])
            ->orderBy(['created_at' => SORT_DESC])
            ->all();

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

    /**
     * Finds the Application model based on its primary key value.
     *
     * @param integer $id
     * @return Application the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findApplicationModel($id)
    {
        if (($model = Application::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('Заявка не найдена.');
    }

    /**
     * Finds the User model based on its primary key value.
     *
     * @param integer $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findUserModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('Пользователь не найден.');
    }

    /**
     * Finds the Course model based on its primary key value.
     *
     * @param integer $id
     * @return Course the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findCourseModel($id)
    {
        if (($model = Course::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('Курс не найден.');
    }
}