<?php

namespace app\controllers;

use Yii;
use app\base\Model;
use app\models\Contact;
use app\models\Contactareas;
use app\models\Contactclients;
use app\models\Contactpartners;
use app\models\ContactSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\web\Response;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;

/**
 * ContactController implements the CRUD actions for Contact model.
 */
class ContactController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['index', 'create', 'update', 'view', 'delete'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Contact models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ContactSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

    /**
     * Displays a single Contact model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Contact model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    /*
    public function actionCreate()
    {
        $model = new Contact();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->contact_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
    */

    public function actionCreate()
    {
        $model = new Contact;
        $modelareas = [new Contactareas];
        $modelclients = [new Contactclients];
        $modelpartners = [new Contactpartners];

        if ($model->load(Yii::$app->request->post())) {

            $modelclients = Model::createMultiple(Contactclients::classname());
            Model::loadMultiple($modelclients, Yii::$app->request->post());

            $modelareas = Model::createMultiple(Contactareas::classname());
            Model::loadMultiple($modelareas, Yii::$app->request->post());

            $modelpartners = Model::createMultiple(Contactpartners::classname());
            Model::loadMultiple($modelpartners, Yii::$app->request->post());
            
            $count = count($modelclients) - 1;
            if(isset($modelclients[$count]->attributes)) {
                $model->contact_q1 = $modelclients[$count]->contact_client_q1;
                $model->contact_q2 = $modelclients[$count]->contact_client_q2;
                $model->contact_q3 = $modelclients[$count]->contact_client_q3;
                // $model->contact_q4 = $modelclients[$count]->contact_client_q4;
                // $model->contact_q5 = $modelclients[$count]->contact_client_q5;
            }
            
            $count = count($modelareas) - 1;
            if(isset($modelareas[$count]->attributes)) {
                // $model->contact_q1 = $modelareas[$count]->contact_client_q1;
                // $model->contact_q2 = $modelareas[$count]->contact_client_q2;
                // $model->contact_q3 = $modelareas[$count]->contact_client_q3;
                $model->contact_q4 = $modelareas[$count]->contact_area_q1;
                $model->contact_q5 = $modelareas[$count]->contact_area_q2;
            }
            $count = count($modelpartners) - 1;
            if(isset($modelpartners[$count]->attributes)) {
                $model->contact_q6 = $modelpartners[$count]->contact_partner_q1;
                $model->contact_q7 = $modelpartners[$count]->contact_partner_q2;
                $model->contact_q8 = $modelpartners[$count]->contact_partner_q3;
                $model->contact_q9 = $modelpartners[$count]->contact_partner_q4;
            }

            // ajax validation
            if (Yii::$app->request->isAjax) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                $valids = ActiveForm::validate($model);
                $validareas = ActiveForm::validateMultiple($modelareas);
                $validclients = ActiveForm::validateMultiple($modelclients);
                $validpartners = ActiveForm::validateMultiple($modelpartners);
                // return $valids;
                return ArrayHelper::merge(
                    $valids,
                    $validareas,
                    $validclients,
                    $validpartners
                );
            }
            
            $valid = $model->validate();
            $valid1 = Model::validateMultiple($modelclients);
            $valid2 = Model::validateMultiple($modelareas);
            $valid = Model::validateMultiple($modelpartners) & $valid & $valid1 & $valid2;

            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();

                try {
                    if($model->save()) {
                        foreach ($modelclients as $modelAddress) {
                            $modelAddress->contact_id = $model->contact_id;
                            if (! ($flag = $modelAddress->save(false))) {
                                $transaction->rollBack();
                                break;
                            }
                        }
                        foreach ($modelareas as $modelAddress) {
                            $modelAddress->contact_id = $model->contact_id;
                            if (! ($flag = $modelAddress->save(false))) {
                                $transaction->rollBack();
                                break;
                            }
                        }
                        foreach ($modelpartners as $modelAddress) {
                            $modelAddress->contact_id = $model->contact_id;
                            if (! ($flag = $modelAddress->save(false))) {
                                $transaction->rollBack();
                                break;
                            }
                        }

                        if ($flag) {
                            $transaction->commit();
                            Yii::$app->session->setFlash('success', "Records Created Successful");
                            // return $this->redirect(['/'.Yii::$app->controller->id]);
                            return $this->redirect(['view', 'id' => $model->contact_id]);
                        }
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }
        }
        
        return $this->render('create', [
            'model' => $model,
            'modelareas' => (empty($modelareas[0])) ? [new Contactclients] : $modelareas,
            'modelclients' => (empty($modelclients[0])) ? [new Contactclients] : $modelclients,
            'modelpartners' => (empty($modelpartners[0])) ? [new Contactpartners] : $modelpartners,
        ]);
    }

    /**
     * Updates an existing Contact model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    /*
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->contact_id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }
    */

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $modelareas = Contactareas::find()->where(['contact_id' => $id])->all();
        $modelclients = Contactclients::find()->where(['contact_id' => $id])->all();
        $modelpartners = Contactpartners::find()->where(['contact_id' => $id])->all();

        if ($model->load(Yii::$app->request->post())) {

            $oldIDs = ArrayHelper::map($modelclients, 'contact_client_id', 'contact_client_id');
            $modelclients = Model::createMultiple(Contactclients::classname(), $modelclients, 'contact_client_id');
            Model::loadMultiple($modelclients, Yii::$app->request->post());
            $clientDeletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelclients, 'contact_client_id', 'contact_client_id')));

            $oldIDs = ArrayHelper::map($modelareas, 'contact_area_id', 'contact_area_id');
            $modelareas = Model::createMultiple(Contactareas::classname(), $modelareas, 'contact_area_id');
            Model::loadMultiple($modelareas, Yii::$app->request->post());
            $areaDeletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelareas, 'contact_area_id', 'contact_area_id')));

            $poldIDs = ArrayHelper::map($modelpartners, 'contact_partner_id', 'contact_partner_id');
            $modelpartners = Model::createMultiple(Contactpartners::classname(), $modelpartners, 'contact_partner_id');
            Model::loadMultiple($modelpartners, Yii::$app->request->post());
            $partnerDeletedIDs = array_diff($poldIDs, array_filter(ArrayHelper::map($modelpartners, 'contact_partner_id', 'contact_partner_id')));

            $count = count($modelclients) - 1;
            if(isset($modelclients[$count]->attributes)) {
                $model->contact_q1 = $modelclients[$count]->contact_client_q1;
                $model->contact_q2 = $modelclients[$count]->contact_client_q2;
                $model->contact_q3 = $modelclients[$count]->contact_client_q3;
                // $model->contact_q4 = $modelclients[$count]->contact_client_q4;
                // $model->contact_q5 = $modelclients[$count]->contact_client_q5;
            }
            $count = count($modelareas) - 1;
            if(isset($modelareas[$count]->attributes)) {
                // $model->contact_q1 = $modelareas[$count]->contact_client_q1;
                // $model->contact_q2 = $modelareas[$count]->contact_client_q2;
                // $model->contact_q3 = $modelareas[$count]->contact_client_q3;
                $model->contact_q4 = $modelareas[$count]->contact_area_q1;
                $model->contact_q5 = $modelareas[$count]->contact_area_q2;
            }
            $count = count($modelpartners) - 1;
            if(isset($modelpartners[$count]->attributes)) {
                $model->contact_q6 = $modelpartners[$count]->contact_partner_q1;
                $model->contact_q7 = $modelpartners[$count]->contact_partner_q2;
                $model->contact_q8 = $modelpartners[$count]->contact_partner_q3;
                $model->contact_q9 = $modelpartners[$count]->contact_partner_q4;
            }

            // ajax validation
            if (Yii::$app->request->isAjax) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                $valids = ActiveForm::validate($model);
                $validclients = ActiveForm::validateMultiple($modelclients);
                $validpartners = ActiveForm::validateMultiple($modelpartners);
                // return $valids;
                return ArrayHelper::merge(
                    $valids,
                    $validclients,
                    $validpartners
                );
            }

            $valid = $model->validate();
            $valid1 = Model::validateMultiple($modelclients);
            $valid = Model::validateMultiple($modelpartners) & $valid & $valid1;

            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();

                try {
                    if($model->save()) {
                        if (! empty($clientDeletedIDs)) {
                            Contactclients::deleteAll(['contact_client_id' => $clientDeletedIDs]);
                        }
                        foreach ($modelclients as $modelAddress) {
                            $modelAddress->contact_id = $model->contact_id;
                            if (! ($flag = $modelAddress->save(false))) {
                                $transaction->rollBack();
                                break;
                            }
                        }
                        if (! empty($areaDeletedIDs)) {
                            Contactareas::deleteAll(['contact_area_id' => $areaDeletedIDs]);
                        }
                        foreach ($modelareas as $modelAddress) {
                            $modelAddress->contact_id = $model->contact_id;
                            if (! ($flag = $modelAddress->save(false))) {
                                $transaction->rollBack();
                                break;
                            }
                        }
                        if (! empty($partnerDeletedIDs)) {
                            Contactpartners::deleteAll(['contact_partner_id' => $partnerDeletedIDs]);
                        }
                        foreach ($modelpartners as $modelAddress) {
                            $modelAddress->contact_id = $model->contact_id;
                            if (! ($flag = $modelAddress->save(false))) {
                                $transaction->rollBack();
                                break;
                            }
                        }

                        if ($flag) {
                            $transaction->commit();
                            Yii::$app->session->setFlash('success', "Records Created Successful");
                            // return $this->redirect(['/'.Yii::$app->controller->id]);
                            return $this->redirect(['view', 'id' => $model->contact_id]);
                        }
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }
        }

        return $this->render('update', [
            'model' => $model,
            'modelareas' => (empty($modelareas)) ? [new Contactareas] : $modelareas,
            'modelclients' => (empty($modelclients)) ? [new Contactclients] : $modelclients,
            'modelpartners' => (empty($modelpartners)) ? [new Contactpartners] : $modelpartners,
        ]);
    }

    /**
     * Deletes an existing Contact model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['/'.Yii::$app->controller->id]);
    }

    /**
     * Finds the Contact model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Contact the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Contact::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
