<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;
use app\models\EmployeeProfile;
use app\models\EmployeeProfileSearch;
use yii\data\ActiveDataProvider;

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;
                        }
                    ],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        $searchModel = new EmployeeProfileSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        // Получаем уникальные значения для фильтров
        $genders = EmployeeProfile::find()->select('gender')->distinct()->where(['IS NOT', 'gender', null])->column();
        $citizenships = EmployeeProfile::find()->select('citizenship')->distinct()->where(['IS NOT', 'citizenship', null])->column();
        $educations = EmployeeProfile::find()->select('education')->distinct()->where(['IS NOT', 'education', null])->column();
        $positions = EmployeeProfile::find()->select('position')->distinct()->where(['IS NOT', 'position', null])->column();
        $maritalStatuses = EmployeeProfile::find()->select('marital_status')->distinct()->where(['IS NOT', 'marital_status', null])->column();

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'genders' => array_combine($genders, $genders),
            'citizenships' => array_combine($citizenships, $citizenships),
            'educations' => array_combine($educations, $educations),
            'positions' => array_combine($positions, $positions),
            'maritalStatuses' => array_combine($maritalStatuses, $maritalStatuses),
        ]);
    }

    public function actionUpdateStatus($id)
    {
        $model = EmployeeProfile::findOne($id);
        if (!$model) {
            throw new \yii\web\NotFoundHttpException('Анкета не найдена.');
        }

        $currentStatus = $model->status;
        
        if (Yii::$app->request->isPost) {
            $newStatus = Yii::$app->request->post('status');
            
            if (in_array($newStatus, array_keys(EmployeeProfile::getStatuses()))) {
                $model->status = $newStatus;
                if ($model->save()) {
                    Yii::$app->session->setFlash('success', "Статус анкеты успешно изменен с '$currentStatus' на '$newStatus'.");
                    return $this->redirect(['view', 'id' => $id]);
                } else {
                    Yii::$app->session->setFlash('error', 'Ошибка при обновлении статуса.');
                }
            } else {
                Yii::$app->session->setFlash('error', 'Неверный статус.');
            }
        }

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

    public function actionQuickUpdateStatus($id, $status)
    {
        $model = EmployeeProfile::findOne($id);
        if ($model && in_array($status, array_keys(EmployeeProfile::getStatuses()))) {
            $oldStatus = $model->status;
            $model->status = $status;
            if ($model->save()) {
                Yii::$app->session->setFlash('success', "Статус анкеты успешно изменен с '$oldStatus' на '$status'.");
            } else {
                Yii::$app->session->setFlash('error', 'Ошибка при обновлении статуса.');
            }
        } else {
            Yii::$app->session->setFlash('error', 'Анкета не найдена или неверный статус.');
        }

        $referrer = Yii::$app->request->referrer;
        if (strpos($referrer, 'admin/view') !== false) {
            return $this->redirect(['view', 'id' => $id]);
        }
        
        return $this->redirect(['index']);
    }

    public function actionView($id)
    {
        $model = EmployeeProfile::findOne($id);
        if (!$model) {
            throw new \yii\web\NotFoundHttpException('Анкета не найдена.');
        }

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