<?php

class AutomaticImports extends Window
{
    protected $tableName = 'import';
    protected $template = 'window/automatic_import.tpl';

    public function get_vars()
    {
        $ID = $this->getID();
        $vars = parent::get_vars();
        $pageVars = getVal('body', $vars);
        $acn = $this->getAction();

        if ($acn == 'edit' || ($acn == 'add' && $this->isDuplicate() && !empty($ID))) {
            $SQL = sqlQuery('SELECT s.*
                        FROM '.getTableName('import')." s
                        WHERE s.id='".$ID."' ");
            if (sqlNumRows($SQL) == 1) {
                $pageVars['data'] = sqlFetchArray($SQL);
                if ($acn == 'add' && $this->isDuplicate() && !empty($ID)) {
                    $pageVars['data']['name'] = stringCopy(trim($pageVars['data']['name']));
                }
                $pageVars['data']['local_file'] = $GLOBALS['cfg']['Path']['data'].'/tmp/autoimport_'.$ID;
                if (empty($pageVars['data']['source']) && file_exists($pageVars['data']['local_file'])) {
                    $pageVars['data']['source_type'] = 'upload';
                } else {
                    $pageVars['data']['source_type'] = 'url';
                }
            }
        } elseif ($acn == 'add') {
            $pageVars['data']['source_type'] = 'upload';
            $pageVars['data']['source'] = '';
            $pageVars['data']['type'] = AutomaticImport::TYPE_XML;
            $pageVars['data']['interval'] = 1;
            $pageVars['data']['delete_old'] = null;
            $pageVars['data']['modify_in_store'] = 1;
            $pageVars['data']['pair'] = 1;
            $pageVars['data']['local_file'] = null;
        }

        $sql = sqlQuery('SELECT id, name FROM '.getTableName('suppliers'));
        foreach ($sql as $row) {
            $pageVars['suppliers'][$row['id']] = $row['name'];
        }

        $pageVars['automatic_import'] = AutomaticImport::$types;

        if (file_exists($pageVars['data']['local_file'])) {
            $pageVars['data']['local_file_time'] = date('d.m.Y H:i:s', filemtime($pageVars['data']['local_file']));
        }

        $pageVars['choices'] = ['1' => 'u produktu/varianty'];
        if (findModule(\Modules::PRODUCTS_SUPPLIERS) || findModule(\Modules::SUPPLIERS)) {
            $pageVars['choices']['0'] = 'u dodavatele';
        }

        $pageVars['add_new'] = [
            '0' => 'Pouze aktualizovat stávající',
            '1' => 'Přidat nové i aktualizovat stávající',
            '2' => 'Pouze přidat nové',
            '3' => 'Přidat a aktualizovat pouze varianty',
        ];
        $pageVars['pair'] = ['0' => 'Ne', '1' => 'Ano'];

        if (findModule('products_suppliers') && !empty($pageVars['data']['id_supplier'])) {
            $pageVars['products_of_suppliers'] = returnSQLResult('SELECT COUNT(*) FROM '.getTableName('products_of_suppliers')." pos WHERE pos.id_supplier='{$pageVars['data']['id_supplier']}'");
        }

        $vars['type'] = 'automatic_import';
        $vars['body'] = $pageVars;

        return $vars;
    }

    //   protected function getData()
    //   {
    //      $data = parent::getData();
    //
    //      $data['transformation'] = $this->prettyXml($data['transformation']);
    //
    //      return $data;
    //   }
    //
    //   function prettyXml($string)
    //   {
    //      $domxml = new DOMDocument('1.0');
    //      $domxml->preserveWhiteSpace = false;
    //      $domxml->formatOutput = true;
    //
    //      /* @var $xml SimpleXMLElement */
    //      $domxml->loadXML($string);
    //      return $domxml->saveXML();
    //   }

    public function handle()
    {
        $ID = $this->getID();

        ini_set('memory_limit', '1024M');

        $synchronize = getVal('synchronize');
        $synchronize_try = getVal('synchronize_try');
        if ((!empty($synchronize) || !empty($synchronize_try)) && !empty($ID)) {
            // $errors = error_reporting(E_ALL|E_STRICT);

            $import = \KupShop\KupShopBundle\Util\Compat\ServiceContainer::getService(\KupShop\AdminBundle\Util\AutomaticImport::class);

            $import->setData($ID);

            if (getVal('dumpXmlBefore') || getVal('dumpXmlAfter')) {
                if (!$import->parseParams()) {
                    exit($import->error);
                }

                if (!$import->getSourceFile()) {
                    exit($import->error);
                }

                if (!$import->getXML()) {
                    exit($import->error);
                }

                if (getVal('dumpXmlBefore')) {
                    exit($import->dumpXML());
                }

                if (!$import->transformXML()) {
                    exit($import->error);
                }

                exit($import->dumpXML());
            }

            if (!$import->process(!empty($synchronize_try))) {
                redirect('launch.php?s=automatic_import.php&acn=edit&refresh=parent&ID='.$ID.'&ErrStr='.urlencode("Chyba importu: {$import->error}"));
            }

            $import->deleteOldProducts();

            $import->showUpdatedProducts();

            // presmerovani
            if (empty($synchronize_try)) {
                $smarty = createSmarty(true, true);
                $smarty->assign(Window::get_vars());
                $smarty->assign([
                    'ID' => $this->getID(),
                    'import' => $import,
                    'view' => $this,
                ]);
                $columns = $import->getDebugData();

                $updatedProducts = array_filter($import->updatedCreatedProducts ?? [], function ($product) {
                    return $product['status'] != 'ignorován';
                });

                $smarty->assign(['updatedProducts' => $updatedProducts]);
                $smarty->assign($columns);
                $smarty->display('window/import.result.tpl');
                if (in_array('import_error', $columns['columns'])) {
                    $number = 0;
                    foreach ($columns['products'] as $product) {
                        if (!empty($product['import_error'])) {
                            $number++;
                        }
                    }
                    writeDownActivity('Pozor: Auto. import - počet neúspěšně importovaných souborů:'.$number);
                }
                exit;
            /*$ret = "";
            $ret .= "Načteno {$import->stats['products']} produktů\\n";
            $ret .= "Načteno {$import->stats['variations']} variant\\n";
            $ret .= "Vytvořeno {$import->stats['products_created']} produktů\\n";
            $ret .= "Vytvořeno {$import->stats['variations_created']} variant\\n";
            $ret .= "Aktualizováno {$import->stats['products_updated']} produktů\\n";
            $ret .= "Aktualizováno {$import->stats['variations_updated']} variant\\n";
            $ret .= "Smazáno ".count($import->stats['deleted'])." starých produktů/variant\\n";
            //$ret .= "Smazáno ".count($import->stats['variations_deleted'])." starých variant\\n";

            redirect("launch.php?s=automatic_import.php&acn=edit&refresh=parent&ID=".$ID."&ErrStr=".urlencode($ret));*/
            } else {
                $smarty = createSmarty(true, true);
                $smarty->assign(Frame::get_vars());
                $smarty->assign([
                    'data' => $this->getData(),
                    'ID' => $this->getID(),
                    'import' => $import,
                    'view' => $this,
                    'all' => getVal('all'),
                ]);
                $smarty->assign($import->getDebugData());
                $smarty->display('window/automatic_import.dump.tpl');
                exit;
            }

            // error_reporting($errors);
        }

        parent::handle();
    }

    public function handleUpdate()
    {
        $data = $this->getData();
        $ID = $this->getID();
        $acn = $this->getAction();

        $SQL = parent::handleUpdate();

        if ($SQL) {
            if ($acn == 'add') {
                $ID = sqlInsertID();
            }
            if (!empty($_FILES['source_file']) && is_uploaded_file($_FILES['source_file']['tmp_name'])) {
                $data['local_file'] = $GLOBALS['cfg']['Path']['data'].'/tmp/autoimport_'.$ID;
                if (!move_uploaded_file($_FILES['source_file']['tmp_name'], $data['local_file'])) {
                    $ErrStr = 'Nelze přesunout uploadovaný soubor.';
                }
            }
        }

        return $SQL;
    }

    public function handleDownload()
    {
        $ID = $this->getID();
        $type = returnSqlResult('SELECT type
            FROM '.getTableName('import')." s
            WHERE s.id='{$ID}' ");

        $file = $GLOBALS['cfg']['Path']['data'].'/tmp/autoimport_'.$ID;

        if (!file_exists($file)) {
            $this->returnError('Soubor neexistuje');
        }

        switch ($type) {
            case AutomaticImport::TYPE_XML:
                $contentType = 'application/pdf';
                $extension = 'pdf';
                break;

            case AutomaticImport::TYPE_CSV:
                $contentType = 'text/csv';
                $extension = 'csv';
                break;

            case AutomaticImport::TYPE_XLS:
                $contentType = 'application/vnd.ms-excel';
                $extension = 'xls';
                break;

            default:
                $contentType = 'application/octet-stream';
                $extension = 'bin';
        }

        header("Content-type: {$contentType}");
        header("Content-Disposition: attachment; filename=\"automatic_import_{$ID}.{$extension}\"");

        readfile($file);
        exit;
    }
}

return AutomaticImports::class;
