<?php

class UserController 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('indexsearch', 'by_phone'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('index', 'create', 'view', 'update', 'uploadcompany', 'excel', 'delete', 'exportexceladmin', 'exportexceluser'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin'),
                'users' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

//fin del método actionExcel

    public function actionExportexceluser() {


        $Criteria = new CDbCriteria();
        $user_id = Yii::app()->user->id;
        $mymodel = Company::model()->findAll('user_id=:user_id', array(':user_id' => $user_id));
        if ($mymodel == NULL) {
            Yii::app()->user->setFlash('error', 'No Company Exist.');

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



        $path = Yii::app()->basePath . '/../uploads/excelfiles/';
       // $user_id = Yii::app()->user->id;
        $company_model = Company::model()->findAll('user_id=:user_id', array(':user_id' => $user_id));
        $count = 2;
        $objPHPExcel = Yii::app()->excel;
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', 'Name')
                ->setCellValue('B1', 'Adress')
                ->setCellValue('C1', 'Phone')
                ->setCellValue('D1', 'City')
                ->setCellValue('E1', 'State')
                ->setCellValue('F1', 'ZipCode')
                ->setCellValue('G1', 'Notes')
                ->setCellValue('H1', 'First Name')
                ->setCellValue('I1', 'Last Name')
                ->setCellValue('J1', 'Date of Birth')
                ->setCellValue('K1', 'Position')
                ->setCellValue('L1', 'Contact Phone')
                ->setCellValue('M1', 'E-Mail')
                ->setCellValue('N1', 'Notes');
        foreach ($company_model as $value) {
            //deal owner
            $getOwnerFkey = $value->id;
            $owner_model = Owner::model()->find('id=:id', array(':id' => $getOwnerFkey));
            //end deal owner
            $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A' . $count . '', $value->name)
                    ->setCellValue('B' . $count . '', $value->adress)
                    ->setCellValue('C' . $count . '', $value->phone)
                    ->setCellValue('D' . $count . '', $value->city)
                    ->setCellValue('E' . $count . '', $value->state)
                    ->setCellValue('F' . $count . '', $value->zip)
                    ->setCellValue('G' . $count . '', $value->notes)
                    ->setCellValue('H' . $count . '', $owner_model->firstname)
                    ->setCellValue('I' . $count . '', $owner_model->lastname)
                    ->setCellValue('J' . $count . '', $owner_model->dob)
                    ->setCellValue('K' . $count . '', $owner_model->position)
                    ->setCellValue('L' . $count . '', $owner_model->phone)
                    ->setCellValue('M' . $count . '', $owner_model->email)
                    ->setCellValue('N' . $count . '', $owner_model->notes);
            $count++;
            $objPHPExcel->getActiveSheet()->setTitle('SimpleFahad');
            $objPHPExcel->setActiveSheetIndex(0);
            ob_end_clean();
            ob_start();
//            header('Content-Type: application/vnd.ms-excel');
//            header('Content-Disposition: attachment;filename="' . $path . 'fahadtest.xls"');
//            header('Cache-Control: max-age=0');
//            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
//            $objWriter->save('php://output');
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . 'companies.xlsx"');
            header('Cache-Control: max-age=0');
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save('php://output');
        }
    }

    public function actionExportexceladmin() {

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

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


        $path = Yii::app()->basePath . '/../uploads/excelfiles/';
        $user_id = Yii::app()->user->id;
        $company_model = Company::model()->findAll();
        $count = 2;
        $objPHPExcel = Yii::app()->excel;
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', 'Name')
                ->setCellValue('B1', 'Adress')
                ->setCellValue('C1', 'Phone')
                ->setCellValue('D1', 'City')
                ->setCellValue('E1', 'State')
                ->setCellValue('F1', 'ZipCode')
                ->setCellValue('G1', 'Notes')
                ->setCellValue('H1', 'First Name')
                ->setCellValue('I1', 'Last Name')
                ->setCellValue('J1', 'Date of Birth')
                ->setCellValue('K1', 'Position')
                ->setCellValue('L1', 'Contact Phone')
                ->setCellValue('M1', 'E-Mail')
                ->setCellValue('N1', 'Notes');
        foreach ($company_model as $value) {
            $getOwnerFkey = $value->id;
            $owner_model = Owner::model()->find('id=:id', array(':id' => $getOwnerFkey));
            //CVarDumper::dump($owner_model->id, 10, TRUE); exit; 
            $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A' . $count . '', $value->name)
                    ->setCellValue('B' . $count . '', $value->adress)
                    ->setCellValue('C' . $count . '', $value->phone)
                    ->setCellValue('D' . $count . '', $value->city)
                    ->setCellValue('E' . $count . '', $value->state)
                    ->setCellValue('F' . $count . '', $value->zip)
                    ->setCellValue('G' . $count . '', $value->notes)
                    ->setCellValue('H' . $count . '', $owner_model->firstname)
                    ->setCellValue('I' . $count . '', $owner_model->lastname)
                    ->setCellValue('J' . $count . '', $owner_model->dob)
                    ->setCellValue('K' . $count . '', $owner_model->position)
                    ->setCellValue('L' . $count . '', $owner_model->phone)
                    ->setCellValue('M' . $count . '', $owner_model->email)
                    ->setCellValue('N' . $count . '', $owner_model->notes);
            $count++;
            $objPHPExcel->getActiveSheet()->setTitle('SimpleFahad');
            $objPHPExcel->setActiveSheetIndex(0);
            ob_end_clean();
            ob_start();
//            header('Content-Type: application/vnd.ms-excel');
//            header('Content-Disposition: attachment;filename="' . $path . 'fahadtest.xls"');
//            header('Cache-Control: max-age=0');
//            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
//            $objWriter->save('php://output');
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . 'companies.xlsx"');
            header('Cache-Control: max-age=0');
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save('php://output');
        }
    }

    public function actionUploadcompany() {
        $id = Yii::app()->user->id;
        $path = Yii::app()->basePath . '/../uploads/excelfiles';
        if (!is_dir($path)) {
            mkdir($path);
        }
        $this->render('uploadcompany', array('id' => $id));
    }

    public function actionExcel() {
        $uploadPath = Yii::app()->basePath . '/../uploads/excelfiles/';
        $model = new User();
        $user_id = Yii::app()->user->id;
        $objPHPExcel = Yii::app()->excel;
        $myfile = $uploadPath . $_SESSION['fileNameinSess'];
        $uploadPath = Yii::app()->basePath . '/../uploads/excelfiles/';
        $model = new User();
        $user_id = Yii::app()->user->id;
        $myfile = $uploadPath . $_SESSION['fileNameinSess'];
        unset($_SESSION['fileNameinSess']);
        $objReader = $objPHPExcel->readExcel2007();
        $objPHPExcel = $objReader->load($myfile); //ARCHIVE excel2007 dir 
        $lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();
        //echo 'Last Row is' . $lastRow; //----------------------->5
        $highestColumm = $objPHPExcel->getActiveSheet()->getHighestColumn();
        //echo 'Last Column is ' . $highestColumm; //---------->H
        $highestColumm = $objPHPExcel->setActiveSheetIndex(0)->getHighestColumn(); // e.g. "EL" 
        $highestRow = $objPHPExcel->setActiveSheetIndex(0)->getHighestRow();
        $userStatus = Yii::app()->user->getState('__statusAdmin'); // get user status
        $highestColumm++;
        $count = 1;
//        $dateNumber = $objPHPExcel->setActiveSheetIndex(0)->getCell("J2")->getvalue();
//        $dateText = PHPExcel_Shared_Date::ExcelToPHP($dateNumber);
//        $dateFormattedString = gmdate("Y-m-d\TH:i:s\Z", $dateText);        
//        CVarDumper::dump($dateFormattedString, 10, true);


        for ($row = 2; $row < $highestRow + 1; $row++) {
            $dataset = array();
            for ($column = 'A'; $column != $highestColumm; $column++) {
                //($column == 'J')?CVarDumper::dump($objPHPExcel->setActiveSheetIndex(0)->getCell($column . $row), 10, true):"";
                $dataset[] = $objPHPExcel->setActiveSheetIndex(0)->getCell($column . $row)->getValue();
                //it is for date
                $dateCellName = 'J' . $row;
                $dateNumber = $objPHPExcel->setActiveSheetIndex(0)->getCell($dateCellName)->getvalue();
                $dateText = PHPExcel_Shared_Date::ExcelToPHP($dateNumber);
                $dateFormattedString = gmdate("Y-m-d", $dateText);
                //end date
            }
            $companyname = $dataset[0];   //Name
            $adress = $dataset[1]; // ADRESS
            $phone = $dataset[2]; //PHONE
            $city = $dataset[3]; //CITY
            $state = $dataset[4];  //STATE
            $zip = $dataset[5];

            //notes
            if ($dataset[6] == '')
                $notes = 'N/A';
            else {
                $notes = $dataset[6];
            }
            //===============
//            echo '<br>';
//            echo 'company name is ' .  $companyname;
//            echo '<br>';
//            echo ' address is ' . $adress;
//            echo '<br>';
//            echo 'phone is '. $phone;
//            echo '<br>';
//            echo  'city is '.$city;
//            echo '<br>';
//            echo 'state is ' . $state;
//            echo '<br>';
//            echo 'zip is '.$zip;
//            echo '<br>';
//            echo 'Notes are'.$notes;
//            exit;
            ///////////OWNER//////////////////////
            $firstname = $dataset[7]; //first name
            $lastname123 = $dataset[8]; //lastname
            $dob = $dateFormattedString;
            $position = $dataset[10]; //position
            $phoneOwner = $dataset[11];
            //owner email
            if ($dataset[12] == '')
                $email = 'N/A';
            else {
                $email = $dataset[12];
            }
            //owner email
            if ($dataset[13] == '')
                $ownernotes = 'N/A';
            else {
                $ownernotes = $dataset[13];
            }
            //get max id of company
            $maxOrderNumber = Yii::app()->db->createCommand()
                    ->select('max(id) as max')
                    ->from('company')
                    ->queryScalar();
            $compMaxID = $maxOrderNumber + 1;
//            echo $compMaxID;
//            exit;
            //====================

            $model = new Company();
            $model->id = $compMaxID;
            $model->user_id = $user_id;
            $model->name = $companyname;
            $model->adress = $adress;
            $model->phone = $phone;
            $model->city = $city;
            $model->state = $state;
            $model->zip = $zip;
            $model->notes = $notes;
            if ($model->validate()) {
                $Owner = new Owner();
                $Owner->id = $compMaxID;
                $Owner->firstname = $firstname;
                $Owner->lastname = $lastname123;
                $Owner->dob = $dob;
                $Owner->position = $position;
                $Owner->phone = $phoneOwner;
                $Owner->email = $email;
                $Owner->notes = $ownernotes;
                //Owner Section Starts
                if ($Owner->validate()) {
                    $model->save();
                    $Owner->save();
                } else {
                    //check user
                    if ($userStatus == 'Admin') {
                        Yii::app()->user->setFlash('error', "Data Not Validated! Please Enter Correct Format");
                        $this->redirect(array('/company/admin/'));
                    } else {
                        Yii::app()->user->setFlash('error', "Data Not Validated! Please Enter Correct Format");
                        $this->redirect(array('/company/useradmin/', 'id' => Yii::app()->user->id));
                    }
                    //end check user
                }
                //Owner Section Ends
            } else {
                //check if company data is not validated
                //check user
                if ($userStatus == 'Admin') {
                    Yii::app()->user->setFlash('error', " Data Not Validated! Please Enter Correct Format");
                    $this->redirect(array('/company/admin/'));
                } else {
                    Yii::app()->user->setFlash('error', "Data Not Validated! Please Enter Correct Format");
                    $this->redirect(array('/company/useradmin/', 'id' => Yii::app()->user->id));
                }
                //end check user
            }
        }
        ob_end_clean();
        ob_start();
        header('Content-Type: application/vnd.ms-excel');
        // header('Content-Disposition: attachment;filename="' . $path . 'fahadtest.xls"');
        header('Cache-Control: max-age=0');

        unlink($myfile);
        $lastID = Yii::app()->db->getLastInsertId(); // HERE IT IS!
        Yii::app()->controller->redirect(array('/user/view/', 'id' => $user_id));
        exit;        //          
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $company_model = Company::model()->findAll('user_id=:user_id', array(':user_id' => $id));
        $this->render('view', array(
            'model' => $this->loadModel($id),
            'company_model' => $company_model
        ));
    }

    public function actionIndexsearch() {
        $this->layout = '//layouts/column1';
        //$model = new Owner;
        $model = new User();
        if (isset($_POST['User'])) {
            $phone = $_POST['User']['phone'];
            $this->redirect(array('by_phone', 'phone' => $phone));
        }
        $this->render('indexsearch', array(
            'model' => $model,
        ));
    }

    /* render to search page only */

    public function actionby_phone($phone) {

        $this->layout = '//layouts/column1';


        if (isset($_POST['User'])) {
            $phone = $_POST['User']['phone'];
            $this->redirect(array('by_phone', 'phone' => $phone));
        }
        $modelCompany = Company::model()->findAllByAttributes(array('phone' => $phone));
        if ($modelCompany === null) {
            Yii::app()->user->setFlash('error', "Record Not Found");
            $this->redirect('indexsearch');
        }
//        $company_model = Company::model()->findAllByAttributes(array('user_id' => $modelCompany->id));
//        $company_model_attribs = $company_model->getAttributes();        
//        $model = User::model()->findAllByAttributes(array('id'=>$company_model->id));//'id=:id', array(':id' => $company_model->id));
        $this->render('searchphone', array(
            'modelCompany' => $modelCompany,
        ));
    }

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

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

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

    /**
     * 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) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $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) {
        $this->loadModel($id)->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'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('User');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new User('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['User']))
            $model->attributes = $_GET['User'];

        $this->render('admin', 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 User the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
        $model = User::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

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

}
