<?php

require_once dirname(__FILE__).'/../lib/catGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/catGeneratorHelper.class.php';

/**
 * cat actions.
 *
 * @package    sf
 * @subpackage cat
 * @author     Atma
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class catActions extends autoCatActions
{
    static public $parentId = null;
    public function executeDelete(sfWebRequest $request)
    {
        $this->dispatcher->notify(new sfEvent($this, 'admin.delete_object', array('object' => $this->getRoute()->getObject())));
        $cat = $this->getRoute()->getObject();

        $children_count = Doctrine_Query::create()
            ->from("Cat")
            ->where("parent_id = ?", $cat->getId())
            ->count();
        $product_count = Doctrine_Query::create()
            ->from("Product p")
            ->innerJoin("p.Cats c")
            ->where("c.id = ?", $cat->getId())
            ->count();
        if($children_count == 0 && $product_count == 0){
            $cat->delete();
            echo 'ok';
        }else{
            echo 'no';
        }
        return sfView::NONE;
    }
    protected function buildQuery()
    {
        $query = parent::buildQuery();
        $query->leftJoin("r.Translation t");
        $query->andWhere("r.parent_id IS NULL");
        return $query;
    }
    public function executeUpdate(sfWebRequest $request)
    {
        parent::executeUpdate($request);
        return sfView::NONE;
    }
    public function executeCreate(sfWebRequest $request)
    {
        parent::executeCreate($request);
        return sfView::NONE;
    }
    protected function processForm(sfWebRequest $request, sfForm $form)
    {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid())
        {
            try
            {
                $cat = $form->save();
                echo $this->getPartial('cat/struct_form', array('form' => new CatForm($cat), 'parent_id' => Cat::$parentId, 'link' => '/arm/cat' . ($cat ? '/' . $cat->getId() : '')));
                return sfView::NONE;
            }
            catch (Doctrine_Validator_Exception $e)
            {
                $errorStack = $form->getObject()->getErrorStack();
                return sfView::NONE;
            }
            $this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $cat)));
        }
        echo $this->getPartial('cat/struct_form', array('form' => $form, 'parent_id' => Cat::$parentId, 'link' => '/arm/cat' . ($this->cat && $this->cat->getId() ? '/' . $this->cat->getId() : '')));
    }
    public function executeStruct(sfWebRequest $request)
    {
        if(strpos($request->getPathInfo(), 'Blank') !== false){
            $type = false;
            foreach (array('cat', 'product', 'offer') as $t){
                if(strpos($request->getParameter('Id'), $t) !== false){
                    $type = $t;
                    break;
                }
            }
            if(!$type){
                $type = 'cat';
                if($request->getParameter('object_Group') == 1){
                    $type = 'product';
                }elseif($request->getParameter('object_Group') == 3){
                    $type = 'offer';
                }
            }
            if($type){
                $id = str_replace(array('cat', 'product', 'offer', '_'), '', $request->getParameter('Id'));
                if($type == 'cat'){
                    $cat = ($id ? Doctrine::getTable("Cat")->find($id) : null);
                    $form = new CatForm($cat, array('struct' => true));
                }elseif($type == 'product'){
                    $product = ($id ? Doctrine::getTable("Product")->find($id) : null);
                    $form = new ProductForm($product, array('struct' => true));
                }elseif($type == 'offer'){
                    $offer = ($id ? Doctrine::getTable("Offer")->find($id) : null);
                    $form = new OfferForm($offer);
                }
                Cat::$parentId = $request->getParameter('parentId');
                echo $this->getPartial('struct_form', array('link' => '/arm/' . $type . ($id ? '/' . $id : ''), 'parent_id' => Cat::$parentId, 'form' => $form));
            }
        }elseif(strpos($request->getPathInfo(), 'List') !== false){
            $id = str_replace(array('cat', 'product', 'offer', '_'), '', $request->getParameter('parentId'));
            if($id && is_numeric($id)){
                if(strpos($request->getParameter('parentId'), 'cat') !== false){
                    $cats = Doctrine_Query::create()
                        ->select("c.id, c.parent_id, t.*")
                        ->from("Cat c")
                        ->innerJoin("c.Translation  t")
                        ->where("c.parent_id = ?", $id)
                        ->orderBy("c.sort ASC")
                        ->fetchArray();
                    $products = Doctrine_Query::create()
                        ->select("p.id, p.is_delete, t.title, t.lang")
                        ->from("Product p")
                        ->innerJoin("p.Translation t")
                        ->innerJoin("p.CatProduct c")
                        ->where("c.cat_id = ?", $id)
                        ->andWhere("p.is_delete = 0")
                        ->orderBy("p.sort ASC")
                        ->fetchArray();
                    echo $this->getPartial('struct', array('results' => array('cat' => $cats, 'product' => $products)));
                }elseif(strpos($request->getParameter('parentId'), 'product') !== false){
                    $product = Doctrine::getTable("Product")->find($id);
                    $offers = Doctrine_Query::create()
                        ->select("o.id, o.product_id, o.is_delete, t.lang, t.title, ")
                        ->from("Offer o")
                        ->innerJoin("o.Translation  t")
                        ->where("o.product_id = ?", $id)
                        ->andWhere("o.is_delete = 0")
                        ->orderBy("o.sort ASC")
                        ->fetchArray();
                    echo $this->getPartial('struct', array('results' => array('offer' => $offers), 'is_detail' => ($product && $product->getIsDetail())));
                }
            }else{
                $cats = Doctrine_Query::create()
                    ->select("c.id, c.parent_id, t.*")
                    ->from("Cat c")
                    ->innerJoin("c.Translation  t")
                    ->where("c.parent_id IS NULL")
                    ->orderBy("c.sort ASC")
                    ->fetchArray();
                echo $this->getPartial('struct', array('results' => array('cat' => $cats)));
            }
        }
        return sfView::NONE;
    }
    public function executeSort(sfWebRequest $request)
    {
        $array = explode(',', $request->getParameter('SetSort'));
        $ids = array();
        foreach ($array as $key => $item)
        {
            $table = preg_replace("/[^a-z]/", '', $item);
            $ids[$key] = preg_replace("/[^0-9]/", '', $item);

            if ($table == 'offer')
            {
                Doctrine_Query::create()
                    ->update($table)
                    ->set("sort", intval($key))
                    ->where("id = ?", intval($ids[$key]))
                    ->execute();
            }else
            {
                Doctrine::getTable($table)->findOneById(intval($ids[$key]))->setSort(intval($key))->save();
            }
            


        }
        return sfView::NONE;
    }
    public function executeIndex(sfWebRequest $request)
    {

        // sorting
        if ($request->getParameter('sort') && $this->isValidSortColumn($request->getParameter('sort')))
        {
            print_r($request->getParameter('sort'));
            die();
            $this->setSort(array($request->getParameter('sort'), $request->getParameter('sort_type')));

        }

        // pager
        if ($request->getParameter('page'))
        {
            $this->setPage($request->getParameter('page'));
        }
        else
        {
            $this->setPage(1);
        }

        //search
        if ($request->getParameter('q'))
        {
            $this->setSearch($request->getParameter('q'), ($request->hasParameter('checked') ? $request->getParameter('checked') : false));
        }
        else
        {
            $this->setSearch(false);
        }

        //checked
        if ($request->getParameter('checked'))
        {
            $this->setChecked($request->getParameter('checked'));
        }
        else
        {
            $this->setChecked(false);
        }

        $this->pager = $this->getPager($request);
        $this->sort = $this->setSort(array(
            0 => 'sort',
            1 => 'ASC'
        ));





        if($request->hasParameter('export'))
        {

            require_once sfConfig::get('sf_lib_dir') . '/Classes/PHPExcel.php';
            $objPHPExcel = new PHPExcel();
            $sheet = $objPHPExcel->setActiveSheetIndex(0);
            $sheet->setCellValue('A1', 'Название');
            $styleArray = array(
                'font' => array(
                    'bold' => true,
                )
            );


            $sheet->getStyle('A1')->applyFromArray($styleArray);

            $sheet->setCellValue('B1', 'Алиас');
            $styleArray = array(
                'font' => array(
                    'bold' => true,
                )
            );


            $sheet->getStyle('B1')->applyFromArray($styleArray);

            $sheet->setCellValue('C1', 'Родительская категория');
            $styleArray = array(
                'font' => array(
                    'bold' => true,
                )
            );


            $sheet->getStyle('C1')->applyFromArray($styleArray);


            foreach ($this->pager->getResults() as $i => $cat)
            {
                $value = '';

                ob_start();
                ob_implicit_flush(0);

                try
                {
                    require(sfConfig::get('sf_app_module_dir') . '/cat/templates/_title.php');
                }
                catch (Exception $e)
                {
                    ob_end_clean();
                    throw $e;
                }

                $value = ob_get_clean();





                $sheet->setCellValue('A' . ($i + 2), $value);
                $sheet->getColumnDimension('A')->setAutoSize(true);

                $value = '';
                $method = 'getAlias';

                if(is_callable(array($cat, 'getAlias')))
                {
                    $method = $cat->$method();
                    if(is_object($method) && count($method) > 0)
                    {
                        $value = $method->__toString();
                    }

                    else
                    {
                        $value = $method;
                    }
                }



                $sheet->setCellValue('B' . ($i + 2), $value);
                $sheet->getColumnDimension('B')->setAutoSize(true);

                $value = '';

                ob_start();
                ob_implicit_flush(0);

                try
                {
                    require(sfConfig::get('sf_app_module_dir') . '/cat/templates/_parent_id.php');
                }
                catch (Exception $e)
                {
                    ob_end_clean();
                    throw $e;
                }

                $value = ob_get_clean();





                $sheet->setCellValue('C' . ($i + 2), $value);
                $sheet->getColumnDimension('C')->setAutoSize(true);

            }
            $sheet->setAutoFilter('A1:C' . $i);
            $sheet->setTitle('Каталог');
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $uuid = Page::generateUuid();

            $objWriter->save('php://output');
            $this->getResponse()->setHttpHeader('Content-type', 'application/octet-stream');
            $this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename="Каталог.xlsx"');

            return sfView::NONE;

        }
    }
}
