<?php
/**
  * @category modules
  *
  * @author Carlos Perez Fernandez <cperez@demartinacode.com>
  * @support Soporte DemartinaCode <soporte@demartinacode.com>
  * @copyright PrestaShop
  * @license http://www.opensource.org/licenses/osl-3.0.php Open-source licence 3.0
  * @version 1.0
  *
  */
class cartiumcom extends Module{

    const INSTALL_SQL_FILE = 'install.sql';
    
    public function  __construct() {
        $this->name = 'cartiumcom';
        $this->tab = 'Products';
        $this->version =0.3;
        parent::__construct();
        $this->page = basename(__FILE__, '.php');
        $this->displayName = $this->l('Cartium Comments');
        $this->description = $this->l('Comments.');

    }
    
    function install(){
        
        if (!file_exists(dirname(__FILE__).'/'.self::INSTALL_SQL_FILE)){
            return (false);
        }else{
            if (!$sql = file_get_contents(dirname(__FILE__).'/'.self::INSTALL_SQL_FILE)){
                return (false);
            }
            $sql = str_replace('PREFIX_', _DB_PREFIX_, $sql);
            if (!Db::getInstance()->Execute(trim($sql))){
                return (false);
            }
            if (parent::install() == false
            OR $this->registerHook('productTab') == false
            OR $this->registerHook('productTabContent') == false
            OR $this->registerHook('header') == false
            OR $this->registerHook('rightColumn') == false
            OR $this->registerHook('leftColumn') == false
            OR Configuration::updateValue($this->name.'MODERATE', 1) == false){
                return (false);
            }
            return (true);
        }
    }
    public function getContent(){
        global $smarty, $cookie, $errors;
        $smarty->assign('request_uri', $_SERVER['REQUEST_URI']);
        $tab = Tools::getValue('tab');
	$currentIndex = __PS_BASE_URI__.substr($_SERVER['SCRIPT_NAME'], strlen(__PS_BASE_URI__)).($tab ? '?tab='.$tab : '');
	$token = Tools::getValue('token');
        $smarty->assign('tab',$tab);
        $smarty->assign('currentIndex',$currentIndex);
        $smarty->assign('token',$token);
        $smarty->assign('name',$this->name);
        $smarty->assign('path',$this->_path);
        

        $command=Tools::getValue($this->name."_command");
        if($command=="to_right"){
            Configuration::updateValue($this->name.'RIGHT', 1);
        }
        if($command=="to_left"){
            Configuration::updateValue($this->name.'RIGHT', 0);
        }
        if($command=="num_of_comm"){
            $num_of_comm=Tools::getValue("num_of_comm");
            Configuration::updateValue($this->name.'num_of_comm', $num_of_comm);
            $num_of_chars=Tools::getValue("num_of_chars");
            Configuration::updateValue($this->name.'num_of_chars', $num_of_chars);
        }
        if($command=="show"){
            Configuration::updateValue($this->name.'show_colum', 1);
        }
        if($command=="hide_show"){
            Configuration::updateValue($this->name.'show_colum', 0);
        }
        $max=Configuration::get($this->name.'num_of_comm');
        if($max==""){
            $max=3;
            Configuration::updateValue($this->name.'num_of_comm', $max);
        }
        $right=Configuration::get($this->name.'RIGHT');
        $num_of_chars=Configuration::get($this->name.'num_of_chars');
        if($num_of_chars==""){
            $num_of_chars=20;
            Configuration::updateValue($this->name.'num_of_chars', $max);
        }
        $show_colum=Configuration::get($this->name.'show_colum');
        $smarty->assign('num_of_comm',$max);
        $smarty->assign('right',$right);
        $smarty->assign('num_of_chars',$num_of_chars);
        $smarty->assign('show_colum',$show_colum);
        
        if($command=="valid_true"){
            Configuration::updateValue($this->name.'MODERATE', 1);
        }
        if($command=="valid_false"){
            Configuration::updateValue($this->name.'MODERATE', 0);
        }
        if($command=="change_valid"){
            $id_comment=Tools::getValue("id_comment");
            $this->changeValid($id_comment);
            $comment=$this->get_by_comment_id($id_comment);
            $id_product=$comment['id_product'];
        }
        if($command=="up_grade"){
            $id_comment=Tools::getValue("id_comment");
            $this->up($id_comment);
            $comment=$this->get_by_comment_id($id_comment);
            $id_product=$comment['id_product'];
        }
        if($command=="down_grade"){
            $id_comment=Tools::getValue("id_comment");
            $this->down($id_comment);
            $comment=$this->get_by_comment_id($id_comment);
            $id_product=$comment['id_product'];
        }
        if($command=="change_order"){
            $by=Tools::getValue('by');
            $order=Tools::getValue('order');

            Configuration::updateValue($this->name.'by',$by);
            Configuration::updateValue($this->name.'order',$order);
        }
        $valid=Configuration::get($this->name.'MODERATE');
        $smarty->assign('valid', $valid);
        $products=$this->get_all_products_comments();
        $smarty->assign('products',$products);
        $out=$this->display(__FILE__, 'product.tpl');

        if($command==""){
            $command="list_all";
        }
        if($command=="list_all"){
            //get_all_products_comments_list()
        }


        if(!isset($id_product))
            $id_product=Tools::getValue("id_product");
            
        if($id_product=="")
            $id_product=Configuration::get($this->name.'id_product');
        
        if($id_product!=""){
            Configuration::updateValue($this->name.'id_product',$id_product);
        }
        
        if($id_product!=""&& !(($command=="delete") || ($command=="edit_submit") || ($command=="comment_submit"))) {
            $list=$this->getByIdProductAll($id_product);
            $smarty->assign('cartiumcomments',$list);
            $out.=$this->display(__FILE__, 'tree_admin.tpl');
        }
        if($command=="edit_form"){
            $id_comment=Tools::getValue("id_comment");
            $comm=$this->get_by_comment_id($id_comment);
            $smarty->assign('id_comment',$id_comment);
            $smarty->assign('alias',$comm['alias']);
            $smarty->assign('email',$comm['email']);
            $smarty->assign('content',$comm['content']);
            $smarty->assign('command','edit_submit');
            $out.=$this->display(__FILE__, 'form_admin.tpl');
        }
        if($command=="edit_submit"){
            $id_comment=Tools::getValue("id_comment");
            $content=Tools::getValue("content");
            $alias=Tools::getValue("alias");
            $email=Tools::getValue("email");
            $this->edit($id_comment, $content, $alias, $email);
            $comment=$this->get_by_comment_id($id_comment);
            $id_product=$comment['id_product'];
            $list=$this->getByIdProductAll($id_product);
            $smarty->assign('cartiumcomments',$list);
            $out.=$this->display(__FILE__, 'tree_admin.tpl');
        }
        if($command=="delete"){
            $id_comment=Tools::getValue("id_comment");
            $comment=$this->get_by_comment_id($id_comment);
            $this->delete($id_comment);
            $id_product=$comment['id_product'];
            $list=$this->getByIdProductAll($id_product);
            $smarty->assign('cartiumcomments',$list);
            $out.=$this->display(__FILE__, 'tree_admin.tpl');
        }
        if($command=="comment_form"){
            $id_comment=Tools::getValue("id_comment");
            $email=$cookie->email;
            $alias=$cookie->firstname;
            $comment="";
            $command_form="comment_submit";
            $smarty->assign('id_comment',$id_comment);
            $smarty->assign('alias',$alias);
            $smarty->assign('email',$email);
            $smarty->assign('content',$comment);
            $smarty->assign('command',$command_form);
            $out.=$this->display(__FILE__, 'form_admin.tpl');
        }
        if($command=="comment_submit"){
            $id_parent=Tools::getValue("id_comment");
            $comment=$this->get_by_comment_id($id_parent);
            $id_product=$comment['id_product'];
            $id_customer='0';
            $content=Tools::getValue("content");
            $alias=Tools::getValue("alias");
            $email=Tools::getValue("email");
            $this->publishValid($id_parent, $id_product, $id_customer, $content, $alias, $email);
            $list=$this->getByIdProductAll($id_product);
            $smarty->assign('cartiumcomments',$list);
            $out.=$this->display(__FILE__, 'tree_admin.tpl');
        }
        
        //$out.=$this->display(__FILE__, '/form.tpl');
        return $out;
    }

