<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\RegisterForm;
use app\models\User;
use app\models\RestaurantForm;
use app\models\Restaurant;
use app\models\CourierForm;
use app\models\Courier;

class AuthController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'only' => ['logout', 'login', 'register', 'courier_register', 'restaurant_register'],
                'rules' => [
                    [
                        'actions' => ['login', 'register'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout', 'courier_register', 'restaurant_register'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Login action.
     *
     * @return Response|string
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        }

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

    /**
     * Logout action.
     *
     * @return Response
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    public function actionRegister()
    {
        $model = new RegisterForm();
        if ($model->load(Yii::$app->request->post()) && $model->register()) {

            return $this->redirect(['/auth/login']);
        }
        return $this->render('register', [
            'model' => $model,
        ]);
    }

    public function actionRestaurantRegister()
    {
        if (Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $userId = Yii::$app->user->id;
        
        $hasActiveRestaurant = Restaurant::find()
            ->where(['user_id' => $userId, 'status' => 1])
            ->exists();
        
        if ($hasActiveRestaurant) {
            return $this->redirect(['site/restaurant']);
        }

        $model = new RestaurantForm();

        if ($model->load(Yii::$app->request->post()) && $model->restaurant()) {
            return $this->redirect(['site/index']);
        }

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

    public function actionCourierRegister()
    {
        if (Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $userId = Yii::$app->user->id;

        $hasActiveCourier = Courier::find()
            ->where(['user_id' => $userId, 'status' => 1])
            ->exists();
        
        if ($hasActiveCourier) {
            return $this->redirect(['site/courier']);
        }

        $existingCourier = Courier::findOne(['user_id' => $userId]);
        if ($existingCourier) {
            Yii::$app->session->setFlash('info', 'Ваша заявка на регистрацию курьера находится на рассмотрении администратора.');
            return $this->redirect(['site/index']);
        }

        $model = new CourierForm();
        
        if (Yii::$app->request->isPost) {
            $model->load(Yii::$app->request->post());
        
            if ($model->courier()) {
                Yii::$app->session->setFlash('success', 'Регистрация успешно завершена! Ожидайте подтверждения администратора.');
                return $this->redirect(['site/index']);
            }
        }

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