<?php

QUnit_Global::includeClass('QUnit_UI_TemplatePage');

class Affiliate_Merchants_Views_PZoneArticles extends QUnit_UI_TemplatePage
{
    function Affiliate_Merchants_Views_PZoneArticles() {
        $this->navigationAddURL(L_G_HOME,'index.php?md=home');
        $this->navigationAddURL(L_G_PZONE,'javascript:;');
		$this->navigationAddURL(L_G_PZONE_ARTICLES,'index.php?md=Affiliate_Merchants_Views_PZoneArticles');
        if($_GET['action']=='add') {
            $this->navigationAddURL(L_G_PZONE_ADDARTICLES,'');
        }else if($_GET['action']=='edit') {
            $this->navigationAddURL(L_G_PZONE_EDITARTICLES,'');
        }else {
            $this->navigationAddURL(L_G_PZONE_ARTICLESLIST,'');
        }
    }

    //------------------------------------------------------------------------

    function process()
    {

        $this->addContent('dynamiclink_js');

        if($_POST['commited']=="yes"){
            switch($_REQUEST['action']) {
                case 'add': return $this->processAdd();break;
                case 'edit': return $this->processEdit();break;
                case 'delete': return $this->processDelete(); break;
                default: $this->addErrorMessage(L_G_PZONE_ALERT_UNKNOWMETHOD);
            }
        }

        switch($_REQUEST['action']) {
            case 'add': {
                return $this->drawAddForm();
            }
            case 'edit': {
                $_REQUEST['id'] = preg_replace('/[\'\"]/', '', $_REQUEST['id']);
                $query = 'select * from `wd_pz_posts` where `ID`="'.$_REQUEST['id'].'"';
                $rs = $GLOBALS['db']->Query($query);
                if(!$rs || $rs->EOF) {
                    $this->addErrorMessage(L_G_PZONE_ALERT_ARTICLES_NOTEXISTS);
                }
                $_POST['title'] = $rs->fields['title'];
                $_POST['cateid'] = $rs->fields['cateid'];
                $_POST['context'] = $rs->fields['context'];
                $_POST['show2nav'] = $rs->fields['show2nav'];
                $this->assign('id',$_REQUEST['id']);
                return $this->drawEditForm();
            }
        }

        $this->drawList();
    }

    //--------------------------------------------------------------------------


    function drawAddForm() {
        $this->assign('tabtitle',L_G_CREATE);
        $this->assign('catesComboboxString',$this->getCatesCombo());
        $this->addContent('pzonearticles_edit');
    }

    //--------------------------------------------------------------------------

    function drawEditForm() {
        $this->assign('tabtitle',L_G_EDIT);
        $this->assign('catesComboboxString',$this->getCatesCombo());
        $this->addContent('pzonearticles_edit');
    }

    //--------------------------------------------------------------------------

    function drawList() {
        //整理搜索参数，统一使用POST参数，链接和搜索表单提交为GET，删除表单提交为POST
        if(!isset($_POST['cateid'])) $_POST['cateid'] = $_GET['cateid'];
        if(!isset($_POST['authorid'])) $_POST['authorid'] = $_GET['authorid'];
        if(!isset($_POST['title'])) $_POST['title'] = $_GET['title'];

        $this->assign('searchlink','&cateid='.$_POST['cateid'].'&authorid='.$_POST['authorid'].'&title='.$_POST['title']);

        $this->getListData();
        $this->assign('catesComboboxString',$this->getCatesCombo(true));
        $this->assign('authorComboboxString',$this->getAuthorCombo());
        $this->addContent('pzonearticles_list');
    }

    //--------------------------------------------------------------------------

    function processAdd() {
        $title = preg_replace('/[\'\"]/', '', strip_tags($_POST['title']));
        $show2nav = $_POST['show2nav']=='yes'?'yes':'no';

        $query = "insert into `wd_pz_posts` values ('%s','%s','%s',NOW(),'%s','%s','%s')";
        $id = QCore_Sql_DBUnit::createUniqueID('wd_pz_posts','ID');
        $query = sprintf($query,$id,$_POST['cateid'],$GLOBALS['Auth']->getUserID(),$title,$_POST['context'],$show2nav);
        if($this->checkInputData())
        if($GLOBALS['db']->Execute($query)===false) {
            $this->addErrorMessage(L_G_PZONE_ALERT_ADD_ARTICLECATES_FAIL);
            $_REQUEST['action'] = 'add';
            $this->drawAddForm();
        }else{
            $this->addOKMessage(L_G_PZONE_ALERT_ADD_ARTICLECATES_OK);
            $this->assign('id',$id);
            $_REQUEST['action'] = 'edit';
            //$this->drawEditForm();
            //必须重定向，因为CONTENT会被自动加上转义字符，重定向后会重新读取
            $this->redirect($_POST['md']."&action=edit&id=".$id);
            return true;
        }
        $this->drawAddForm();
    }

    //--------------------------------------------------------------------------

