<?php
/**
 *
 */
namespace modules\forms\controllers;

use Yii;
use yii\db\Expression;
use common\models\Base;
use backend\models\User;
use modules\forms\models\sub\{ServiceItem, ServiceLifeJacketBulk};
use modules\forms\models\{Forms, Formssearch};
use backend\controllers\FormsController as BaseController;
use yii\filters\VerbFilter;
use yii\helpers\{Arrayhelper, Url};
use yii\web\{Controller, NotFoundHttpException};

/**
 * ActivitiesController implements the CRUD actions for Activities model.
 */
class DefaultController extends BaseController
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Activities models.
     * @return mixed
     */
    public function actionIndex()
    {
        $type = Yii::$app->request->get('type');
        $searchModel = new Formssearch();
        $searchModel->form = $type;
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * Displays a single model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id, $form) {
        if($model = $this->findModel($id, $form)){
            return $this->render(property_exists($model, 'viewpath') ? $model->viewpath : 'view', [
                'model' => $model,
            ]);
        } else {
            throw new NotFoundHttpException('The was a problem with the data.');
        }
    }
    /**
     * Displays a single model for PDFing.
     * @param integer $id
     * @return mixed
     */
    public function actionPdfview($id, $form) {
        if($model = $this->findModel($id, $form)){
            return $this->render(property_exists($model, 'viewpath') ? $model->viewpath : 'view', [
                'model' => $model,
            ]);
        } else {
            throw new NotFoundHttpException('The was a problem with the data.');
        }
    }

    
    public function actionPdf($id, $form){
        if($model = $this->findModel($id, $form)){
            return $model->pdf();
            } else {
            throw new NotFoundHttpException('The was a problem with the data.');
        }
    }
    public function actionDelete($id, $form){
        if(($model = Forms::findOne(['id' =>$id, 'form' => $form]))){
            return $model->delete();
        } else {
            throw new NotFoundHttpException('The was a problem with the data.');
        }
    }

    /**
     * Creates a new Form model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($form)
    {
        $form = str_replace(' ', '', UcWords(str_replace('-', ' ', $form)));
        $formclass = '\\modules\\forms\\models\\sub\\'.$form;
        global $formmodel;
        $formModel = new Forms(['formclass' => $form, 'id' => Forms::tempid()]);
        $formModel->language = 'en';
        $formModel->form = $form;
        $model = $formModel->data;
        
        $items = property_exists($model, 'items') ? $model->items : false;
        $result = false;
        if(Yii::$app->request->isPost == true){
            //$capture = Recaptcha::recaptcha(Yii::$app->request->post('g-recaptcha'));
            //$formModel->captchadata = json_encode($capture);
            $result = true; // $capture['result'];
            
        }
        if( property_exists($model, 'items') && Yii::$app->request->isPost == true){
            $items = $model->items;
            yii\base\DynamicModel::loadMultiple($items, Yii::$app->request->post());
            $result = yii\base\DynamicModel::ValidateMultiple($items);
            $model->items = $items;
        }
        if ($result == true && $model->load(Yii::$app->request->post()) && $model->validate() && $formModel->save()) {
            method_exists ($model, 'sendMail') == true ? $model->sendMail() : false;
            $model->hasMethod('PostProcess') ? $model->PostProcess(Yii::$app->request->post()) : false;
            return $this->redirect(['/forms/view', 'form' => $form, 'id' => $formModel->id]);
        } else {
            return $this->render('@modules/forms/views/default/'.$model->filename, [
                'model' => $model,
                'items' => $items,
                'formModel' => $formModel,
            ]);
        }
    }

        /**
     * Finds the model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return  the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id, $form)
    {
        $class = "\\modules\\forms\\models\\sub\\$form";
        if (($model = $class::findOne(['id' => $id]) ) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    public function actionUpdate($id, $form)
    {
        $model = $this->findModel($id, $form);
        if($model->load(yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['/forms/view', 'id' => $model->id, 'form' => $form]);
        } else {
            return $this->render('@modules/forms/views/default/'.$model->filename, [
                'model' => $model,
            ]);
        }
    }

    public function actionAdditem(){
        $count = Yii::$app->request->get('count');
        $item = new ServiceItem();
        $form = \yii\widgets\ActiveForm::begin();
        return $this->renderAjax($item->filename, ['model' => $item, 'form' => $form, 'key' => $count]);
    }
    public function actionAddbulkitem(){
        $id = Yii::$app->request->get('id');
        $form = \yii\widgets\ActiveForm::begin();
        return $this->renderAjax('_item_bulk', ['id' => $id, 'form' => $form]);
    }

}