    function hookProductTab($params){
        //Calculo del número de comentarios
        $id_product=Tools::getValue('id_product');
        $cout = $this->count_by_product_id($id_product);
        return "<li><a href='#".$this->name."_div' class='idTabHrefShort'>".$this->l('Comments')."($cout)</a></li>";
    }

    function hookProductTabContent($params){
        global $smarty, $cookie, $errors;
        $id_product=Tools::getValue('id_product');
        $id_lang=intval($cookie->id_lang);
        $logged=$cookie->isLogged();
        if($cookie->isLogged()){
            $email=$cookie->email;
            $alias=$cookie->customer_firstname;
        }else{
            $email="yourname@company.com";
            $alias="";
        }
        $smarty->assign('logged',$cookie->isLogged());
        $smarty->assign('email',$email);
        $smarty->assign('alias',$alias);
        $smarty->assign('name',$this->name);
        $smarty->assign('name_div',$this->name."_div");
        $smarty->assign('request_uri',$_SERVER['REQUEST_URI']);
        $smarty->assign('img_path',$this->_path);
        //captcha
        $rand1=rand(0, 100);
        $rand2=rand(0, 100);
        $smarty->assign('rand1',$rand1);
        $smarty->assign('rand2',$rand2);
        $cookie->cartiumcom_rand=$rand1+$rand2;
        //comments
        $comments=$this->getByIdProduct($id_product);
        $smarty->assign('cartiumcomments',$comments);
        $out="<div id='".$this->name."_div'>";
        $out.=$this->display(__FILE__, '/tree.tpl');
        $out.=$this->display(__FILE__, '/form.tpl');
        $out.="</div>";
        return $out;
    }
    public function hookHeader(){
        global $smarty, $cookie, $errors;
        $command=Tools::getValue($this->name."_command");
        $logged=$cookie->isLogged();
        if($command=="publish" || $command=="comment"){
            $id_parent=Tools::getValue("id_comment");
            $id_product=Tools::getValue('id_product');
            $id_customer=$cookie->id_customer;
            $content=Tools::getValue("content");
            $grade=Tools::getValue("grade");
            $alias=Tools::getValue("alias");
            $email=Tools::getValue("email");
            //validation CAPTCHA
            $this->publish($id_parent, $id_product, $id_customer, $content, $alias, $email);
        }
        if($command=="edit"){
            $id_comment=Tools::getValue("id_comment");
            $content=Tools::getValue("content");
            $alias=Tools::getValue("alias");
            $email=Tools::getValue("email");
            $this->edit($id_comment, $content, $alias, $email);
        }
        if($command=="delete"){
            $id_comment=Tools::getValue("id_comment");
            $this->delete($id_comment);
        }
        if($command=="up" && $logged){
            $id_comment=Tools::getValue("id_comment");
            $this->up($id_comment);
        }
        if($command=="down" && $logged){
            $id_comment=Tools::getValue("id_comment");
            $this->down($id_comment);
        }


    }
    public function publish($id_parent, $id_product, $id_customer, $content, $alias, $email){
        global $smarty, $cookie, $errors;
        $grade=0;
        //validación
        //exite el id_product
        //Captcha
        $validate=true;
        if(!$cookie->isLogged()){
            $cmp1=$cookie->cartiumcom_rand;
            $cmp2=Tools::getValue("sec");
            $validate=(intval($cmp1)==intval($cmp2));
        }
        // validación de alias, $email y contenido
        $validate=$validate && Validate::isUnsignedInt($id_parent)&&Validate::isUnsignedInt($id_product)&&Validate::isUnsignedInt($id_customer)&&Validate::isMessage($content)&&Validate::isName($alias)&&Validate::isEmail($email);
        $valid=Configuration::get($this->name.'MODERATE');
        if($validate){
            $SQL="INSERT INTO "._DB_PREFIX_."cartium_comment (id_parent, id_product, id_customer, content, grade, validate, date_add, alias, email) VALUES ( '$id_parent', '$id_product', '$id_customer', '".addslashes($content)."', '$grade', '$valid', NOW(), '$alias', '$email')";
            $ret=Db::getInstance()->Execute($SQL);
            if($id_parent!=0 && $valid){
                $comment=$this->get_by_comment_id($id_parent);
                $email=$comment['email'];
                $this->sedMail($email,$id_product);
            }
        }else{

        }
    }
    public function publishValid($id_parent, $id_product, $id_customer, $content, $alias, $email){
        global $smarty, $cookie, $errors;
        $grade=0;
        $validate=Validate::isUnsignedInt($id_parent)&&Validate::isUnsignedInt($id_product)&&Validate::isUnsignedInt($id_customer)&&Validate::isMessage($content)&&Validate::isName($alias)&&Validate::isEmail($email);
        $valid=1;
        if($validate){
            $SQL="INSERT INTO "._DB_PREFIX_."cartium_comment (id_parent, id_product, id_customer, content, grade, validate, date_add, alias, email) VALUES ( '$id_parent', '$id_product', '$id_customer', '".addslashes($content)."', '$grade', '$valid', NOW(), '$alias', '$email')";
            $ret=Db::getInstance()->Execute($SQL);
            if($id_parent!=0){
                $comment=$this->get_by_comment_id($id_parent);
                $email=$comment['email'];
                $this->sedMail($email,$id_product);
            }
        }else{

        }
    }
    public function edit($id_comment, $content, $alias, $email){
        global $smarty, $cookie, $errors;
        $validate=Validate::isUnsignedInt($id_comment)&&Validate::isMessage($content)&&Validate::isName($alias)&&Validate::isEmail($email);
        //edita algien que le pertenece
        
        if($validate)
            $validate=$validate&&$this->valid($id_comment);
        if($validate){
            $SQL="UPDATE "._DB_PREFIX_."cartium_comment SET content='".addslashes($content)."', alias='$alias', email='$email' WHERE id_product_comment = '$id_comment'";
            $ret=Db::getInstance()->Execute($SQL);
            
        }else{

        }
    }
    
