<?php
namespace backend\modules\admin\controllers;

use Yii;
use backend\models\forms\ChangePasswordForm;
use backend\models\PasswordApi;
use backend\models\MemberIdentity;

class PasswordController extends BaseController
{
    public function actionIndex()
    {
        $model = new ChangePasswordForm();
        $this->view->title = '修改密码';
        return $this->render('index', [
            'model' => $model,
        ]);
    }

    /**
     * 修改密码
     */
    public function actionChangePassword()
    {
        $response = ['code' => 0, 'message' => '修改失败', 'data' => []];

        $model = new ChangePasswordForm();
        $model->load(Yii::$app->request->post());
        if ($model->validate()) {
            $api = new PasswordApi();
            $result = $api->changePassword($model->attributes, MemberIdentity::MEMBER_TYPE_ADMIN);
            if ($result['code'] == 1) {
                $response['code'] = 1;
                $response['message'] = '修改成功';
            } else {
                $response['message'] = $result['message'];
            }
        } else {
            $errors = $model->getErrors();
            $errors = array_values($errors);
            $response['message'] = isset($errors[0][0]) ? $errors[0][0] : '数据输入错误';
        }
        return json_encode($response);
    }
}