/**
  * Adds member select fields to CMS
  * 
  * @param FieldSet $fields
  * @return void
  */
 public function updateCMSFields(FieldSet &$fields)
 {
     // Only modify folder objects with parent nodes
     if (!$this->owner instanceof Folder || !$this->owner->ID) {
         return;
     }
     // Only allow ADMIN and SECURE_FILE_SETTINGS members to edit these options
     if (!Permission::checkMember(Member::currentUser(), array('ADMIN', 'SECURE_FILE_SETTINGS'))) {
         return;
     }
     // Update Security Tab
     $secureFilesTab = $fields->findOrMakeTab('Root.' . _t('SecureFiles.SECUREFILETABNAME', 'Security'));
     $secureFilesTab->push(new HeaderField(_t('SecureFiles.MEMBERACCESSTITLE', 'Member Access')));
     //_t('SecureFiles.MEMBERACCESSFIELD', 'Member Access Permissions')
     $secureFilesTab->push($memberTableField = new ManyManyComplexTableField($this->owner, 'MemberPermissions', 'Member', null));
     $memberTableField->setPermissions(array());
     if ($this->owner->InheritSecured()) {
         $permissionMembers = $this->owner->InheritedMemberPermissions();
         if ($permissionMembers->Count()) {
             $fieldText = implode(", ", $permissionMembers->map('ID', 'Name'));
         } else {
             $fieldText = _t('SecureFiles.NONE', "(None)");
         }
         $InheritedMembersField = new ReadonlyField("InheritedMemberPermissionsText", _t('SecureFiles.MEMBERINHERITEDPERMS', 'Inherited Member Permissions'), $fieldText);
         $InheritedMembersField->addExtraClass('prependUnlock');
         $secureFilesTab->push($InheritedMembersField);
     }
 }
 protected function getProductGroupsTable()
 {
     $tableField = new ManyManyComplexTableField($this, 'ProductGroups', 'ProductGroup', array('Title' => 'Product Group Page Title'));
     $tableField->setPageSize(30);
     $tableField->setPermissions(array());
     return $tableField;
 }
    /**
     * 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;
    }