    function processEdit() {
        $title = preg_replace('/[\'\"]/', '', strip_tags($_POST['title']));
        $show2nav = $_POST['show2nav']=='yes'?'yes':'no';
        $query = "update `wd_pz_posts` set `title`='%s',`cateid`='%s',`authorid`='%s',`context`='%s',`postime`=NOW(),`show2nav`='%s' where `ID`='%s'";
        $query = sprintf($query,$title,$_POST['cateid'],$GLOBALS['Auth']->getUserID(),$_POST['context'],$show2nav,$_POST['id']);
        if($this->checkInputData())
        if($GLOBALS['db']->Execute($query)===false) {
            $this->addErrorMessage(L_G_PZONE_ALERT_EDT_ARTICLES_FAIL);
        }else{
            $this->addOKMessage(L_G_PZONE_ALERT_EDT_ARTICLES_OK);
        }
        $this->assign('id',$_POST['id']);
        $_REQUEST['action'] = 'edit';
        //$this->drawEditForm();
        //必须重定向，因为CONTENT会被自动加上转义字符，重定向后会重新读取
        $this->redirect($_POST['md']);  //."&action=edit&id=".$_POST['id']);
        unset($_POST);
        exit();
    }

    //--------------------------------------------------------------------------

    function processDelete() {
        if(is_array($_POST['checkeditems'])) {
            $where = '("'.join('","',$_POST['checkeditems']).'")';
            $query = 'delete from `wd_pz_posts` where `ID` in '.$where;
            if($GLOBALS['db']->Execute($query)===false) {
                $this->addOKMessage(L_G_PZONE_ALERT_DEL_ARTICLES_FAIL);
            }else {
                $catesCount = count($_POST['checkeditems']);
                $rs = $GLOBALS['db']->Execute($query);
                $this->addOKMessage(sprintf(L_G_PZONE_ALERT_DEL_ARTICLES_OK,$catesCount));
            }
        }
        $this->drawList();
    }

    //--------------------------------------------------------------------------

    function getListData() {
        $limit = 30;

        $where = 'where 1 ';
        if(!empty($_POST['cateid'])) $where .= ' and p.`cateid`="'.$_POST['cateid'].'"';
        if(!empty($_POST['authorid'])) $where .= ' and p.`authorid`="'.$_POST['authorid'].'"';
        if(!empty($_POST['title'])) $where .= ' and p.`title` like "%'.mysql_real_escape_string($_POST['title']).'%"';

        $query = 'select count(p.ID) as "total" from `wd_pz_posts` p '.$where;
        $rs = $GLOBALS['db']->Query($query);
        $total = $rs->fields['total'];
        $totalpage = ceil($total/$limit);
        $totalpage = $totalpage<1?1:$totalpage;

        $page = (int) $_GET['page'];
        $page = $page<1?1:($page>$totalpage?$totalpage:$page);

        $start = ($page-1)*$limit;
        $this->assign('page',$page);
        $this->assign('totalpage',$totalpage);
        $this->assign('total',$total);
        $this->assign('limit',$limit);

        $query = 'select p.*, c.catename, u.name as "author" from `wd_pz_posts` p join `wd_pz_cates` c on p.cateid=c.ID join `wd_g_users` u on p.authorid=u.userid '.$where.' order by p.`postime` desc limit '.$start.','.$limit;
        $rs = $GLOBALS['db']->Query($query);
        if(!$rs || $rs->EOF) $this->assign('listdata',array());
        $this->assign('listdata',$rs);
    }

    //--------------------------------------------------------------------------

    function getCatesCombo($isearch=false) {
        $s = '<select name="cateid">';
        $query = 'select * from `wd_pz_cates` order by `displaysort`,`dateinserted` asc';
        $rs = $GLOBALS['db']->Query($query);
        if(!$rs || $rs->EOF) {
            $this->addErrorMessage(L_G_PZONE_ALERT_NOCATES);
        }else {
            if($isearch) {
                $tmp[] = array('ID'=>0,'catename'=>L_G_PZONE_ALLCATEGORIES);
            }
            foreach($rs as $irow) { $tmp[] = $irow; }
            foreach($tmp as $row) {
                $ck = $_POST['cateid']==$row['ID']?'selected="selected"':'';
                $s .= sprintf('<option value="%s" %s>%s</option>',$row['ID'],$ck,$row['catename']);
            }
        }
        $s .= '</select>';
        return $s;
    }

    //--------------------------------------------------------------------------

    function getAuthorCombo() {
        $s = '<select name="authorid">';
        $query = 'select * from `wd_g_users` where `rtype`=3 and deleted=0 order by `dateinserted` asc';
        $rs = $GLOBALS['db']->Query($query);
        if($rs && !$rs->EOF) {
            $tmp[] = array('userid'=>0,'name'=>L_G_PZONE_ALLAUTHOR);
            foreach($rs as $irow) { $tmp[] = $irow; }
            foreach($tmp as $row) {
                $ck = $_POST['authorid']==$row['userid']?'selected="selected"':'';
                $s .= sprintf('<option value="%s" %s>%s</option>',$row['userid'],$ck,$row['name']);
            }
        }
        $s .= '</select>';
        return $s;
    }

    //--------------------------------------------------------------------------

    function checkInputData() {
        $flg = true;
        if(empty($_POST['cateid'])){
            $flg = false;
            $this->addErrorMessage(L_G_PZONE_ALERT_CATEGORY_CANOT_BE_EMPTY);
        }
        if(empty($_POST['title'])){
            $flg = false;
            $this->addErrorMessage(L_G_PZONE_ALERT_TITLE_CANOT_BE_EMPTY);
        }
        if(empty($_POST['context'])){
            $flg = false;
            $this->addErrorMessage(L_G_PZONE_ALERT_CONTENT_CANOT_BE_EMPTY);
        }
        return $flg;
    }

    //--------------------------------------------------------------------------

}
?>
