<?php

abstract class TM_Argento_Model_Upgrade extends TM_Core_Model_Module_Upgrade
{
    /**
     * Get basic configuration settings for Magento adn extensions
     *
     * @param  string $themeName
     * @return array
     */
    public function getDefaultConfiguration($themeName)
    {
        return array( // @todo split into each module, if custom config is not needed
            'design' => array(
                'package/name' => 'argento',
                'theme' => array(
                    'template' => $themeName,
                    'skin'     => $themeName,
                    'layout'   => $themeName,
                    'after_default' => Mage::helper('argento')->isEnterprise() ?
                        'enterprise/default' : ''
                )
            ),

            'ajax_pro' => array(
                'general' => array(
                    'enabled' => 1,
                    'useLoginFormBlock' => 1
                ),
                'effect' => array(
                    'opacity' => 1,
                    'enabled_overlay' => 1,
                    'overlay_opacity' => 0.5
                ),
                'checkoutCart' => array(
                    'enabled'     => 1,
                    'enabledForm' => 1,
                    'messageHandle' => 'tm_ajaxpro_checkout_cart_add_suggestpage'
                ),
                'catalogProductCompare' => array(
                    'enabled'     => 1,
                    'enabledForm' => 1
                ),
                'wishlistIndex' => array(
                    'enabled'     => 1,
                    'enabledForm' => 1
                ),
                'catalogCategoryView' => array(
                    'enabled' => 1,
                    'type' => 'button'
                )
            ),

            'easycatalogimg' => array(
                'general/enabled' => 1,
                'category' => array(
                    'enabled_for_default' => 0,
                    'enabled_for_anchor'  => 0
                )
            ),

            'facebooklb' => array(
                'category_products' => array(
                    'enabled'   => 0,
                    'send'      => 0,
                    'layout'    => 'button_count',
                    'color'     => 'light'
                ),
                'productlike' => array(
                    'enabled'   => 1,
                    'send'      => 1,
                    'layout'    => 'button_count',
                    'color'     => 'light',
                    'image_width' => '512',
                    'image_height' => '512',
                    'image_keep_frame' => '0'
                )
            ),

            'tm_ajaxsearch/general' => array(
                'enabled'              => 1,
                'show_category_filter' => 1,
                'attributes'           => 'name,sku'
            ),

            'tm_easytabs/general' => array(
                'enabled' => 1
            ),

            'soldtogether' => array(
                'general' => array(
                    'enabled' => 1,
                    'random'  => 1
                ),
                'order' => array(
                    'enabled'           => 1,
                    'addtocartcheckbox' => 0,
                    'amazonestyle'      => 1
                ),
                'customer/enabled' => 1
            ),

            'richsnippets/general' => array(
                'enabled' => 1
            ),

            'askit/general/enabled'       => 1,
            'prolabels/general' => array(
                'enabled' => 1,
                'mobile'  => 0
            ),

            'lightboxpro' => array(
                'general/enabled' => 1,
                'size' => array(
                    'main'      => '512x512',
                    'thumbnail' => '112x112',
                    'maxWindow' => '800x600'
                )
            ),
            'navigationpro/top/enabled'   => 1,
            'suggestpage/general/show_after_addtocart' => 1,
            'testimonials/general/enabled' => 1
        );
    }

