/**
     * Can add products to the category straight from the ProductCategory page
     * TODO remove this, its not useful. And change the direction of the many_many relation so that patched version of CTF not needed
     * 
     * @see Page::getCMSFields()
     * @return FieldSet
     */
    function getCMSFields()
    {
        $fields = parent::getCMSFields();
        /*
            //Product categories
            $manager = new ManyManyComplexTableField(
              $this,
              'Products',
              'Product',
              array(),
              'getCMSFields_forPopup'
            );
            $manager->setPermissions(array());
            $fields->addFieldToTab("Root.Content.Products", $manager);
        */
        if (file_exists(BASE_PATH . '/swipestripe') && ShopSettings::get_license_key() == null) {
            $fields->addFieldToTab("Root.Content.Main", new LiteralField("SwipeStripeLicenseWarning", '<p class="message warning">
					 Warning: You have SwipeStripe installed without a license key. 
					 Please <a href="http://swipestripe.com" target="_blank">purchase a license key here</a> before this site goes live.
				</p>'), "Title");
        }
        return $fields;
    }
    /**
     * Set some CMS fields for managing Product images, Variations, Options, Attributes etc.
     * 
     * @see Page::getCMSFields()
     * @return FieldSet
     */
    public function getCMSFields()
    {
        $fields = parent::getCMSFields();
        //Gallery
        $manager = new ComplexTableField($this, 'Images', 'ProductImage', array('SummaryOfImage' => 'Thumbnail', 'Caption' => 'Caption'), 'getCMSFields_forPopup');
        $manager->setPopupSize(650, 400);
        $fields->addFieldToTab("Root.Content.Gallery", new HeaderField('GalleryHeading', 'Add images for this product, the first image will be used as a thumbnail', 3));
        $fields->addFieldToTab("Root.Content.Gallery", $manager);
        //Product fields
        $amountField = new MoneyField('Amount', 'Amount');
        $amountField->setAllowedCurrencies(self::$allowed_currency);
        $fields->addFieldToTab('Root.Content.Main', $amountField, 'Content');
        //Stock level field
        $level = $this->StockLevel()->Level;
        $fields->addFieldToTab('Root.Content.Main', new StockField('Stock', null, $level, $this), 'Content');
        //Product categories
        $fields->addFieldToTab("Root.Content.Categories", new HeaderField('CategoriesHeading', 'Select categories you would like this product to appear in', 3));
        $categoryAlert = <<<EOS
<p class="message good">
Please 'Save' after you have finished changing categories if you would like to set the order of this product
in each category.
</p>
EOS;
        $fields->addFieldToTab("Root.Content.Categories", new LiteralField('CategoryAlert', $categoryAlert));
        /*
        $manager = new BelongsManyManyComplexTableField(
          $this,
          'ProductCategories',
          'ProductCategory',
          array(),
          'getCMSFields_forPopup',
          '',
          '"Title" ASC'
        );
        $manager->setPageSize(20);
        $manager->setPermissions(array());
        $fields->addFieldToTab("Root.Content.Categories", $manager);
        */
        $categoriesField = new CategoriesField('ProductCategories', false, 'ProductCategory');
        $fields->addFieldToTab("Root.Content.Categories", $categoriesField);
        //Attributes selection
        $anyAttribute = DataObject::get_one('Attribute');
        if ($anyAttribute && $anyAttribute->exists()) {
            $tablefield = new ManyManyComplexTableField($this, 'Attributes', 'Attribute', array('Title' => 'Title', 'Label' => 'Label', 'Description' => 'Description'), 'getCMSFields');
            $tablefield->setPermissions(array());
            $fields->addFieldToTab("Root.Content.Attributes", new HeaderField('AttributeHeading', 'Select attributes for this product', 3));
            $attributeHelp = <<<EOS
<p class="ProductHelp">
Once attributes are selected don't forget to save. 
Always make sure there are options for each attribute and variations which are enabled and have 
an option selected for each attribute.
</p>
EOS;
            $fields->addFieldToTab("Root.Content.Attributes", new LiteralField('AttributeHelp', $attributeHelp));
            $attributeAlert = <<<EOS
<p id="AttributeAlert" class="message good">
Please 'Save' after you have finished changing attributes and check that product variations are correct.
</p>
EOS;
            $fields->addFieldToTab("Root.Content.Attributes", new LiteralField('AttributeAlert', $attributeAlert));
            $fields->addFieldToTab("Root.Content.Attributes", $tablefield);
        }
        //Options selection
        $attributes = $this->Attributes();
        if ($attributes && $attributes->exists()) {
            //Remove the stock level field if there are variations, each variation has a stock field
            $fields->removeByName('Stock');
            $variationFieldList = array();
            $fields->addFieldToTab("Root.Content", new TabSet('Options'));
            $fields->addFieldToTab("Root.Content", new Tab('Variations'));
            foreach ($attributes as $attribute) {
                $variationFieldList['AttributeValue_' . $attribute->ID] = $attribute->Title;
                //TODO refactor, this is a really dumb place to be writing default options probably
                //If there aren't any existing options for this attribute on this product,
                //populate with the default options
                $defaultOptions = DataObject::get('Option', "ProductID = 0 AND AttributeID = {$attribute->ID}");
                $existingOptions = DataObject::get('Option', "ProductID = {$this->ID} AND AttributeID = {$attribute->ID}");
                if (!$existingOptions || !$existingOptions->exists()) {
                    if ($defaultOptions && $defaultOptions->exists()) {
                        foreach ($defaultOptions as $option) {
                            $newOption = $option->duplicate(false);
                            $newOption->ProductID = $this->ID;
                            $newOption->write();
                        }
                    }
                }
                $attributeTabName = str_replace(' ', '', $attribute->Title);
                $fields->addFieldToTab("Root.Content.Options", new Tab($attributeTabName));
                $manager = new OptionComplexTableField($this, $attribute->Title, 'Option', array('Title' => 'Title'), 'getCMSFields_forPopup', "AttributeID = {$attribute->ID}");
                $manager->setAttributeID($attribute->ID);
                $fields->addFieldToTab("Root.Content.Options." . $attributeTabName, $manager);
            }
            $variationFieldList = array_merge($variationFieldList, singleton('Variation')->summaryFields());
            $manager = new VariationComplexTableField($this, 'Variations', 'Variation', $variationFieldList, 'getCMSFields_forPopup');
            if (class_exists('SWS_Xero_Item_Decorator')) {
                $manager->setPopupSize(500, 650);
            }
            $fields->addFieldToTab("Root.Content.Variations", $manager);
        }
        //Product ordering
        $categories = $this->ProductCategories();
        if ($categories && $categories->exists()) {
            $fields->addFieldToTab("Root.Content", new Tab('Order'));
            $fields->addFieldToTab("Root.Content.Order", new HeaderField('OrderHeading', 'Set the order of this product in each of it\'s categories', 3));
            $orderHelp = <<<EOS
<p class="ProductHelp">
Products with higher order numbers in each category will appear further at the front of 
that category.
</p>
EOS;
            $fields->addFieldToTab("Root.Content.Order", new LiteralField('OrderHelp', $orderHelp));
            foreach ($categories as $category) {
                $categoryTitle = $category->Title;
                $categoryID = $category->ID;
                $productID = $this->ID;
                $sql = <<<EOS
SELECT "ProductOrder" 
FROM  "ProductCategory_Products" 
WHERE "ProductCategoryID" = {$categoryID} 
AND "ProductID" = {$productID} 
EOS;
                $query = DB::query($sql);
                $order = $query->value();
                $val = $order ? $order : 0;
                $fields->addFieldToTab('Root.Content.Order', new TextField("CategoryOrder[{$categoryID}]", "Order in {$categoryTitle} Category", $val));
            }
        }
        //Ability to edit fields added to CMS here
        $this->extend('updateProductCMSFields', $fields);
        if (file_exists(BASE_PATH . '/swipestripe') && ShopSettings::get_license_key() == null) {
            $fields->addFieldToTab("Root.Content.Main", new LiteralField("SwipeStripeLicenseWarning", '<p class="message warning">
					 Warning: You have SwipeStripe installed without a license key. 
					 Please <a href="http://swipestripe.com" target="_blank">purchase a license key here</a> before this site goes live.
				</p>'), "Title");
        }
        return $fields;
    }
 /**
  * Output license keys in XML format
  * 
  * @see Page_Controller::init()
  */
 public function init()
 {
     $data = array();
     $data['Key'] = ShopSettings::get_license_key();
     //Find folders that start with swipestripe_, get their license keys
     $base = Director::baseFolder() . '/swipestripe_';
     $dirs = glob($base . '*', GLOB_ONLYDIR);
     $extensionLicenseKeys = ShopSettings::get_extension_license_keys();
     if ($dirs && is_array($dirs)) {
         $data['Extensions'] = array();
         foreach ($dirs as $dir) {
             $extensionName = str_replace($base, '', $dir);
             if ($extensionName) {
                 $data['Extensions'][]['Extension'] = array('Name' => $extensionName, 'Key' => $extensionLicenseKeys[$extensionName]);
             }
         }
     }
     $xml = new SimpleXMLElement("<?xml version=\"1.0\"?><SwipeStripe></SwipeStripe>");
     $this->array_to_xml($data, $xml);
     header("content-type: text/xml");
     print $xml->asXML();
     exit;
 }