<?php

namespace frontend\controllers;

use common\libs\MyLib;
use common\models\PeerPhoneT;
use common\models\UserT;
use Yii;
use yii\web\Response;

class PeerController extends BaseController
{
    public function actionPhoneIndex()
    {
        $request = Yii::$app->request;
        $phone = $request->get('phone');

        $query = PeerPhoneT::find();
        if($phone != '') {
            $query = $query->andWhere('phone="'.$phone.'"');;
        }
        $items = $query->all();

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

    public function actionPhoneEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        if($id > 0) {
            $info = PeerPhoneT::findOne(['id'=>$id]);
        } else {
            $info = new PeerPhoneT();
        }

        return $this->render('phone-edit',[
            'info' => $info
        ]);
    }

    public function actionPhoneSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost) {
            $id = $request->post('id',0);
            $phone = $request->post('phone');

            if($phone == '') {
                $result['msg'] = '请输入电话号码!';
                return $result;
            }

            $row = null;
            if($id > 0) {
                $row = PeerPhoneT::findOne(['id'=>$id]);
            } else {
                $row = new PeerPhoneT();
            }
            $row->phone = $phone;
            $row->save();

            $result['success'] = true;
            $result['msg'] = '保存成功';
        }
        return $result;
    }

    public function actionPhoneDelete()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '删除失败';

        if($request->isPost) {
            $id = $request->post('id',0);

            if($id > 0) {
                $row = PeerPhoneT::findOne(['id'=>$id]);
                $row->delete();

                $result['success'] = true;
                $result['msg'] = '删除成功';
            }
        }
        return $result;
    }
}