    public function delete($id_comment){
        global $smarty, $cookie, $errors;
        $validate=Validate::isUnsignedInt($id_comment);
        if($validate)
            $validate=$validate&&$this->valid($id_comment);
        if($validate){
            $SQL="DELETE FROM "._DB_PREFIX_."cartium_comment WHERE id_product_comment='$id_comment' OR id_parent='$id_comment'";
            $ret=Db::getInstance()->Execute($SQL);
        }else{

        }


    }
    public function up($id_comment){
        global $smarty, $cookie, $errors;
        $tmp="votado_$id_comment";
        if(!isset($cookie->$tmp)){
            $cookie->$tmp=false;
        }

        if( $cookie->$tmp && $cookie->id_employee==""){
            //ya ha votado
            $errors[] = $this->l('You have voted yet');
            //$cookie->votado=false;
        }else{
            //no ha votado
            $comment=$this->get_by_comment_id($id_comment);
            $grade=$comment['grade']+1;
            $SQL="UPDATE "._DB_PREFIX_."cartium_comment SET grade='$grade' WHERE id_product_comment = '$id_comment'";
            $ret=Db::getInstance()->Execute($SQL);
            $cookie->$tmp=true;
        }

    }

    public function down($id_comment){
        global $smarty, $cookie, $errors;
        $tmp="votado_$id_comment";
        if(!isset($cookie->$tmp)){
            $cookie->$tmp=false;
        }

        if( $cookie->$tmp  && $cookie->id_employee==""){
            //ya ha votado
            $errors[] = Tools::displayError('ya ha votado');
            //$cookie->votado=false;
        }else{
            //no ha votado
            $comment=$this->get_by_comment_id($id_comment);
            $grade=$comment['grade']-1;
            $SQL="UPDATE "._DB_PREFIX_."cartium_comment SET grade='$grade' WHERE id_product_comment = '$id_comment'";
            $ret=Db::getInstance()->Execute($SQL);
            $cookie->$tmp=true;
        }
    }
    /**
     *  Genera un listado de comentarios y subcomentarios.
     * @param <type> $id_product
     * @return <type> 
     */
    public function getByIdProduct($id_product){
        global $smarty, $cookie, $errors;
        $SQL="SELECT * FROM "._DB_PREFIX_."cartium_comment WHERE id_product=$id_product AND id_parent=0 AND validate=1 ORDER BY grade DESC, date_add ASC";
        $tmp= Db::getInstance()->ExecuteS($SQL);
        $out=Array();
        foreach($tmp as $row){
            $id_parent=$row['id_product_comment'];
            $SQL="SELECT * FROM "._DB_PREFIX_."cartium_comment WHERE id_product=$id_product AND id_parent=$id_parent AND validate=1 ORDER BY grade DESC, date_add ASC";
            $sub_tmp=Db::getInstance()->ExecuteS($SQL);
            $subcomments=array();
            foreach($sub_tmp as $subcomm){
                $id_customer=$subcomm['id_customer'];
                if($cookie->id_customer!="" && $id_customer==$cookie->id_customer){
                    $subcomm['own']=true;
                }else{
                    $subcomm['own']=false;
                }
                $subcomments[]=$subcomm;
            }
            $row['subcomments']=$subcomments;
            $id_customer=$row['id_customer'];
            if($cookie->id_customer!="" && $id_customer==$cookie->id_customer){
                $row['own']=true;
            }else{
                $row['own']=false;
            }
            $out[]=$row;
        }
        return $out;
    }
    //admin
    public function getByIdProductAll($id_product){
        global $smarty, $cookie, $errors;
        $by=Configuration::get($this->name.'by');
        $order=Configuration::get($this->name.'order');
        if($by=="" || $order==""){
            $by="grade";
            $order="DESC";
        }
        $SQL="SELECT * FROM "._DB_PREFIX_."cartium_comment WHERE id_product=$id_product AND id_parent=0 ORDER BY $by $order";
        $tmp= Db::getInstance()->ExecuteS($SQL);
        $out=Array();
        foreach($tmp as $row){
            $id_parent=$row['id_product_comment'];
            $SQL="SELECT * FROM "._DB_PREFIX_."cartium_comment WHERE id_product=$id_product AND id_parent=$id_parent ORDER BY $by $order";
            $sub_tmp=Db::getInstance()->ExecuteS($SQL);
            $subcomments=array();
            foreach($sub_tmp as $subcomm){
                $id_customer=$subcomm['id_customer'];
                if($cookie->id_customer!="" && $id_customer==$cookie->id_customer){
                    $subcomm['own']=true;
                }else{
                    $subcomm['own']=false;
                }
                $subcomments[]=$subcomm;
            }
            $row['subcomments']=$subcomments;
            $id_customer=$row['id_customer'];
            if($cookie->id_customer!="" && $id_customer==$cookie->id_customer){
                $row['own']=true;
            }else{
                $row['own']=false;
            }
            $out[]=$row;
        }
        return $out;
    }

