#!/usr/bin/php
<?
if (!$_SERVER["HTTP_USER_AGENT"]) { // to run via local browser use $_SERVER["SERVER_ADDR"] == $_SERVER["REMOTE_ADDR"]
  $profileId = 7; // SYSTEM - IMPORT/EXPORT - ADVANCED PROFILES

  require_once 'app/Mage.php';
  umask(0);
  Mage::app("default")->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
  $profile = Mage::getModel('dataflow/profile');
  $userModel = Mage::getModel('admin/user');
  $userModel->setUserId(0);
  Mage::getSingleton('admin/session')->setUser($userModel);

  $profile->load($profileId);
  if (!$profile->getId()) {
    Mage::getSingleton('adminhtml/session')->addError('ERROR: Incorrect profile id');
  }

  Mage::register('current_convert_profile', $profile);

  $profile->run();
  
  $recordCount = 0;
  $batchModel = Mage::getSingleton('dataflow/batch');
  if ($batchModel->getId()) {
    if ($batchModel->getAdapter()) {
      $batchId = $batchModel->getId();
      $batchImportModel = $batchModel->getBatchImportModel();
      $importIds = $batchImportModel->getIdCollection();  
      $batchModel = Mage::getModel('dataflow/batch')->load($batchId);      
      $adapter = Mage::getModel($batchModel->getAdapter());
      $resource = Mage::getSingleton('core/resource');
      $product_table = $resource->getTableName('catalog/product');
      $attribute_table = $resource->getTableName('eav/attribute');
      $super_link_table = $resource->getTableName('catalog/product_super_link');
      $super_attribute_table = $resource->getTableName('catalog/product_super_attribute');
      $write = $resource->getConnection('catalog_write');
      foreach ($profile->getExceptions() as $e) {
        printf($e->getMessage() . "\n");
      }
      $exceptionCount = count($profile->getExceptions());
      foreach ($importIds as $importId) {
        $recordCount++;
        try{
          $batchImportModel->load($importId);
          if (!$batchImportModel->getId()) {
             $errors[] = Mage::helper('dataflow')->__('WARNING: Skip undefined row');
             continue;
          }
          $importData = $batchImportModel->getBatchData();
          try {
            $adapter->saveRow($importData);
	    if ($importData['type'] == 'configurable') { // force link of configurable products
	      $parent_id = $write->fetchOne("select * from $product_table where sku='".$importData['sku']."'");
	      $attribute_id = $write->fetchOne("select * from $attribute_table where attribute_code='".$importData['config_attributes']."'");
	      if (!$write->fetchOne("select * from $super_attribute_table where product_id=".(int)$parent_id." and attribute_id=".(int)$attribute_id)) {
	        $write->query("insert into $super_attribute_table (product_id, attribute_id) values (".(int)$parent_id.",".(int)$attribute_id.")");
	      }
	      foreach (explode(',', $importData['associated']) as $product_sku) {
		try {
	          $product_id = $write->fetchOne("select * from $product_table where sku='$product_sku'");
		  if (!$write->fetchOne("select * from $super_link_table where parent_id=".(int)$parent_id." and product_id=".(int)$product_id)) {
		    $write->query("insert into $super_link_table (parent_id, product_id) values (".(int)$parent_id.",".(int)$product_id.")");
		  }
		} catch (Exception $e) {
                  printf("ROW " . $recordCount . ", PARENT SKU " . $importData['sku'] . ", PRODUCT SKU " . $product_sku . " - " . $e->getMessage() . "\n");
	 	}
	      }
	    }
          } catch (Exception $e) {
            printf("ROW " . $recordCount . ", SKU " . $importData['sku'] . " - " . $e->getMessage() . "\n");
	    continue;
          }
          if ($recordCount%100 == 0) {
            printf($recordCount . "...\n");          
          }
        } catch(Exception $ex) {
          printf("ROW " . $recordCount . ", SKU " . $importData['sku'] . " - " . $e->getMessage() . "\n");          
        }
      }
      foreach ($profile->getExceptions() as $e) {
	$exceptionCount>0 ? $exceptionCount-- : printf($e->getMessage() . "\n");
      }
    }
    printf("Done\n");
  }
}
?>
