<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use app\models\Application;
use app\models\Event;

class AdminController extends Controller
{
    public function beforeAction($action)
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(['/auth/login']);
        }

        $user = Yii::$app->user->identity;
        if ($user->role !== 'admin') {
            Yii::$app->session->setFlash('error', 'Доступ запрещён.');
            return $this->goHome();
        }

        return parent::beforeAction($action);
    }

    public function actionIndex()
    {
        $applications = Application::find()
            ->with('user', 'event.game')
            ->orderBy('created_at DESC')
            ->all();

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

    public function actionUpdateStatus()
    {
        $id = Yii::$app->request->post('id');
        $status = Yii::$app->request->post('status');

        $app = Application::findOne($id);
        if (!$app) {
            throw new NotFoundHttpException('Заявка не найдена.');
        }

        $app->status = $status;
        if ($app->save(false)) {
            Yii::$app->session->setFlash('success', 'Статус заявки обновлён.');
        }

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