<?php

/**
 * category actions.
 *
 * @package    tvtl
 * @subpackage category
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2288 2006-10-02 15:22:13Z fabien $
 */
class categoryActions extends autocategoryActions
{
    protected function addSortCriteria($c) {
      //$c = new Criteria();
      //$c->addAscendingOrderByColumn('orderPath(cg_family)');
    }

    public function executeList()
  {
    //$this->processSort();

    $this->processFilters();

    $this->filters = $this->getUser()->getAttributeHolder()->getAll('sf_admin/tblcategory/filters');

    // pager
    $this->pager = new sfPropelPager('Tblcategory', 100);
    $c = new Criteria();
    $this->addFiltersCriteria($c);
    $this->addSortCriteria($c);
    $this->pager->setCriteria($c);
    $this->pager->setPage($this->getRequestParameter('page', 1));
    $this->pager->init();
  }

    /**
     * Enter description here...
     *
     * @param unknown_type $tblcategory
     */
    protected function saveTblcategory($tblcategory)
    {
        $tblcategory->save();
        //create dir for this category
        $real_upload_dir = sfConfig::get('sf_upload_dir');
        if (!is_dir( "$real_upload_dir/resources/".$tblcategory->getCgId())) {
            mkdir("$real_upload_dir/resources/".$tblcategory->getCgId());
            if (!is_dir( "$real_upload_dir/resources/".$tblcategory->getCgId().'/thumbnails'))
                mkdir("$real_upload_dir/resources/".$tblcategory->getCgId().'/thumbnails');
        }
        if ( $tblcategory->getCgParentid() != -1) {
            $cat = TblcategoryPeer::retrieveByPK($tblcategory->getCgParentid());
            $cgFamily = $cat->getCgFamily().'/'.$tblcategory->getCgId();
        }
        else {
            $cgFamily = $tblcategory->getCgId();
        }

        $tblcategory->setCgFamily($cgFamily);
        $tblcategory->save();
        //Tblcategory::save()
        //update tree category
        $this->updateTreeSubCat($tblcategory);
    }

    /**
     * move all sub category to new tree
     *
     * @param Tblcategory $tblcategory
     */
    protected  function updateTreeSubCat($tblcategory) {
        $c = new Criteria();
        $c->add(TblcategoryPeer::CG_PARENTID, $tblcategory->getCgId());
        $cats = TblcategoryPeer::doSelect($c);
        //updateDocument
        $this->updateDocCatTable( $tblcategory);
        foreach ($cats as $cat) {
            //updateCategory
            $cat->setCgFamily($tblcategory->getCgFamily().'/'.$cat->getCgId());
            $cat->save();
            $this->updateTreeSubCat($cat);
        }
    }

    /**
     * update document when edit category
     *
     * @param Tblcategory $tblcategory
     */
    protected function updateDocCatTable( $tblcategory) {
        $c = new Criteria();
        $c->add(TbldocumentPeer::DOC_CATEGORY ,$tblcategory->getCgId());
        $documents = TbldocumentPeer::doSelect($c);
        if($documents) {
            foreach ($documents as $document) {
                //var_dump($document);
                //remove from categorydocment
                $c->clear();
                $c->add(TblcategorydocumentPeer::CD_DOCUMENT ,$document->getDocId());
                TblcategorydocumentPeer::doDelete($c);
                //update
                $cats = explode('/', $tblcategory->getCgFamily());
                foreach ($cats as $cat) {
                    $catDoc = new Tblcategorydocument();
                    $catDoc->setCdCategory($cat);
                    $catDoc->setCdDocument($document->getDocId());
                    $catDoc->setCdUpload(0);
                    $catDoc->save();
                }
            }//foreach
        }//if
    }
    /**
     * Enter description here...
     *
     * @param unknown_type $tblcategory
     */
    protected function deleteTblcategory($tblcategory) {

        // check contain document
        $c = new  Criteria();
        $c->add(TbldocumentPeer::DOC_CATEGORY  ,$tblcategory->getCgId());
        $numSubDoc = TbldocumentPeer::doCount($c);
        //var_dump($numSubDoc);

        // check contain sub category
        $c = new  Criteria();
        $c->add(TblcategoryPeer::CG_PARENTID ,$tblcategory->getCgId());
        $numSubCat = TblcategoryPeer::doCount($c);
        //var_dump($numSubCat);
        if($numSubDoc == 0 && $numSubCat == 0) {
            //if(is_dir(sfConfig::get('sf_upload_dir')."/resources/".$tblcategory->getCgId()))
                //rmdir(sfConfig::get('sf_upload_dir')."/resources/".$tblcategory->getCgId());
            $tblcategory->delete();
        }
        else {
            $this->getRequest()->setError('delete', 'Could not delete the selected category. Make sure it does not have any associated sub categor and item.');
            return $this->forward('category', 'list');
        }
        //$this->setTemplate('');
    }

