<?php

class catalyzImportTask extends sfPropelBaseTask {
    protected function configure() {
        $this->namespace = 'catalyz';
        $this->name = 'import';
        $this->briefDescription = '';
        $this->detailedDescription = <<<EOF
The [catalyz:import|INFO] task does things.
Call it with:

  [php symfony catalyz:import|INFO]
EOF;
        $this->addArgument('application', sfCommandArgument::REQUIRED, 'The application name');
        // add other arguments here
        $this->addOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev');
        $this->addOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'propel');
        // add other options here
    }

    protected function execute($arguments = array(), $options = array()) {
        // Database initialization
        $databaseManager = new sfDatabaseManager($this->configuration);
        $connection = Propel::getConnection($options['connection'] ? $options['connection'] : '');

        $configuration = ProjectConfiguration::getApplicationConfiguration('admin', 'jroussel', true);
        sfContext::createInstance($configuration);

        $this->importConfig();
        $this->importNodes();
        $this->importMembers();
        $this->importSuppliers();
        $this->importProducts();
        $this->addResponsibleToNodes();
        $this->updateConfig();
    }

    protected function importConfig() {
        $katao_config = new KataoConfig();
        $katao_config->setName('KATAO SARL');
        $katao_config->setAddress('LE BAT
82110 CAZES-MONDENARD');
        $katao_config->setPhone('06 82 26 68 19');
        $katao_config->setEmail('contact@katao.eu');
        $katao_config->setInitialTransactionsCount(2314);
        $katao_config->setInitialTransactionsSum(17729.35);
        $katao_config->setAccountingCodeBank('512000');
        $katao_config->setAccountingCodeBankSol('521000');
        $katao_config->setAccountingCodePrefixPurchase('607');
        $katao_config->setAccountingCodePrefixSell('707');
        $katao_config->setAccountingCodeSolDiscount('709000');
        $katao_config->setAccountingCodeErrorAdjustmentPositive('758000');
        $katao_config->setAccountingCodeErrorAdjustmentNegative('658000');
        $katao_config->setMailingListEmail('katao');
        $katao_config->setDefaultProductPicture('/uploads/repository/produits/unavailable.gif');
        $katao_config->setCartValidationDaysNumber(3);
        $katao_config->setAdditionalCurrencyName('SOL');
        $katao_config->setSiretNumber('50139732700013');
        $katao_config->setTvaNumber('tva');
        $katao_config->setRcsNumber('501397327');
        $katao_config->setCapital(1000);
        $katao_config->save();
    }

    protected function importNodes() {
        $xml = simplexml_load_file(sfConfig::get('sf_data_dir') . '/xml/noeud.xml');
        foreach($xml->children() as $xmlNode) {
            $katao_node = new KataoNode();
            $katao_node->setCity((string)$xmlNode->NOE_NOM);
            $katao_node->setBeginAt(mktime(12, 0, 0, 3, 18, 2006));
            $katao_node->setIsDefault('AUCUN' == $katao_node->getCity());
            $katao_node->save();

            $this->logSection('node+', $katao_node->getCity());
        }
    }

    protected function importMembers() {
        $members_data = array();
        $handle = fopen(sfConfig::get('sf_data_dir') . '/xml/KATAO ADHERENTS.csv', 'r');
        fgetcsv($handle, 1000, ";");
        while (($data = fgetcsv($handle, 1000, ";")) !== false) {
            $created_at = time();
            if ('' != $value = trim($data[2])) {
                list($day, $month, $year) = explode('/', $value);
                $created_at = mktime(0, 0, 0, (int)$month, (int)$day, (int)$year);
            }
            $members_data[trim($data[0])] = $created_at;
        }

        $xml = simplexml_load_file(sfConfig::get('sf_data_dir') . '/xml/ADHERENTS.xml');
        foreach($xml->children() as $adherent) {
            $katao_member = new KataoMember();
            $katao_member->setKataoIndex((int)$adherent->ADH_IND);
            $katao_member->setKataoNodeId((int)$adherent->NOE_ID);
            $katao_member->setFirstName((string)$adherent->ADH_PRENOM);
            $katao_member->setLastName((string)$adherent->ADH_NOM);
            $katao_member->setInitialAmountEuro(round((float)$adherent->ADH_SOLDE_EURO, 2));
            $katao_member->setInitialAmountSol(0);
            $katao_member->setIsReferer(1 == (int)$adherent->ADH_REFERENT);
            $katao_member->setIsDelegate(1 == (int)$adherent->ADH_DELEGUE);
            $katao_member->setCreatedAt(!empty($members_data[$katao_member->getLastName()])?$members_data[$katao_member->getLastName()]:time());
            $katao_member->save();

            $katao_user = new KataoUser();
            $katao_user->setEmail((string)$adherent->ADH_MAIL);
            $katao_user->setAddress1((string)$adherent->ADH_ADR);
            $katao_user->setAddress2((string)$adherent->ADH_ADR2);
            $katao_user->setZip((string)$adherent->ADH_CPO);
            $katao_user->setCity((string)$adherent->ADH_VILLE);
            $katao_user->setPhone((string)$adherent->ADH_TEL);
            $katao_user->setFax((string)$adherent->ADH_FAX);
            $katao_user->setGmapLat((string)$adherent->ADH_LATITUDE);
            $katao_user->setGmapLng((string)$adherent->ADH_LONGITUDE);
            $katao_user->setLogin((string)$adherent->ADH_LOG);
            $katao_user->setPassword((string)$adherent->ADH_PAS);
            $katao_user->setIsSeo(1 == (int)$adherent->ADH_GERANT);
            $katao_user->setIsAdmin(1 == (int)$adherent->ADH_ADMIN);
            $katao_user->setKataoMember($katao_member);
            $katao_user->setStatus((1 == (int)$adherent->ADH_ACTIF)?KataoUser::STATUS_ACTIVE:KataoUser::STATUS_DISABLED);
            $katao_user->save();

            $this->logSection('member+', $katao_member->getFullName());
        }
    }

    protected function importSuppliers() {
        $xml = simplexml_load_file(sfConfig::get('sf_data_dir') . '/xml/fournisseur.xml');
        foreach($xml->children() as $supplierNode) {
            $ADH_IND = (int)$supplierNode->ADH_IND;

            $katao_member = null;
            if ($ADH_IND && 1 != $ADH_IND) {
                $katao_member = KataoMemberPeer::retrieveByKataoIndex($ADH_IND);
            }
            // do not save supplier related to member
            $katao_member = null;

            $katao_supplier = new KataoSupplier();
            $katao_supplier->setKataoIndex((int)$supplierNode->FOU_IND);
            $katao_supplier->setKataoMemberRelatedByMemberId($katao_member);
            $katao_supplier->setKataoMemberRelatedByRefererId(KataoMemberPeer::retrieveByKataoIndex((int)$supplierNode->FOU_REFERENT));
            $katao_supplier->setName((string)$supplierNode->FOU_NOM);
            $katao_supplier->setPresentation('<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec consequat lobortis sapien. Proin quis justo. Nam rhoncus dolor eget libero. Integer pede libero, lobortis vitae, auctor vel, feugiat a, nisi. Pellentesque mattis suscipit urna. Praesent consequat imperdiet pede. Aliquam eu ipsum nec leo dictum pretium. Praesent arcu quam, blandit a, tincidunt nec, aliquam id, urna. Aliquam vulputate pulvinar risus. Nunc sagittis adipiscing purus.</p>
<p>Aenean mi ligula, vehicula ut, ultricies in, porta sed, diam. Curabitur commodo. Vivamus pretium venenatis sapien. Donec ante lacus, fermentum in, euismod euismod, ullamcorper ut, augue. Maecenas adipiscing mi nec tortor. Vestibulum pellentesque augue non mi. Nulla pellentesque varius nisi. Sed tempus tristique magna. Vivamus sapien. Integer vel erat. Etiam semper libero sit amet lorem. Integer erat mauris, sodales at, luctus eget, facilisis ac, nisi. Nunc pede. Mauris turpis. Donec congue, libero at aliquam laoreet, sapien nisi egestas arcu, vitae vulputate nisl metus eu dui. Vestibulum mauris. Aenean vitae diam. In neque felis, ultrices nec, pellentesque venenatis, vehicula nec, eros. Ut sagittis posuere massa.</p>');
            $katao_supplier->setEmail((string)$supplierNode->FOU_EMAIL);
            $katao_supplier->setAddress1((string)$supplierNode->FOU_ADRESSE);
            $katao_supplier->setAddress2((string)$supplierNode->FOU_aDRESSE_FIN);
            $katao_supplier->setZip((string)$supplierNode->FOU_CP);
            $katao_supplier->setCity((string)$supplierNode->FOU_VILLE);
            $katao_supplier->setPhone((string)$supplierNode->FOU_TELEPHONE);
            $katao_supplier->setFax((string)$supplierNode->FOU_TELECOPIE);
            $katao_supplier->setGmapLat((string)$supplierNode->FOU_LATITUDE);
            $katao_supplier->setGmapLng((string)$supplierNode->FOU_LONGITUDE);

            $siret = (string)$supplierNode->FOU_SIRET;
            $katao_supplier->setSiretNumber(($siret && '?' != $siret)?Utils::formatSiretNmber($siret):sprintf('%d-???', (int)$supplierNode->FOU_IND));

            $katao_supplier->setIsGlobal(false);
            $katao_supplier->setOrderMinAmount(0);
            $katao_supplier->save();

            $katao_user = null;
            if (!is_null($katao_member)) {
                $katao_user = $katao_member->getFirstKataoUser();
            }
            if (is_null($katao_user)) {
                $katao_user = new KataoUser();
                $katao_user->setEmail((string)$supplierNode->FOU_EMAIL);
                $katao_user->setAddress1((string)$supplierNode->FOU_ADRESSE);
                $katao_user->setAddress2((string)$supplierNode->FOU_aDRESSE_FIN);
                $katao_user->setZip((string)$supplierNode->FOU_CP);
                $katao_user->setCity((string)$supplierNode->FOU_VILLE);
                $katao_user->setPhone((string)$supplierNode->FOU_TELEPHONE);
                $katao_user->setFax((string)$supplierNode->FOU_TELECOPIE);
                $katao_user->setGmapLat((string)$supplierNode->FOU_LATITUDE);
                $katao_user->setGmapLng((string)$supplierNode->FOU_LONGITUDE);
                $katao_user->setLogin($katao_supplier->getUrlIdentifier());
                $katao_user->setPassword('katao');
            }

            $katao_user->setKataoSupplier($katao_supplier);
            $katao_user->save();

            $katao_supplier_node = new KataoSupplierNode();
            $katao_supplier_node->setKataoSupplier($katao_supplier);
            $katao_supplier_node->setKataoNodeId(2); //LAFRANCAISE
            $katao_supplier_node->save();

            $katao_supplier_node = new KataoSupplierNode();
            $katao_supplier_node->setKataoSupplier($katao_supplier);
            $katao_supplier_node->setKataoNodeId(3); //MONTAUBAN
            $katao_supplier_node->save();

            $this->logSection('supplier+', $katao_supplier->getName());
        }
    }

    protected function importProducts() {
        $categories = array();
        $families = array();

        $index = 1;
        $xml = simplexml_load_file(sfConfig::get('sf_data_dir') . '/xml/rayon.xml');
        foreach($xml->children() as $katao_product_category_node) {
            if (1 == (int)$katao_product_category_node->RAY_Envente) {
                $katao_product_category = new KataoProductCategory();
                $katao_product_category->setName((string)$katao_product_category_node->RAY_Nom);
                $katao_product_category->setAccountingCodeSuffix(sprintf('%d00', $index));
                $katao_product_category->setSortOrder($index++);
                $katao_product_category->save();

                $categories[(int)$katao_product_category_node->RAY_ID] = $katao_product_category->getId();
                $this->logSection('category+', $katao_product_category->getName());
            }
        }

        $xml = simplexml_load_file(sfConfig::get('sf_data_dir') . '/xml/famille.xml');
        foreach($xml->children() as $katao_product_family_node) {
            if (1 == (int)$katao_product_family_node->FAM_Envente && !empty($categories[(int)$katao_product_family_node->RAY_ID])) {
                $katao_product_family = new KataoProductFamily();
                $katao_product_family->setKataoProductCategoryId($categories[(int)$katao_product_family_node->RAY_ID]);
                $katao_product_family->setName((string)$katao_product_family_node->FAM_NOM);
                $katao_product_family->save();

                $families[(int)$katao_product_family_node->FAM_ID] = $katao_product_family->getId();
                $this->logSection('family+', $katao_product_family->getName());
            }
        }

        $xml = simplexml_load_file(sfConfig::get('sf_data_dir') . '/xml/produit.xml');
        foreach($xml->children() as $katao_product_node) {
            if (!empty($categories[(int)$katao_product_node->RAY_ID]) && !empty($families[(int)$katao_product_node->FAM_ID])) {
                $katao_product = new KataoProduct();
                $katao_product->setReference(trim((string)$katao_product_node->PRO_REF));
                $katao_product->setName((string)$katao_product_node->PRO_NOM);
                $katao_product->setDescription((string)$katao_product_node->pro_designation);
                $katao_product->setKataoProductFamilyId($families[(int)$katao_product_node->FAM_ID]);
                $katao_product->setKataoSupplier(KataoSupplierPeer::retrieveByKataoIndex((int)$katao_product_node->FOU_IND));
                $katao_product->setMaxSolAmount(floor(CONST_EURO_TO_SOL * (float)$katao_product_node->PRO_TTC * 5 / 100));
                $katao_product->setUnitPriceEuro(round((float)$katao_product_node->PRO_TTC / (1 + (float)$katao_product_node->PRO_mar) / (1 + (float)$katao_product_node->PRO_TVA), 3));
                $katao_product->setTvaRate((float)$katao_product_node->PRO_TVA);
                $katao_product->setMinOrderNumber(max(1, (int)$katao_product_node->PRO_MIN));
                $katao_product->setMargin((float)$katao_product_node->PRO_mar);

                $picture_distant = utf8_decode(trim((string)$katao_product_node->PRO_IMG));
                $picture_local = '/uploads/repository/produits/' . Catalyz::normalizeUrlIdentifier(trim((string)$katao_product_node->PRO_IMG));
                if (false === strpos($picture_local, '.bmp') && '' != $picture_distant && '<FONT SIZE=1>Libell&eacute;</FONT>' != $picture_distant && '' != $picture_local) {
                    if (file_put_contents(sprintf('%s%s', sfConfig::get('sf_web_dir'), $picture_local), file_get_contents(sprintf('http://lereseau.katao.eu/KATAO_WEB/%s', rawurlencode($picture_distant))))) {
                        $katao_product->setPicture($picture_local);
                    }
                }

                $katao_product->setDeliveryDelay((int)$katao_product_node->PRO_DEL);
                $katao_product->setIsArchived((int)$katao_product_node->PRO_ARCHIVER);
                $katao_product->save();

                $this->logSection('product+', $katao_product->getName());
            }
        }
    }

    protected function addResponsibleToNodes() {
        $xml = simplexml_load_file(sfConfig::get('sf_data_dir') . '/xml/noeud.xml');
        foreach($xml->children() as $xmlNode) {
            if (null != $katao_node = KataoNodePeer::retrieveByCity((string)$xmlNode->NOE_NOM)) {
                if (null != $katao_member = KataoMemberPeer::retrieveByKataoIndex((int)$xmlNode->ADH_IND)) {
                    if (null != $katao_user = $katao_member->getFirstKataoUser()) {
                        $katao_node->setResponsible($katao_user->getId());
                        $katao_node->save();
                    }
                }
            }
        }
    }

    protected function updateConfig() {
        $katao_config = wpConfig::getInstance(true);
        $katao_config->setKataoMemberId(1);
        $katao_config->save();
        wpConfig::setInstance($katao_config);
    }
}