<?php
/* * ********************************************************************************************
 * 								Open Real Estate
 * 								----------------
 * 	version				:	V1.36.0
 * 	copyright			:	(c) 2016 Monoray
 * 							http://monoray.net
 * 							http://monoray.ru
 *
 * 	website				:	http://open-real-estate.info/en
 *
 * 	contact us			:	http://open-real-estate.info/en/contact-us
 *
 * 	license:			:	http://open-real-estate.info/en/license
 * 							http://open-real-estate.info/ru/license
 *
 * This file is part of Open Real Estate
 *
 * ********************************************************************************************* */

class MainController extends ModuleAdminController
{

    //private $delimiter = "\t";
    //private $delimiter = ",";
    private $delimiter = ";";
    private $enclosure = "\0";
    public $modelName = 'TranslateMessage';

    public function init()
    {
        parent::init();

        //$this->enclosure = chr(0);
    }

    public function accessRules()
    {
        return array(
            array('allow',
                'expression' => "Yii::app()->user->checkAccess('all_lang_and_currency_admin')",
            ),
            array('deny',
                'users' => array('*'),
            ),
        );
    }

    public function actionIndex()
    {
        $this->redirect(array('admin'));
    }

    public function actionView($id)
    {
        $this->redirect(array('admin'));
    }

    public function actionAdmin()
    {
        Controller::disableProfiler();

        $modelEx = new EcsvForm();
        $modelIm = new IcsvForm();
        $contentCsv = null;

        if (isset($_POST['EcsvForm'])) {
            $modelEx->attributes = $_POST['EcsvForm'];
            if ($modelEx->validate()) {
                $cmd = Yii::app()->db->createCommand("SELECT id, message, translation_{$modelEx->lang} FROM {{translate_message}}");
                $csv = new ECSVExport($cmd, true, true, $this->delimiter, $this->enclosure);

                $fileName = Yii::app()->request->hostInfo . date('Y_m_d-H_i_s') . '-' . $modelEx->lang;
                $fileName = translit($fileName) . '.csv';

                $BOM = "\xEF\xBB\xBF";
                $contentCsv = $BOM . $csv->toCSV();
                Yii::app()->getRequest()->sendFile($fileName, $contentCsv, "text/csv", false);
            }
        }

        $this->render('admin', array(
            'tab' => 'export',
            'modelEx' => $modelEx,
            'modelIm' => $modelIm,
            'contentCsv' => $contentCsv
        ));
    }

