<?php


class SupsysticTablesPro_Importer_Model_Importer extends SupsysticTables_Core_BaseModel
{
    /**
     * Imports the file content to the table.
     * @param int $id Table id
     * @param array $file File info
     * @throws \SupsysticTablesPro_Importer_Exception_UnsupportedType
     * @throws \SupsysticTablesPro_Importer_Exception_Upload
     */
    public function import($id, array $file, $settings)
    {
        if (isset($file['error']) && $file['error'] !== UPLOAD_ERR_OK) {
            switch ($file['error']) {
                case UPLOAD_ERR_INI_SIZE:
                case UPLOAD_ERR_FORM_SIZE:
                    $message = $this->environment->translate('The uploaded file exceeds the max size of uploaded files.');
                    break;

                case UPLOAD_ERR_PARTIAL:
                    $message = $this->environment->translate('The uploaded file was only partially uploaded.');
                    break;
                case UPLOAD_ERR_NO_FILE:
                    $message = $this->environment->translate('No file was uploaded.');
                    break;
                case UPLOAD_ERR_NO_TMP_DIR:
                    $message = $this->environment->translate('Missing a temporary folder.');
                    break;
                case UPLOAD_ERR_CANT_WRITE:
                    $message = $this->environment->translate('Failed to write file to disk.');
                    break;
                default:
                    $message = $this->environment->translate('Unexpected error.');
            }

            throw new SupsysticTablesPro_Importer_Exception_Upload($message);
        }

        try {
            $extension   = pathinfo($file['name'], PATHINFO_EXTENSION);
            $raw         = isset($settings['raw_data']) && $settings['raw_data'];
            $visibleData = isset($settings['visible_data']) && $settings['visible_data'];

            $remove      = isset($settings['remove_data']) && ($settings['remove_data'] == 'on') ? true : false;
            if ($remove) {
              $core   = $this->environment->getModule('core');
              $tables = $core->getModelsFactory()->get('tables');
              $tables->removeRows($id);
            }

            $importer    = $this->createImporter($extension);
            $importer->setSettings(array(
                'id' => $id,
                'remove' => $remove,
                'raw' => $raw,
                'visibleData' => $visibleData,
                'model' => $this
            ));
            $data    = $importer->import($file['tmp_name'], $extension);

            $this->updateTableData($id, $data);
        }
        catch (InvalidArgumentException $e) {
            throw new SupsysticTablesPro_Importer_Exception_UnsupportedType($e->getMessage());
        }
        catch (PhpOffice\PhpSpreadsheet\Exception $e) {
            throw new SupsysticTablesPro_Importer_Exception_UnsupportedType($e->getMessage());
        }
    }

    public function importSpreadheets($id, $settings)
    {
        preg_match('/([\w-]{25,}).+#gid=(\d+)/', $settings['url'], $matches);
        if (empty($matches)) {
            throw new SupsysticTablesPro_Importer_Exception('Wrong spreadsheet id or url');
        }
        $spreadsheetId = $matches[1];
        $sheetId       = $matches[2];
        $url           = "https://docs.google.com/spreadsheets/d/$spreadsheetId/export?format=xlsx&gid=$sheetId";
        $response      = wp_remote_get($url);
        if (is_wp_error($response)) {
            throw new SupsysticTablesPro_Importer_Exception($response->get_error_message());
        }
        $contentType = wp_remote_retrieve_header($response, 'content-type');
        if (strpos($contentType, 'application') === false) {
            throw new SupsysticTablesPro_Importer_Exception('please, check the sharing settings of your spreadsheet. It must be accessed to edit for everyone who has link.');
        }
        $file = wp_remote_retrieve_body($response);
        if (empty($file)) {
            throw new SupsysticTablesPro_Importer_Exception(error_get_last());
        }
        try {
            $importer = new SupsysticTablesPro_Importer_Type_Xlsx();
            $temp     = tempnam(sys_get_temp_dir(), 'spreadsheet');
            if (empty($temp) || !$temp) {
                $temp = tempnam(get_temp_dir(), 'spreadsheet');
            }
            $handler = fopen($temp, 'w+');
            fwrite($handler, $file);
            fclose($handler);

            $remove = isset($settings['remove_data']) && ($settings['remove_data'] == 'on') ? true : false;
            if ($remove) {
              $core   = $this->environment->getModule('core');
              $tables = $core->getModelsFactory()->get('tables');
              $tables->removeRows($id);
            }
            //error_log( print_r($temp, true) );
            try {
                $importer->setSettings(array(
                    'id' => $id,
                    'remove' => $remove,
                    'raw' => (isset($settings['raw_data']) && $settings['raw_data'] ? true : false),
                    'model' => $this,
                    'uniq' => 'stb-google-' . $spreadsheetId . '-' . $sheetId
                ));
                $data = @$importer->import($temp, 'xlsx');
                $this->updateTableData($id, $data);
                unlink($temp);
            }
            catch (PhpOffice\PhpSpreadsheet\Exception $e) {
                $message = strtolower($e->getMessage());

                throw new SupsysticTablesPro_Importer_Exception("possible reason - $message Also, please, check the sharing settings of your spreadsheet: it must be accessed to edit for everyone who has link.");
            }
        }
        catch (InvalidArgumentException $e) {
            throw new SupsysticTablesPro_Importer_Exception_UnsupportedType($e->getMessage());
        }
    }

    protected function createImporter($type)
    {
        $importer = null;
        $this->environment->getModule('importer')->getController()->includePHPExcel();

        switch (strtolower($type)) {
            case 'csv':
                $importer = new SupsysticTablesPro_Importer_Type_Csv();
                break;
            case 'xls':
            case 'xlsx':
                $importer = new SupsysticTablesPro_Importer_Type_Xlsx();
                break;
            default:
                throw new InvalidArgumentException(sprintf($this->environment->translate('Unsupported file type "%s".'), $type));
        }

        return $importer;
    }

    public function updateTableData($id, $data)
    {
        /** @var SupsysticTables_Core_Module $core */
        $core   = $this->environment->getModule('core');
        /** @var SupsysticTables_Tables_Model_Tables $tables */
        $tables = $core->getModelsFactory()->get('tables');

        $tables->setRowsImport($id, (array) $data['rows']);
        if (isset($data['removeRows']) && $data['removeRows'] > 0) {
            $tables->removeLastRows($id, $data['removeRows']);
        }
        if (isset($data['lastColumn']) && $data['lastColumn'] >= 0) {
            $tables->removeLastColumns($id, $data['lastColumn']);
        }

        // Set table meta
        if (isset($data['meta'])) {
            $meta = $tables->getMeta($id);
            if (isset($data['meta']['columnsWidth'])) {
                @$meta['columnsWidth'] = !empty($data['meta']['columnsWidth']) ? $data['meta']['columnsWidth'] : array();
            }

            if (isset($data['meta']['mergedCells'])) {
                @$meta['mergedCells'] = !empty($data['meta']['mergedCells']) ? $data['meta']['mergedCells'] :  array();
            }
            $tables->setMeta($id, $meta);
        }

        if (isset($data['conditions'])) {
            $conditions = $core->getModelsFactory()->get('conditions', 'tables');
            $conditions->removeConditions($id);
            $conditions->setConditions($id, $data['conditions']);
        }
    }
}