    /**
     * Get data for CMS block `services_sidebar`
     *
     * @return array
     */
    public function getSidebarBlockServices()
    {
        return array(
                'title'      => 'services_sidebar',
                'identifier' => 'services_sidebar',
                'status'     => 1,
                'content'    => <<<HTML
<div class="block block-services-sidebar">
    <div class="block-title"><span>Our Services</span></div>
    <div class="block-content">
        <div class="icon-section section-delivery section-left">
            <span class="fa-stack fa-2x icons-primary">
                <i class="fa fa-circle fa-stack-2x">&#8203;</i>
                <i class="fa fa-truck fa-stack-1x fa-inverse">&#8203;</i>
            </span>
            <div class="section-info">
                <h5>Delivery</h5>
                <p>We guarantee to ship your order next day after order has been submitted</p>
            </div>
        </div>
        <div class="icon-section section-customer-service section-left">
            <span class="fa-stack fa-2x icons-primary">
                <i class="fa fa-circle fa-stack-2x">&#8203;</i>
                <i class="fa fa-users fa-stack-1x fa-inverse">&#8203;</i>
            </span>
            <div class="section-info">
                <h5>Customer Service</h5>
                <p>Please contacts us and our customer service team will answer all your questions</p>
            </div>
        </div>
        <div class="icon-section section-returns section-left">
            <span class="fa-stack fa-2x icons-primary">
                <i class="fa fa-circle fa-stack-2x">&#8203;</i>
                <i class="fa fa-reply fa-stack-1x fa-inverse">&#8203;</i>
            </span>
            <div class="section-info">
                <h5>Easy Returns</h5>
                <p>If you are not satisfied with your order - send it back within  30 days after day of purchase!</p>
            </div>
        </div>
    </div>
</div>
HTML
            );
    }

    /**
     * Get data for CMS block `product_sidebar`
     *
     * @return array
     */
    public function getSidebarBlockProduct()
    {
        return array(
                'title'      => 'product_sidebar',
                'identifier' => 'product_sidebar',
                'status'     => 1,
                'content'    => <<<HTML
<div class="block block-product-sidebar">
    <div class="block-content">
        {{widget type="attributepages/product_option" template="tm/attributepages/product/options.phtml" width="180" height="90" use_image="1" image_type="image" use_link="1" attribute_code="manufacturer" css_class="hidden-label"}}
        {{widget type="cms/widget_block" template="cms/widget/static_block/default.phtml" block_id="services_sidebar"}}
    </div>
</div>
HTML
            );
    }

    /**
     * Get data for CMS block `footer_payments`
     *
     * @return array
     */
    public function getFooterBlockPayments()
    {
        return array(
                'title'      => 'footer_payments',
                'identifier' => 'footer_payments',
                'status'     => 1,
                'content'    => <<<HTML
<img class="payments" src="{{skin url='images/payments.png'}}"
            srcset="{{skin url='images/payments.png'}} 1x, {{skin url='images/payments@2x.png'}} 2x"
            alt="Payment methods"/>
HTML
            );
    }

    /**
     * Get visible products fro store
     *
     * @param  integer $storeId
     * @param  Mage_Catalog_Model_Category $category
     * @param  integer $pageSize
     * @param  integer $curPage
     * @return TM_Highlight_Model_Resource_Eav_Mysql4_Catalog_Product_Collection
     */
    public function getVisibleProducts($storeId, $category, $pageSize = 10, $curPage = 1)
    {
        $visibility = Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds();
        $visibleProducts = Mage::getResourceModel('highlight/catalog_product_collection');
        $visibleProducts
            ->setStoreId($storeId)
            ->setVisibility($visibility)
            ->addStoreFilter($storeId)
            ->addCategoryFilter($category)
            ->addAttributeToSort('entity_id', 'desc')
            ->setPageSize($pageSize)
            ->setCurPage($curPage);
        foreach ($visibleProducts as $product) {
            $product->load($product->getId());
        }

        return $visibleProducts;
    }