    function valid($id_comment){
        $val=Validate::isUnsignedInt($id_comment);
        global $smarty, $cookie, $errors;
        $id_employee=$cookie->id_employee;
        $id_customer=$cookie->id_customer;
        if($val){
            $SQL="SELECT * FROM "._DB_PREFIX_."cartium_comment WHERE id_product_comment=$id_comment";
            $row=Db::getInstance()->getRow($SQL);
            $id_customer_val=$row['id_customer'];
            $val=(($id_employee!="")||($id_customer!=""&&$id_customer==$id_customer_val));
        }
        return $val;
    }
    function get_all_products_comments(){
        global $smarty, $cookie, $errors;
        $id_lang=$cookie->id_lang;
        $SQL="SELECT * FROM "._DB_PREFIX_."cartium_comment a LEFT JOIN "._DB_PREFIX_."product_lang b on a.id_product=b.id_product WHERE b.id_lang='$id_lang' GROUP BY a.id_product";
        $tmp = Db::getInstance()->ExecuteS($SQL);
        $out=array();
        foreach($tmp as $res){
            $id_product=$res['id_product'];
            $count = $this->count_by_product_id($id_product);
            $res['count']=$count;
            $validcount = $this->count_valid_by_product_id($id_product);
            $res['validcount']=$validcount;
            $out[]=$res;
        }
        return $out;
    }
    function get_by_comment_id($id_comment){
        $SQL="SELECT * FROM "._DB_PREFIX_."cartium_comment WHERE id_product_comment=$id_comment";
        return Db::getInstance()->getRow($SQL);
    }
    function count_by_product_id($id_product){
        $SQL="SELECT count(*) AS total FROM "._DB_PREFIX_."cartium_comment WHERE id_product=$id_product AND validate=1";
        $res=Db::getInstance()->getRow($SQL);
        return $res['total'];
    }
    function count_valid_by_product_id($id_product){
        $SQL="SELECT count(*) AS total FROM "._DB_PREFIX_."cartium_comment WHERE id_product=$id_product AND validate=0";
        $res=Db::getInstance()->getRow($SQL);
        return $res['total'];
    }
    function changeValid($id_comment) {
        $SQL="SELECT * FROM "._DB_PREFIX_."cartium_comment WHERE id_product_comment=$id_comment";
        $res=Db::getInstance()->getRow($SQL);
        $valid=$res['validate'];
        if($valid=="1"){
            $SQL="UPDATE "._DB_PREFIX_."cartium_comment SET validate='0' WHERE id_product_comment = '$id_comment'";
            $ret=Db::getInstance()->Execute($SQL);
        }else{
            $SQL="UPDATE "._DB_PREFIX_."cartium_comment SET validate='1' WHERE id_product_comment = '$id_comment'";
            $ret=Db::getInstance()->Execute($SQL);
            if($res['id_parent']!=0){
                $comment=$this->get_by_comment_id($res['id_parent']);
                $email=$comment['email'];
                $this->sedMail($email,$res['id_product']);
            }
        }
    }
    function sedMail($email, $id_product){
        global $smarty, $cookie, $errors;
        $id_lang=intval($cookie->id_lang);
        $template='newsletter';
        $subject=$this->l('Message to a customer');
        $message=$this->l('Somebody reply to your comment');
        $message.="<br><a href='"._PS_BASE_URL_.__PS_BASE_URI__."product.php?id_product=$id_product'>"._PS_BASE_URL_.__PS_BASE_URI__."product.php?id_product=$id_product</a>";
        $templateVars=array(
				'{message}' => $message);
        $to=array($email);
        $toName = strval(Configuration::get('PS_SHOP_NAME'));
        $from=strval(Configuration::get('PS_SHOP_EMAIL'));
        Mail::Send($id_lang, $template, $subject, $templateVars, $to, $toName, $from);

    }
    public function getCustomerId($id_customer)
	{
		$row = Db::getInstance()->getRow('
		SELECT *
		FROM '._DB_PREFIX_.'customer c
		WHERE c.`id_customer` = '.intval($id_customer));

		return $row;
	}
    public function hookRightColumn($params){
        $right=Configuration::get($this->name.'RIGHT');
        if($right==""){
            $right=1;
            Configuration::updateValue($this->name.'RIGHT', $right);
        }
        $out="";
        if($right==1){
            $out.=$this->getColumn();
        }
        return $out;
    }
    public function hookLeftColumn($params){
        $right=Configuration::get($this->name.'RIGHT');
        $show_colum=Configuration::get($this->name.'show_colum');
        if($right=="" && $show_colum==1 ){
            $right=1;
            Configuration::updateValue($this->name.'RIGHT', $right);
        }
        $out="";
        if($right==0 && $show_colum==1){
            $out.=$this->getColumn();
        }
        return $out;
    }
    public function getColumn(){
        $out="";
        $out.="<div class='block'><h4>".$this->l('Last Commets')."</h4>";
        $out.="<ul class='block_content'>";
        $resp=$this->getLastMenssages();
        $out.="<li>".$resp." </li>";
        $out.="</ul>";
        $out.="</div>";
        return $out;
    }
    public function getLastMenssages(){
        global $smarty, $cookie, $errors;
        $out="";
        $max=Configuration::get($this->name.'num_of_comm');
        if($max==""){
            $max=3;
            Configuration::updateValue($this->name.'num_of_comm', $max);
        }
        $max_chars=Configuration::get($this->name.'num_of_chars');

        $id_lang=$cookie->id_lang;
        $SQL="SELECT * FROM "._DB_PREFIX_."cartium_comment WHERE validate=1 AND id_parent=0 ORDER BY date_add DESC LIMIT $max";
        $resp = Db::getInstance()->ExecuteS($SQL);
        foreach($resp as $res){
            $id_product=$res['id_product'];
            $product = new Product($id_product, false, intval($cookie->id_lang));
            $link=$product->getLink();
            $out.="(".$res['alias'].")<a href='$link'>$product->name</a><br />";
            $content=$res['content'];
            if(strlen($content)>$max_chars){
                $out.=substr($res['content'],0,$max_chars)."...<br />";
            }else{
                $out.=$res['content']."<br />";
            }
        }
        return $out;
    }
}
?>
