<?php

class CompanyController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array(),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('index', 'deletealluser', 'deletealladmin', 'create', 'update', 'createusercompany', 'admin', 'delete', 'useradmin', 'usercompany', 'view'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array(),
                'users' => array(),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        if (Yii::app()->user->isGuest) {
            $this->redirect(Yii::app()->homeUrl);
            // IF NOT LOGGED IN, GO TO LOGIN SCREEN
        }
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    public function actionUsercompany($id) {
        if (Yii::app()->user->isGuest)
            $this->redirect(Yii::app()->homeUrl);
        $this->layout = '//layouts/column2';
        $modelCompany = Company::model()->findAllByAttributes(array('user_id' => $id));
        if ($modelCompany === null)
            Yii::app()->user->setFlash('error', "Record Not Found");
        $this->render('usercompanies', array(
            'modelCompany' => $modelCompany,
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        if (Yii::app()->user->isGuest)
            $this->redirect(Yii::app()->homeUrl);
        // Uncomment the following line if AJAX validation is needed//$this->performAjaxValidation($model);
        $model = new Company;
        $model->owner = new Owner();

        if (isset($_POST['Company'])) {
            $model->attributes = $_POST['Company'];
            $model->owner->attributes = $_POST['Owner'];
            $model->setAttribute('contacts', $_POST['Company']['contacts']);
            $email = $_POST['Owner']['email'];
            // echo $email;exit;

            $model = $this->SaveCompanyWithOwner($model, $email);
        }
        $this->render('create', array('model' => $model));
    }

    /**
     * 
     * @param Company $model
     */
    public function SaveCompanyWithOwner($model, $email) {
        if ($model->validate() & $model->owner->validate()) {


            if ($model->save()) {
                $model->owner->id = $model->id;
                $model->owner->email = $email;
                if ($model->owner->save()) {
                    $this->redirect(array('view', 'id' => $model->id));
                } else {
                    $model->owner->addError("id", "Problem in saving data. Please try again.");
                }
            } else {
                $model->addError("id", "Problem in saving data. Please try again.");
            }
        }
        return $model;
    }

    /**
     * user create compamy
     */
    public function actionCreateusercompany($id) {
        $model = new Company;
        $modelowner = new Owner();
        if (Yii::app()->user->isGuest)
            $this->redirect(Yii::app()->homeUrl);
        if (isset($_POST['Company'])) {
            $model->attributes = $_POST['Company'];
            $model->setAttribute('contacts', $_POST['Company']['contacts']);
            $modelowner->attributes = $_POST['Owner'];
            //get email
            $email = $_POST['Owner']['email'];
//             echo $email;exit;
            //=====
            $modelowner->validate();
            $model->validate();
            if ($model->validate() && $modelowner->validate()) {
                if ($model->save()) {
                    $insert_id = Yii::app()->db->getLastInsertID();

                    $modelowner->id = $insert_id;
                    $modelowner->attributes = $_POST['Owner'];

                    if ($modelowner->validate()) {
                        $modelowner->email = $email;
                        if ($modelowner->save()) {
                            $this->redirect(array('view', 'id' => $model->id));
                        } else {
                            echo 'problem in saving data ';
                            exit;
                        }
                    } else {
                        echo 'data not validated';
                        exit;
                    }
                }
            }
        }
        $this->render('createusercompany', array(
            'model' => $model,
            'user_id' => $id,
            'modelowner' => $modelowner,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {

        if (Yii::app()->user->isGuest) {
            $this->redirect(Yii::app()->homeUrl);
        }

        $model = $this->loadModel($id);

        $model->owner = Owner::model()->findByAttributes(array('id' => $id));

        if (isset($_POST['Company'])) {
            $model->attributes = $_POST['Company'];
            $model->owner->attributes = $_POST['Owner'];
            $email = $_POST['Owner']['email'];
            $model->setAttribute('contacts', $_POST['Company']['contacts']);

            $model = $this->SaveCompanyWithOwner($model, $email);
        }

        $this->render('update', array('model' => $model));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        $owner = Owner::model()->find('id=:id', array(':id' => $id));
        if($owner) $owner->delete();
        $c = $this->loadModel($id);
        if($c) $c->delete();
        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /*
     * Admin Delete all Button  
     */

    public function actionDeletealladmin() {



        $Criteria = new CDbCriteria();

        $mymodel = Company::model()->findAll($Criteria);

        if ($mymodel == NULL) {

            Yii::app()->user->setFlash('error', 'No Company Exist.');

            $this->redirect(array('admin'));
        }

        Owner::model()->deleteAll();

        Company::model()->deleteAll();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /*
     * User Delete all Button  
     */

    public function actionDeletealluser($id) {

        // echo $id; exit;


        $Criteria = new CDbCriteria();

        $mymodel = Company::model()->findAll($Criteria);

        if ($mymodel == NULL) {
        
            Yii::app()->user->setFlash('error', 'No Company Exist.');

            $this->redirect(array('useradmin', 'id' => Yii::app()->user->id));
        }

        $company = Company::model()->findAll('user_id=:user_id', array(':user_id' => $id));

        //  CVarDumper::dump($company, 10, true);exit;

        foreach ($company as $key => $value) {

            $owner = Owner::model()->find('id=:id', array(':id' => $value->id));
            if($owner) $owner->delete();
            $c = Company::model()->find('id=:id', array(':id' => $value->id));
            if($c) $c->delete();


//            echo $value->id;
//            echo '<br>';
//            exit;
            //Owner::model()->delete($value->id);
            //Company::model()->delete($value->id);
        }

// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('/company/useradmin/' . Yii::app()->user->id));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        if (Yii::app()->user->isGuest) {
            $this->redirect(Yii::app()->homeUrl);
// IF NOT LOGGED IN, GO TO LOGIN SCREEN
        }
        $dataProvider = new CActiveDataProvider('Company');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        if (Yii::app()->user->isGuest) {
            $this->redirect(Yii::app()->homeUrl);
// IF NOT LOGGED IN, GO TO LOGIN SCREEN
        }

        $model = new Company('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Company']))
            $model->attributes = $_GET['Company'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    public function actionUseradmin($id) {
        if (Yii::app()->user->isGuest) {
            $this->redirect(Yii::app()->homeUrl);
// IF NOT LOGGED IN, GO TO LOGIN SCREEN
        }

        $model = new Company('search');
        //$model  = Company::model()->findAllByAttributes(array('user_id' => $id));
        //  $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Company']))
            $model->attributes = $_GET['Company'];

        $this->render('useradminarea', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return Company the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
        $model = Company::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param Company $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'company-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