    /**
     * Check is there are any new products at store and category
     *
     * @param  integer $storeId
     * @param  Mage_Catalog_Model_Category $category
     * @return boolean
     */
    public function existNewProducts($storeId, $category)
    {
        $visibility = Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds();
        $todayStartOfDayDate  = Mage::app()->getLocale()->date()
            ->setTime('00:00:00')
            ->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
        $todayEndOfDayDate  = Mage::app()->getLocale()->date()
            ->setTime('23:59:59')
            ->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
        $newProducts = Mage::getResourceModel('highlight/catalog_product_collection');
        $newProducts
            ->setStoreId($storeId)
            ->setVisibility($visibility)
            ->addStoreFilter($storeId)
            ->addCategoryFilter($category)
            ->addAttributeToFilter('news_from_date', array('or'=> array(
                0 => array('date' => true, 'to' => $todayEndOfDayDate),
                1 => array('is' => new Zend_Db_Expr('null')))
            ), 'left')
            ->addAttributeToFilter('news_to_date', array('or'=> array(
                0 => array('date' => true, 'from' => $todayStartOfDayDate),
                1 => array('is' => new Zend_Db_Expr('null')))
            ), 'left')
            ->addAttributeToFilter(
                array(
                    array('attribute' => 'news_from_date', 'is'=>new Zend_Db_Expr('not null')),
                    array('attribute' => 'news_to_date', 'is'=>new Zend_Db_Expr('not null'))
                )
            )
            ->addAttributeToSort('news_from_date', 'desc')
            ->setPageSize(1)
            ->setCurPage(1);
        return (bool)$newProducts->count();
    }

    /**
     * Check if product with $attributeCode == 'Yes' exists
     *
     * @param  string $attributeCode
     * @param  integer $storeId
     * @param  Mage_Catalog_Model_Category $category
     * @return boolean
     */
    public function existProductsWithAttribute($attributeCode, $storeId, $category)
    {
        $visibility = Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds();
        $collection = Mage::getResourceModel('highlight/catalog_product_collection');
        $collection
            ->setStoreId($storeId)
            ->setVisibility($visibility)
            ->addStoreFilter($storeId)
            ->addCategoryFilter($category)
            ->setPageSize(1)
            ->setCurPage(1);
        if (!$collection->getAttribute($attributeCode)) { // Mage 1.6.0.0 fix
            return true;
        }

        $collection->addAttributeToFilter("{$attributeCode}", array('Yes' => true));
        return (bool)$collection->count();
    }

    /**
     * Setup attribute values for products
     *
     * @param  array $attributesToSetup
     */
    public function setupProducts($attributesToSetup)
    {
        $isAddNewProducts = in_array('new', $attributesToSetup);
        $attributes = array_diff($attributesToSetup, array('new'));
        $todayStartOfDayDate  = Mage::app()->getLocale()->date()
            ->setTime('00:00:00')
            ->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
        foreach ($this->getStoreIds() as $storeId) {
            if ($storeId) {
                $store = Mage::app()->getStore($storeId);
            } else {
                $store = Mage::app()->getDefaultStoreView();
            }
            if (!$store) {
                continue;
            }
            $storeId = $store->getId();
            $rootCategory = Mage::getModel('catalog/category')->load($store->getRootCategoryId());

            if (!$rootCategory) {
                continue;
            }

            $visibleProducts = $this->getVisibleProducts($storeId, $rootCategory);
            if (!$visibleProducts->count()) {
                continue;
            }

            // NEW PRODUCTS
            // check if there are any new products else add some
            if ($isAddNewProducts && !$this->existNewProducts($storeId, $rootCategory)) {
                foreach ($visibleProducts as $product) {
                    $product->setStoreId($storeId);
                    $product->setNewsFromDate($todayStartOfDayDate);
                    $product->save();
                }
            }

            // OTHER PRODUCT ATTRIBUTES
            foreach ($attributes as $attributeCode) {
                if (!$this->existProductsWithAttribute($attributeCode, $storeId, $rootCategory)) {
                    foreach ($visibleProducts as $product) {
                        // attribute should be saved in global scope
                        if (!in_array(Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID, $this->getStoreIds())) {
                            $product->addAttributeUpdate($attributeCode, 0, Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID);
                        }

                        $product->setStoreId($storeId);
                        $product->setData($attributeCode, 1);
                        $product->save();
                    }
                }
            }
        }
    }
}
