<?php



class StoFilterController extends AdminController
{

    public function actionIndex(){
        $this->render('index', array(

        ));

    }



    public function getXLS($xls){

        // get a reference to the path of PHPExcel classes
        $phpExcelPath = Yii::getPathOfAlias('ext');




        // Turn off our amazing library autoload
        spl_autoload_unregister(array('YiiBase','autoload'));

        //
        // making use of our reference, include the main class
        // when we do this, phpExcel has its own autoload registration
        // procedure (PHPExcel_Autoloader::Register();)
        include($phpExcelPath . DIRECTORY_SEPARATOR . 'PHPExcel.php');

        // Create new PHPExcel object
        $objPHPExcel = new PHPExcel();

        $objPHPExcel = PHPExcel_IOFactory::load($xls);

        $count = $objPHPExcel->getSheetCount();

        $fullArray = array();
        for($i =0; $i<$count; $i++){

            $objPHPExcel->setActiveSheetIndex($i);
            $aSheet = $objPHPExcel->getActiveSheet();



            //этот массив будет содержать массивы содержащие в себе значения ячеек каждой строки
            $array = array();
            //получим итератор строки и пройдемся по нему циклом
            foreach($aSheet->getRowIterator() as $row){
                //получим итератор ячеек текущей строки
                $cellIterator = $row->getCellIterator();
                //пройдемся циклом по ячейкам строки
                //этот массив будет содержать значения каждой отдельной строки
                $item = array();
                foreach($cellIterator as $cell){
                    //заносим значения ячеек одной строки в отдельный массив
                    array_push($item,  $cell->getCalculatedValue());
                }
                //заносим массив со значениями ячеек отдельной строки в "общий массв строк"
                array_push($array, $item);
            }

            array_push($fullArray,$array);
        }




        //
        // Once we have finished using the library, give back the
        // power to Yii...
        spl_autoload_register(array('YiiBase','autoload'));

        return $fullArray;
    }

    public function saveParserData($array){
        foreach($array as $sto_filter){

            $sto_filter_id = $this->saveStoFilter($sto_filter);
            $this->saveStoRequire($sto_filter, $sto_filter_id);

        }
    }


    public function saveStoRequire($sto_filter, $sto_filter_id){
        $count = count($sto_filter);
        $mask_start = 'ПЕРІОДИЧНОСТЬ';
        $mask_end = 'Загальна';
        $mask_pause = 'НЕОБХІДНІ';
        $mask_optional_start = 'НАЗВА';

        $dist = array();

        $requireParamsArea = false;

        $optionalParamsArea = false;

        for($i=0; $i<$count; $i++){
            if(!$optionalParamsArea && !$requireParamsArea && (isset($sto_filter[$i][0]) && strripos(mb_strtolower($sto_filter[$i][0]),mb_strtolower($mask_start))!==false)){

                $requireParamsArea = true;
                $count2 = count($sto_filter[$i]);

                for($i2 = 1; $i2<$count2; $i2++){
                    $dist[$i2] = preg_replace('/\s\W+/', "", $sto_filter[$i][$i2]);
                }

            }

            if($requireParamsArea && (isset($sto_filter[$i][0]) && strripos(mb_strtolower($sto_filter[$i][0]),mb_strtolower($mask_end))!==false)){
                $requireParamsArea = false;
            }

            if($requireParamsArea && (isset($sto_filter[$i][0]) && strripos(mb_strtolower($sto_filter[$i][0]),mb_strtolower($mask_pause))===false)){

                $requireNameId = $this->saveStoRequireName($sto_filter[$i][0], $sto_filter_id);

                $count3 = count($dist);

                for($i3 = 1; $i3< $count3; $i3++){

                    $this->saveRequireData($dist[$i3], $sto_filter[$i][$i3], $requireNameId,$sto_filter_id );

                }

            }



            if($optionalParamsArea && isset($sto_filter[$i][0]) ){
                $this->saveOptionalData($sto_filter[$i],$sto_filter_id );



            }

            if(!$optionalParamsArea && !$requireParamsArea && (isset($sto_filter[$i][0]) && strripos(mb_strtolower($sto_filter[$i][0]),mb_strtolower($mask_optional_start))!==false)){
                $optionalParamsArea = true;
            }


        }
    }



