<?php
namespace api\modules\v1\controllers;

use yii\rest\Controller;
use Yii;
use yii\web\Response;
use api\modules\v1\components\Helpers;

class DriversController extends Controller
{
    /* public $modelClass = '\common\models\UserDriver'; */
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            /* pass access-token as a parameter */
            'class' => yii\filters\auth\CompositeAuth::className(),
            'authMethods' => [
                \yii\filters\auth\QueryParamAuth::className(),
                \yii\filters\auth\HttpBearerAuth::className(),
            ]
        ];
        $behaviors['contentNegotiator']['formats']['application/json'] = Response::FORMAT_JSON;
        return $behaviors;
    }

    /* public function actions() */
    /* { */
    /*     /1* Unset rest controller index default behavior *1/ */
    /*     $actions = parent::actions(); */
    /*     unset($actions['index']); */
    /*     unset($actions['create']); */
    /*     unset($actions['update']); */

    /*     return $actions; */
    /* } */

    /**
    * @api {get} /drivers Drivers
    * @apiGroup Drivers
    * @apiSuccess {Object[]} drivers Drivers
    * @apiParam {Integer} condo_id Condo ID
    * @apiSuccessExample {json} Success
    *   HTTP/1.1 200 OK
    *   [
    *       {
    *       "id": 6,
    *       "condo_id": 19,
    *       "user_id": 656,
    *       "photo": null,
    *       "name": "Johon Smith",
    *       "nric": "123456",
    *       "nationality_id": 120,
    *       "contact_no": "123456",
    *       ...
    *       },
    *   ]
    * @apiSuccessExample {json} Success
    *   HTTP/1.1 200 OK
    *   {
    *       "message": "empty"
    *   }
    */
    public function actionIndex()
    {
        $user_id = Yii::$app->user->id;
        $condo_id = Yii::$app->request->get('condo_id');
        $drivers = \common\models\UserDriver::find()
            ->where([
//                'user_id' => [$user_id],
                'condo_id' => [$condo_id],
        ])->all();
        if (count($drivers) == 0) {
            return ['message' => 'empty'];
        }
        return $drivers;
    }

    /**
    * @api {post} /drivers/ Create a new driver record
    * @apiGroup Drivers
    * @apiSuccess {String} message A message of a new record has been created or not
    * @apiParam {Integer} condo_id Condo ID
    * @apiParam {String} name Driver's name
    * @apiParam {String} nric Driver's nric
    * @apiParam {Integer} nationality_id Driver's nationality's id
    * @apiParam {String} contact_no Driver's contact number
    * @apiSuccessExample {json} Success
    *   HTTP/1.1 200 OK
    *   [
    *       {
    *       "id": 6,
    *       "condo_id": 19,
    *       "user_id": 656,
    *       "photo": null,
    *       "name": "Johon Smith",
    *       "nric": "123456",
    *       "nationality_id": 120,
    *       "contact_no": "123456",
    *       ...
    *       },
    *   ]
    * @apiErrorExample {json} Failed
    *   HTTP/1.1 200 OK
    *   {
    *       "message": "failed"
    *   }
     */
    public $driverPhotoPath = '../../frontend/web/upload/driver/';
    public function actionCreate()
    {
        $model = new \common\models\UserDriver();
        $model->user_id = Yii::$app->user->id;
        $model->condo_id = Yii::$app->request->post('condo_id');
        $model->name = Yii::$app->request->post('name');
        $model->nric = Yii::$app->request->post('nric');
        $model->nationality_id = Yii::$app->request->post('nationality_id');
        $model->contact_no = Yii::$app->request->post('contact_no');

        /* photo upload */
        if($_FILES) {
            $postdata = fopen($_FILES['file']['tmp_name'], 'r');
            $extension = substr($_FILES['file']['name'], strrpos($_FILES['file']['name'], '.'));

            $filename = uniqid(). $extension;
            $filepath = $this->driverPhotoPath . $filename;

            $fp = fopen($filepath, "w");
            while($data = fread($postdata, 1024))
                fwrite($fp, $data);

            fclose($fp);
            fclose($postdata);
            $model->photo = $filename;
        }

        if ($model->save()) {
        	Helpers::addtolog('success','Create new driver', Yii::$app->user->id, $model->condo_id, null);
            return $model;
        } else {
            return ['error' => $model->getErrors()];
        }
    }

    /**
    * @api {put} /drivers/ Update a new driver record
    * @apiGroup Drivers
    * @apiSuccess {String} message A message of a new record has been created or not
    * @apiParam {Integer} condo_id Condo ID
    * @apiParam {String} name Driver's name
    * @apiParam {String} nric Driver's nric
    * @apiParam {Integer} nationality_id Driver's nationality's id
    * @apiParam {String} contact_no Driver's contact number
    * @apiSuccessExample {json} Success
    *   HTTP/1.1 200 OK
    *   [
    *       {
    *       "id": 6,
    *       "condo_id": 19,
    *       "user_id": 656,
    *       "photo": null,
    *       "name": "Johon Smith",
    *       "nric": "123456",
    *       "nationality_id": 120,
    *       "contact_no": "123456",
    *       ...
    *       },
    *   ]
    * @apiErrorExample {json} Failed
    *   HTTP/1.1 200 OK
    *   {
    *       "message": "failed"
    *   }
    */
    public function actionUpdate($id)
    {
        $model = \common\models\UserDriver::findOne($id);
        /* $model->user_id = Yii::$app->user->id; */
        /* $model->condo_id = Yii::$app->request->post('condo_id'); */

        if(Yii::$app->request->post('name'))
            $model->name = Yii::$app->request->post('name');
        if(Yii::$app->request->post('nric'))
            $model->nric = Yii::$app->request->post('nric');
        if(Yii::$app->request->post('nationality_id'))
            $model->nationality_id = Yii::$app->request->post('nationality_id');
        if(Yii::$app->request->post('contact_no'))
            $model->contact_no = Yii::$app->request->post('contact_no');

        /* photo upload */
        if($_FILES) {
            $postdata = fopen($_FILES['file']['tmp_name'], 'r');
            $extension = substr($_FILES['file']['name'], strrpos($_FILES['file']['name'], '.'));

            $filename = uniqid(). $extension;
            $filepath = $this->driverPhotoPath . $filename;

            $fp = fopen($filepath, "w");
            while($data = fread($postdata, 1024))
                fwrite($fp, $data);

            fclose($fp);
            fclose($postdata);
            $model->photo = $filename;
        }

        if($model->save()) {
        	Helpers::addtolog('success','Updated driver id='.$id, Yii::$app->user->id, null, null);
            return $model;
        } else {
            return ['error' => $model->getErrors()];
        }
    }

    public function actionDelete($id) {
        $condo_id = Yii::$app->request->get('condo_id');
        $model = \common\models\UserDriver::find()
                ->where ([
                    'id' => [$id],
                    'user_id' => [Yii::$app->user->id],
                    'condo_id' => $condo_id,
                ])
                ->one();
        if($model->delete()) {
			Helpers::addtolog('success', 'Deleted driver id='.$id, Yii::$app->user->id, $condo_id, null);
            return ['message' => true];
        } else {
            return ['message' => false];
        }
    }
}
