<?php

/**
 *
 * @category   Directshop
 * @package    Directshop_FraudDetection
 * @author     Ben James
 * @copyright  Copyright (c) 2008-2010 Directshop Pty Ltd. (http://directshop.com.au)
 */
$installer = $this;
$installer->startSetup();
$installer->run("\r\nDROP TABLE IF EXISTS {$this->getTable('frauddetection_data')};\r\nCREATE TABLE {$this->getTable('frauddetection_data')} (\r\n  `entity_id` int(10) NOT NULL auto_increment,\r\n  `order_id` int(10) NOT NULL,\r\n  `fraud_score` int(11) NULL DEFAULT '0',\r\n  `fraud_data` text NULL,\r\n  `sent_data` text NULL,\r\n  PRIMARY KEY  (`entity_id`),\r\n  KEY `order_id_idx` (`order_id`)\r\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\r\n");
// transfer any old data across
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
if ($setup->getEntityType('order_payment') !== false) {
    $responseAttribute = $setup->getAttribute('order_payment', 'maxmind_response');
    $scoreAttribute = $setup->getAttribute('order', 'fraud_score');
    if ($responseAttribute && $setup->tableExists('sales_order_entity_text')) {
        $read = Mage::getSingleton('core/resource')->getConnection('core_read');
        $existingData = $read->fetchAll("select * from {$this->getTable('sales_order_entity_text')} where attribute_id = ?", array($responseAttribute['attribute_id']));
        foreach ($existingData as $data) {
            $parentId = $read->fetchOne("select parent_id from {$this->getTable('sales_order_entity')} where entity_id = ?", array($data['entity_id']));
            $fraudScore = 0;
            if ($scoreAttribute) {
                $fraudScore = $read->fetchOne("select value from {$this->getTable('sales_order_int')} where entity_id = ? AND attribute_id = ?", array($parentId, $scoreAttribute['attribute_id']));
            } else {
                $fraudData = @unserialize($data['value']);
                if (isset($fraudData['ourscore'])) {
                    $fraudScore = $fraudData['ourscore'];
                }
            }