    public function saveOptionalData($sto_filter,$sto_filter_id ){
        $modelOptional = new StoOptionalItems();
        $modelOptional->sto_filter_id = $sto_filter_id;
        $modelOptional->name = $sto_filter[0];
        $modelOptional->period = $sto_filter[1];
        $modelOptional->item_price = $sto_filter[3];
        $modelOptional->service_price = $sto_filter[5];
        if(!$modelOptional->search() instanceof StoOptionalItems){
            $modelOptional->save();
        }
    }

    public function saveRequireData($dist, $sto_filter ,$requireNameId,$sto_filter_id ){
        $modelData = new StoRequire();
        $modelData->dist = $dist;
        $modelData->sto_filter_id = $sto_filter_id;
        $modelData->sto_require_name_id = $requireNameId;
        $modelData->value = $sto_filter;
        if(!$modelData->search() instanceof StoRequire){
            $modelData->save();
        }

    }


    public function saveStoRequireName($name, $sto_filter_id){
        $modelName = new StoRequireName();
        $modelName->name = $name;
        $modelName->sto_filter_id = $sto_filter_id;
        $model = $modelName->search();
        if(!$model instanceof StoRequireName){
            $modelName->save();
            return $modelName->id;
        } else {
            return $model->id;
        }
    }

    public function saveStoFilter($sto_filter){
        $modelStoFilter = new StoFilter();
        $modelStoFilter->brand = $sto_filter[0][1];
        $modelStoFilter->model = $sto_filter[0][0];
        $modelStoFilter->engine = $sto_filter[0][2];
        $modelStoFilter->fuel_type = $sto_filter[0][3];
        $modelStoFilter->drive_unit = $sto_filter[0][4];
        $modelStoFilter->transmission = $sto_filter[0][5];

        $model = $modelStoFilter->search();
        if(!$model instanceof StoFilter){
            $modelStoFilter->save();
            return $modelStoFilter->id;
        } else {
            return $model->id;
        }
    }


    public function saveFile(){
        $path  = dirname(Yii::app()->basePath).'/uploads/parser';
        $path2  = dirname(Yii::app()->basePath).'/images/action';

        $uploadfile = $path .'/'.basename($_FILES['files']['name']);
        if(!is_dir($path)) {
            mkdir($path, 0777, true);
        }

        if(!is_dir($path2)) {
            mkdir($path2, 0777, true);
        }
        if (move_uploaded_file($_FILES['files']['tmp_name'], $uploadfile)) {
           return $uploadfile;
        } else {
            throw new ErrorException('Ошибка загрузки файла');
        }
    }

    public function actionParser(){
        Yii::app()->request->enableCsrfValidation = true;
        $array = '';
        if(!empty($_FILES)){
            $file = $this->saveFile();
            $result = $this->getXLS($file);
            $this->saveParserData($result);
        }

        die('{ "status": "Загрузка проведена успешно" }');

    }


    public function getSideMenu()
    {
        $res = array(
            array(
                'label' => 'Страницы',
                'items' => array(
                    array(
                        'label' => 'Главная страница',
                        'url' => array('/' . $this->module->id . '/stoFilterPages/index'),
                        'icon' => 'icon-file',
                        'active' => '/' . $this->module->id . '\/stoFilterPages\/index/',
                    ),
                    array(
                        'label' => 'Загрузить',
                        'url' => array('/' . $this->module->id . '/stoFilter/index'),
                        'icon' => 'icon-file',
                        'active' => '/' . $this->module->id . '\/StoFilter\/index/',
                    ),
                ),
            ),
        );
        return $res;
    }
}
