<?php

class Mcommerce_Application_Catalog_ProductController extends Application_Controller_Default_Ajax {

    public function editAction() {

        $product = new Catalog_Model_Product();
        if($id = $this->getRequest()->getParam('product_id')) {
            $product->find($id);
            if($product->getId() AND $this->getCurrentOptionValue()->getId() != $product->getValueId()) {
                throw new Exception($this->_('An error occurred during the process. Please try again later.'));
            }
        }

        $mcommerce = $this->getApplication()->getPage('m_commerce')->getObject();

        $html = $this->getLayout()->addPartial('store_form', 'admin_view_default', 'mcommerce/application/edit/catalog/products/edit.phtml')
            ->setCurrentMcommerce($mcommerce)
            ->setOptionValue($mcommerce->getCatalog())
            ->setCurrentProduct($product)
            ->toHtml();

        $html = array('form_html' => $html);

        $this->_sendHtml($html);

    }

    public function editpostAction() {


        if($datas = $this->getRequest()->getPost()) {

            try {
                $isNew = false;
                $option = $this->getCurrentOptionValue();
                $application = $this->getApplication();
//                $datas['product_id'] = 687;
                $product = new Catalog_Model_Product();
                if(!empty($datas['product_id'])) {
                    $product->find($datas['product_id']);
                    if($product->getId() AND $option->getId() != $product->getValueId()) {
                        throw new Exception($this->_('An error occurred while saving. Please try again later.'));
                    }
                }

                if(!$product->getId()) {
                    $datas['value_id'] = $option->getId();
                    $datas['mcommerce_id'] = $this->getApplication()->getPage('m_commerce')->getObject()->getId();
                    $isNew = true;
                }

                if(!empty($datas['picture'])) {
                    $relative_path = '/features/mcommerce/product/';
                    $folder = Application_Model_Application::getBaseImagePath() . $relative_path;
                    $path = Application_Model_Application::getBaseImagePath() . $relative_path;
                    $file = Core_Model_Directory::getTmpDirectory(true).'/'.$datas['picture'];

                    if(file_exists($file)) {
                        if(!is_dir($path)) mkdir($path, 0777, true);
                        if(!copy($file, $folder.$datas['picture'])) {
                            throw new exception($this->_('An error occurred while saving. Please try again later.'));
                        } else {
                            $datas['picture'] = $relative_path.$datas['picture'];
                        }
                    } else if(!file_exists(Application_Model_Application::getBaseImagePath().$datas['picture'])) {
                        $datas['remove_picture'] = true;
                    }
                }

                if(!empty($datas['remove_picture'])) {
                    $datas['picture'] = null;
                }

                $product->addData($datas);

                $isDeleted = $product->getIsDeleted();
                $productId = $product->getId();

                $product->save();

                if(!$isDeleted) {
                    $productId = $product->getId();
                }

                if(!empty($datas['group']) AND !$product->getIsDeleted()) {

                    $group_ids = array();
                    $groups = $product->getGroups();
                    foreach($datas['group'] as $group_datas) {
                        if(!empty($group_datas['group_id'])) $group_ids[] = $group_datas['group_id'];
                    }
                    // Supprime tous les groups qui ont été décochés
                    foreach($groups as $group) {
                        if(!in_array($group->getGroupId(), $group_ids)) $group->delete();
                    }

                    foreach($datas['group'] as $group_datas) {
                        if(empty($group_datas['group_id'])) continue;

                        $group = new Catalog_Model_Product_Group_Value();
                        if(!$isNew) {
                            $group->find(array('product_id' => $product->getId(), 'group_id' => $group_datas['group_id']));
                            // Supprime le groupe dont toutes les options ont été décochées mais pas lui
                            if(empty($group_datas['new_option_value'])) $group_datas['is_deleted'] = 1;
                        }
                        if(!$group->getId()) {
                            $group_datas['product_id'] = $product->getId();
                        }

                        $group->addData($group_datas)->save();
                    }
                }

                $html = array(
                    'picture' => $datas['picture'],
                    'is_new' => (int) $isNew,
                    'is_deleted' => (int) $isDeleted,
                    'product_id' => $productId,
                    'success' => '1',
                    'success_message' => $this->_('Product successfully saved'),
                    'message_timeout' => 2,
                    'message_button' => 0,
                    'message_loader' => 0
                );

                $html['product'] = array(
                    'name' => Core_Model_Lib_String::truncate($product->getName(), 25),
                    'description' => Core_Model_Lib_String::truncate($product->getDescription(), 25),
                    'formatted_price' => $product->getFormattedPrice($application->getCountryCode())
                );

            }
            catch(Exception $e) {
                $html = array(
                    'error' => 1,
                    'message' => $e->getMessage(),
                    'message_button' => 1,
                    'message_loader' => 1
                );
            }

            $this->_sendHtml($html);

        }

    }

}