	public function handleError()
    {
        return sfView::ERROR;
    }

    public function handleErrorDelete()
    {
    	return sfView::SUCCESS;
    }
    /**
     * view all document of this category
     *
     */
    public function executeDocuments(){
		$this->redirect('document/list?filter=filter&filters[doc_category]='.$this->getRequestParameter('cg_id'));
	}

	public function executeDel() {
        /*$id_list = $this->getRequestParameter('idList');
        $page = $this->getRequestParameter('page');
        $id_array = explode(",", $id_list);

        $c = new  Criteria();
        $c->add(TblcategoryPeer::CG_ID , $id_array, Criteria::IN );
        $fileUnlinks = TblcategoryPeer::doSelect($c);
        //var_dump($fileUnlink);
        if(TblcategoryPeer::doDelete($c)) {
          $this->redirect("category/list?page=$page");
        }
        else {
          $this->getRequest()->setError('delete', "System error: count not delete");
          return $this->forward('category', 'list');
        }*/
        //return sfView::NONE ;

        // check contain document
        $page = $this->getRequestParameter('page');
        $id_list = $this->getRequestParameter('idList');
        $c = new  Criteria();
        $c->add(TbldocumentPeer::DOC_CATEGORY  ,$id_list);
        $numSubDoc = TbldocumentPeer::doCount($c);
        //var_dump($numSubDoc);

        // check contain sub category
        $c = new  Criteria();
        $c->add(TblcategoryPeer::CG_PARENTID ,$id_list);
        $numSubCat = TblcategoryPeer::doCount($c);
        //var_dump($numSubCat);
        if($numSubDoc == 0 && $numSubCat == 0) {
            //if(is_dir(sfConfig::get('sf_upload_dir')."/resources/".$tblcategory->getCgId()))
                //rmdir(sfConfig::get('sf_upload_dir')."/resources/".$tblcategory->getCgId());
            $c->clear();
            $c->add(TblcategoryPeer::CG_ID , $id_list );
            if(TblcategoryPeer::doDelete($c))
                $this->redirect("category/list?page=$page");
        }
        else {
            $this->getRequest()->setError('delete', 'Could not delete the selected category. Make sure it does not have any associated sub categor and item.');
            return $this->forward('category', 'list');
        }
  }

  public  function executeUpdateSort() {
      $cgId = $this->getRequestParameter('cg_id');
      $c = new Criteria();
      $c = TblcategoryPeer::retrieveByPK($cgId);
      $parent = $c->getCgparentid();
      $arr = new Criteria();
      $arr->clearSelectColumns();
      $arr->add(TblcategoryPeer::CG_PARENTID, $parent);
      $arr->addAscendingOrderByColumn(TblcategoryPeer::CG_SORT);
      $rs = TblcategoryPeer::doSelect($arr);
      foreach ($rs as $key => $r) {
        $r->setCgSort(++$key);
        $r->save();
      }
      foreach ($rs as $key => $r) {
        if ($r->getCgId() == $cgId) {
          $tmp = $r->getCgSort();
        	if ($this->getRequestParameter('order')==0) {
        	  $r->setCgSort($rs[$key-1]->getCgSort());
        	  $rs[$key - 1]->setCgSort($tmp);
        	  $rs[$key - 1]->save();
        	}
        	elseif ($this->getRequestParameter('order')==1) {
        	  $r->setCgSort($rs[$key +1]->getCgSort());
        	  $rs[$key + 1]->setCgSort($tmp);
        	  $rs[$key + 1]->save();
        	}
        	$r->save();
        	break;
        }
      }
      return $this->forward('category', 'list');
    }
}