    public function actionImport()
    {
        Controller::disableProfiler();

        $modelEx = new EcsvForm();
        $modelIm = new IcsvForm();
        $contentCsv = null;

        $this->modelName = 'IcsvForm';
        $model = new IcsvForm();

        if (isset($_FILES[$this->modelName]) && isset($_FILES[$this->modelName]['name'])) {
            $model->import = CUploadedFile::getInstance($model, 'import');

            if ($model->validate()) {
                $fileExt = $model->import->extensionName;

                $fileName = date('Y_m_d') . '_import_lang.' . $fileExt;
                $filePath = $model->csvPath . DIRECTORY_SEPARATOR . $fileName;

                $model->import->saveAs($filePath);

                $isZip = false;
                // if zip arhive
                if ($fileExt == 'zip') {
                    $isZip = true;

                    $list = array();

                    $zip = new ZipArchive();
                    if ($zip->open($filePath) === true) {
                        $zip->extractTo($model->csvPath);

                        if ($zip->numFiles) {
                            for ($i = 0; $i < $zip->numFiles; $i++) {
                                $list[$i] = $zip->getNameIndex($i);
                            }
                        }
                        $zip->close();
                    } else {
                        Yii::app()->user->setFlash('error', $zip->getStatusString());
                        $this->redirect('viewImport');
                    }

                    if (empty($list)) {
                        Yii::app()->user->setFlash('error', tc('Error loading. Try again later.'));
                        $this->redirect('viewImport');
                    }

                    if (!empty($list)) {
                        foreach ($list as $item) {
                            if (strpos($item, ".csv")) {
                                if ($item != $fileName) {
                                    $fileNameCSV = str_replace(".zip", ".csv", $fileName);
                                    if (copy($model->csvPath . DIRECTORY_SEPARATOR . $item, $model->csvPath . DIRECTORY_SEPARATOR . $fileNameCSV)) {
                                        @unlink($model->csvPath . DIRECTORY_SEPARATOR . $item);
                                    } else {
                                        Yii::app()->user->setFlash(
                                            'error', tt('Error copying file. Please try again later and set 0777 for ' . $model->csvPath)
                                        );
                                        $this->redirect('viewImport');
                                    }
                                    @unlink($model->csvPath . DIRECTORY_SEPARATOR . $item);
                                    @unlink($model->csvPath . DIRECTORY_SEPARATOR . $fileName);

                                    $fileName = $fileNameCSV;
                                    $filePath = $model->csvPath . DIRECTORY_SEPARATOR . $fileName;
                                }
                                break;
                            }
                        }
                    }
                }

                $import = $rowData = array();

                // prepare
                $fileContents = file_get_contents($filePath);
                iconv(mb_detect_encoding($fileContents, mb_detect_order(), true), "UTF-8", $fileContents);
                $fileContents = str_replace('""', '', $fileContents);
                #$fileContents = strip_tags($fileContents);
                file_put_contents($filePath, $fileContents);

                //parse csv file
                @setlocale(LC_ALL, 'en_US.utf8');
                if (($handle = fopen($filePath, "r")) !== FALSE) {
                    while (($data = fgetcsv($handle, 0, $this->delimiter, $this->enclosure)) !== FALSE) {
                        $import[] = $data;
                    }
                    fclose($handle);

                    // check correct csv
                    $tmpData = $import;
                    foreach ($tmpData as $key => $tmpRow) {
                        if (!is_array($tmpRow) || count($tmpRow) != 3) {
                            unset($tmpData[$key]);
                        }
                    }

                    if (count($tmpData) == count($import)) {
                        unset($tmpData);

                        $keys = $import[0];

                        // remove BOM from file
                        $bom = pack('H*', 'EFBBBF');
                        $keys[0] = preg_replace("/^$bom/", '', $keys[0]);

                        unset($import[0]);

                        // backup translate message
                        $sql = "DROP TABLE IF EXISTS {{translate_message_back}}; \n";
                        $sql .= "CREATE TABLE IF NOT EXISTS {{translate_message_back}} LIKE {{translate_message}}; \n";
                        $sql .= "INSERT {{translate_message_back}} SELECT * FROM {{translate_message}};";
                        Yii::app()->db->createCommand($sql)->execute();

                        $j = 0;
                        foreach ($import as $key => $items) {
                            if (count($keys) == count($items)) {
                                array_walk($items, array($this, 'stripEnclosure'));
                                $update = array_combine($keys, $items);

                                $id = (int)$update['id'];

                                if (isset($update['message']))
                                    unset($update['message']);
                                if (isset($update['id']))
                                    unset($update['id']);

                                Yii::app()->db->createCommand()
                                    ->update('{{translate_message}}', $update, 'id=:id', array(':id' => $id));

                                $j++;
                            } else {
                                continue;
                            }
                        }

                        Yii::app()->user->setFlash('success', $j . ' ' . tt('fields imported'));
                    } else {
                        Yii::app()->user->setFlash(
                            'error', Yii::t('module_translateCsv', 'The File is invalid for use as the following: delimiter must be: {delimiter}. Enclosure must be: ".', array('{delimiter}' => $this->delimiter))
                        );
                    }
                } else {
                    Yii::app()->user->setFlash(
                        'error', tc('Error loading file')
                    );
                }
            } else {
                Yii::app()->user->setFlash(
                    'error', Yii::t('module_iecsv', 'Please select a *.csv or *.zip file for import. Max size of file is {size}.', array('{size}' => $model->fileMaxSizeMessage))
                );
            }
        }

        $this->render('admin', array(
            'tab' => 'import',
            'modelEx' => $modelEx,
            'modelIm' => $modelIm,
            'contentCsv' => $contentCsv
        ));
    }

    private function stripEnclosure(&$val, $key)
    {
        $val = str_replace(array($this->enclosure, '"'), array('', ''), $val);
        $val = filter_var($val, FILTER_SANITIZE_STRING);
    }
}
