<?php

abstract class TM_SoldTogether_Controller_Adminhtml_Abstract
    extends Mage_Adminhtml_Controller_Action
{
    /**
     * Max number of order to process per run of reindexAction
     *
     * @var integer
     */
    protected $_orderCount  = 20;

    /**
     * Max seconds for one run of reindexAction
     *
     * @var integer
     */
    protected $_processTime = 20;

    /**
     * Title of grid in admin
     *
     * @var string
     */
    protected $_soldtogetherTitle;

    /**
     * Message "in progress" for reindexAction
     *
     * @var string
     */
    protected $_inProgressMessage;

    /**
     * Message "on success" for reindexAction
     *
     * @var string
     */
    protected $_successMessage;

    /**
     * Index action
     */
    public function indexAction()
    {
        $this->_title($this->__('TM'))
            ->_title($this->__('Sold Together'))
            ->_title($this->__($this->_soldtogetherTitle));
        $this->loadLayout();
            $this->_setActiveMenu('templates_master/soldtogether');
        $this->renderLayout();
    }

    /**
     * Edit item action
     */
    public function editAction()
    {
        $this->_title($this->__('TM'))
            ->_title($this->__('Sold Together'))
            ->_title($this->__($this->_soldtogetherTitle))
            ->_title($this->__('Edit Item'));
        $relationId = $this->getRequest()->getParam('id');
        $model = $this->_getSoldtogetherModel()->load($relationId);
        if ($model->getId()) {
            Mage::register('soldtogether_data', $model);
            $this->loadLayout();
            $this->_setActiveMenu('templates_master/soldtogether');
            $this->renderLayout();
        } else {
            $this->_getSession()->addError(
                $this->_getHelper()->__('Item does not exist')
            );
            $this->_redirect('*/*/');
        }
    }

    /**
     * Delete item action
     */
    public function deleteAction()
    {
        if ($this->getRequest()->getParam('id') > 0) {
            try {
                $model = $this->_getSoldtogetherModel();
                $model->setId($this->getRequest()->getParam('id'))->delete();
                $this->_getSession()->addSuccess(
                    $this->_getHelper()->__('Item was successfully deleted')
                );
                $this->_redirect('*/*/');
            } catch (Exception $e) {
                $this->_getSession()->addError($e->getMessage());
                $this->_redirect(
                    '*/*/edit',
                    array(
                        'id' => $this->getRequest()->getParam('id')
                    )
                );
                return;
            }
        }

        $this->_redirect('*/*/');
    }

    /**
     * Save item action
     */
    public function saveAction()
    {
        if ($this->getRequest()->getPost()) {
            try {
                $postData = $this->getRequest()->getPost();
                $model = $this->_getSoldtogetherModel();
                $model
                    ->setId($this->getRequest()->getParam('relation_id'))
                    ->setWeight($postData['weight'])
                    ->setIsAdmin(1)
                    ->save();

                Mage::getSingleton('adminhtml/session')->addSuccess(
                    $this->_getHelper()->__('Item was successfully saved')
                );
                Mage::getSingleton('adminhtml/session')
                    ->setsoldtogetherData(false);
                $this->_redirect('*/*/');
                return;
            } catch (Exception $e) {
                $this->_getSession()->addError($e->getMessage());
                $this->_getSession()->setsoldtogetherData(
                    $this->getRequest()->getPost()
                );
                $this->_redirect(
                    '*/*/edit',
                    array(
                        'id' => $this->getRequest()->getParam('related_id')
                    )
                );
                return;
            }
        }

        $this->_redirect('*/*/');
    }

    /**
     * Mass delete action
     */
    public function massDeleteAction()
    {
        $relationIds = $this->getRequest()->getParam('relation_id');
        if (!is_array($relationIds)) {
            $this->_getSession()->addError($this->__('Please select items.'));
        } else {
            try {
                foreach ($relationIds as $relationId) {
                    $relation = $this->_getSoldtogetherModel()->load($relationId);
                    $relation->delete();
                }
                $this->_getSession()->addSuccess(
                    $this->__(
                        'Total of %d record(s) have been deleted.',
                        count($relationIds)
                    )
                );
            } catch (Exception $e) {
                $this->_getSession()->addError($e->getMessage());
            }
        }
        $this->_redirect('*/*/index');
    }

    /**
     * Grid for Ajax request
     */
    public function gridAction()
    {
        $this->loadLayout();
        $this->renderLayout();
    }

    /**
     * Grid at edit product
     */
    public function relatedAction()
    {
        $this->loadLayout();
        $this->renderLayout();
    }

    /**
     * Grid for Ajax request at edit product
     */
    public function relatedGridAction()
    {
        $this->loadLayout();
        $this->renderLayout();
    }

    public function reindexAction()
    {
        $model = $this->_getSoldtogetherModel();
        if ($this->getRequest()->getParam('clear_session')) {
            $obj = new Varien_Object();
            $this->_getSession()->setData('soldtogether_object', $obj);
            $model->getResource()->clearTable();
            $obj->setQueryStep(1);
            $obj->setProcessed(0);
        } else {
            $obj = $this->_getSession()->getData('soldtogether_object');
        }

        $page = $obj->getQueryStep();
        $itemsProcessed = $model->reindexRelations($page);
        if ($itemsProcessed > 0) {
            $obj->setProcessed($obj->getProcessed() + $itemsProcessed);
            $obj->setQueryStep($page + 1);
            return $this->getResponse()->setBody(
                Mage::helper('core')->jsonEncode(
                    array(
                        'completed' => false,
                        'message'   => Mage::helper('soldtogether')->__(
                            $this->_inProgressMessage,
                            $obj->getProcessed()
                        )
                    )
                )
            );
        } else {
            $this->_getSession()->unsetData('soldtogether_object');
            $this->_getSession()->addSuccess(
                Mage::helper('soldtogether')->__(
                    $this->_successMessage, $obj->getProcessed()
                 )
            );
            $this->getResponse()->setBody(
                Mage::helper('core')->jsonEncode(
                    array(
                        'processed' => $obj->getProcessed(),
                        'completed' => true,
                        'message'   => Mage::helper('soldtogether')->__(
                            $this->_inProgressMessage, $obj->getProcessed()
                        )
                    )
                )
            );
        }
    }

    /**
     * Check permissions
     *
     * @return boolean
     */
    protected function _isAllowed()
    {
        $nodeName = str_replace('_', '/', $this->_request->getControllerName());
        return Mage::getSingleton('admin/session')
            ->isAllowed('templates_master/' . $nodeName);
    }

    /**
     * Get model base on controller name
     *
     * @return Mage_Core_Model_Abstract
     */
    protected function _getSoldtogetherModel()
    {
        $modelName = str_replace('_', '/', $this->_request->getControllerName());
        return Mage::getModel($modelName);
    }

}
