<?php
    class USER_AUTH extends USER
    {
        public function user_auth_javainit()
        {

        }

        public function fn_auth_init()
        {
            if(isset($_REQUEST['task'])){$task=trim(strtolower($_REQUEST['task']));}
            if(isset($_POST['task'])){$task=trim(strtolower($_POST['task']));}
            switch($task)
            {
                case "updatemenuid":
                    $this->fn_updatemenuid();
                break;

                case "loadmenu":
                    $this->fn_loadmenu();
                break;

                case "getmenuid":
                    $this->fn_getmenuid();
                break;

                case "getkduser":
                    $this->fn_getkduser();
                break;

                default:
                    $this->fn_default_auth();
                break;
            }
        }

        public function fn_default_auth()
        {
            echo $this->FN_CREATEHEADER();
//            echo "<style>
//                      .besidepassword {margin-left:92px;margin-top:-5px;position:absolute;z-index:0}
//                  </style>";
            echo "<script>  
                       var myFormsearch;var dguserauth;
                       function initObject()
                       {
                           // =====  FOrm Search
                           formData = [
                                        {type: \"settings\", position: \"label-left\", labelWidth: 160, inputWidth: 120},
                                            {type:\"fieldset\",width:\"720\",label:\"Pencarian User\",list:[
                                                {type:\"combo\", name:\"cbokduser\",label: \"Masukkan/Pilih Kode User\", inputWidth:160,info:true,tooltip:\"Masukkan/Pilih User\"},
                                                {type: \"hidden\", name:\"txtmenuid\", value:\"\"},
                                                {type:\"newcolumn\"},
                                                {type:\"combo\",name:\"cbotipemenu\",required:true,info:true,inputWidth:120,readonly:1,options:";
                                                        $arrval=array(array(value=>"",text=>""),array(value=>"",text=>"Menu"),array(value=>"tree",text=>"TreeMenu"));
                                                        echo json_encode($arrval);
                                        echo "  },
                                                {type:\"newcolumn\"},
                                                {type:\"button\", name:\"btnloadmenu\",value: \"Load Menu\",offsetTop:0,offsetLeft:10,disabled:1},
                                                {type:\"newcolumn\"},
                                                {type:\"button\", name:\"btnupdatemenu\",value: \"Update\",offsetTop:0,offsetLeft:10,className:\"button_update\",disabled:1}
                                            ]}
                                      ];
                           myFormsearch = new dhtmlXForm(\"divformsearch\", formData);
                           myFormsearch.enableLiveValidation(true);
                           myFormsearch.setFocusOnFirstActive(true);
                           
                           var cbokduser=myFormsearch.getCombo(\"cbokduser\");
                           url=fn_dhtmlxloadobject('".$this->enc("obj_user")."','obj=".$this->enc("-")."&task=".$this->enc("addcombo")."&tableobj=tbl_userlogin|kduser,kduser&exp=kduser|9999');
                               cbokduser.enableFilteringMode(true);
                               cbokduser.load(url);
                               cbokduser.attachEvent(\"onChange\",function(){
                                    if(myFormsearch.getCombo(\"cbokduser\").getComboText()!==''&&myFormsearch.getCombo(\"cbokduser\").getComboText()!=='-')
                                    {
                                        var kduser=ajaxuridhtmlx('".$this->enc("obj_user")."','obj=".$this->enc("user_auth")."&task=getkduser&kduser='+myFormsearch.getCombo(\"cbokduser\").getComboText());
                                        if(!trim(kduser)){fn_dhtmlxmessage('error','Kode user '+myFormsearch.getCombo(\"cbokduser\").getComboText()+' Tidak terdaftar');fn_myform_clear();}
                                    }
                               });
                           // ==== Attach Event Click
                           myFormsearch.attachEvent(\"onButtonClick\",function(id){
                               switch(id)
                               {
                                    case 'btnloadmenu':
                                        var menuid=ajaxuridhtmlx('".$this->enc("obj_user")."','obj=".$this->enc("user_auth")."&task=getmenuid&tipemenu='+myFormsearch.getCombo(\"cbotipemenu\").getSelectedValue()+'&kduser='+myFormsearch.getCombo(\"cbokduser\").getSelectedValue());
                                        //alert(menuid);
                                        myFormsearch.setItemValue(\"txtmenuid\",menuid);

                                        url=fn_dhtmlxloadobject('".$this->enc("obj_user")."','obj=".$this->enc("user_auth")."&task=loadmenu&kduser='+myFormsearch.getCombo(\"cbokduser\").getSelectedValue()+'&tipemenu='+myFormsearch.getCombo(\"cbotipemenu\").getSelectedValue());
                                        //alert(url);
                                        //dguserauth.enableSmartRendering(true,50);
                                        dguserauth.clearAndLoad(url);                                        
                                        myFormsearch.enableItem(\"btnupdatemenu\");
                                    break;
                                    case 'btnupdatemenu':
                                        dhtmlx.confirm({
                                            title:'Konfirmasi',text:'Data sudah benar dan ingin diupdate?',type:'confirm',
                                            callback:function(result){
                                                if(result)
                                                {
                                                    //alert(myFormsearch.getItemValue(\"txtmenuid\"));
                                                    var res=ajaxuridhtmlx('".$this->enc("obj_user")."','obj=".$this->enc("user_auth")."&task=updatemenuid&kduser='+myFormsearch.getCombo(\"cbokduser\").getSelectedValue()+'&menuid='+myFormsearch.getItemValue(\"txtmenuid\")+'&tipemenu='+myFormsearch.getCombo(\"cbotipemenu\").getSelectedValue());
                                                    var spres=res.split('|');
                                                    if(spres[0]=='ok'){fn_dhtmlxmessage('','Menu sudah berhasil diupdate.TERIMA KASIH');}
                                                    else{fn_dhtmlxmessage('error','Error Found : '+spres[1]);}
                                                    fn_myform_clear();
                                                    dguserauth.clearAll();
                                                }
                                            }
                                        });
                                        
                                    break;
                               } 
                           });

                           myFormsearch.attachEvent(\"onChange\",function(id,value){
                                switch(id)
                                {                                    
                                    case 'cbotipemenu':
                                        myFormsearch.enableItem(\"btnloadmenu\");
                                        myFormsearch.setItemFocus(\"btnloadmenu\");
                                    break;
                                }
                           });
                           
                           // === data grid attach
                           dguserauth=new dhtmlXGridObject(\"divdgsearch\");
                           dguserauth.setSkin(\"dhx_skyblue\");
                           dguserauth.setImagePath(\"".PATH_THEME."/codebase/imgs/\");
                           dguserauth.setHeader(\"chk,Id,Tipe,Menu Text,Keterangan\");
                           dguserauth.setColTypes(\"ch,ro,ro,ro,ro\"); // ro => Read Only, ed => Edit
                           dguserauth.attachHeader(\"#rspan,#rspan,#combo_filter,#rspan,#rspan\");                                  
                           dguserauth.setInitWidths(\"40,30,60,140,*\");
                           dguserauth.setColAlign(\"center,left,center,left,left\");
                           dguserauth.setColSorting(\"int,int,str,str,str\");
                           
                           //dguserauth.setDateFormat(\"%Y-%m-%d %H:%i:%s\");
                           dguserauth.enablePaging(true,".PAGE_LIMIT.",".PAGE_LIMIT_PART.",\"divdgsearchpaging\");
                           //dguserauth.setPagingSkin(\"toolbar\",\"dhx_skyblue\");
                           dguserauth.setPagingSkin(\"bricks\");
                           dguserauth.enableTooltips(\"false,false,false,false,false\");                           
                           dguserauth.attachFooter(\"<a href='javascript:void(0)' style='color:blue' onClick='fn_checkall(1)'>Check All</a>&nbsp;&nbsp;<a href='javascript:void(0)' style='color:blue' onClick='fn_checkall(0)'>Uncheck all</a>,#cspan,#cspan,#cspan,#cspan\",[\"text-align:left;\"]);
                           dguserauth.init();
                           
                           // === data grid attach Event
                           dguserauth.attachEvent(\"onXLE\",function(){
                                var rwcount=dguserauth.getRowsNum();
                                var menuid=myFormsearch.getItemValue(\"txtmenuid\");
                                if(menuid)
                                {                                    
                                    spmenuid=menuid.split(',');
                                    //dguserauth.cells(40,0).setValue(1);return false;
                                    for(i=1;i<=rwcount;i++)
                                    {
                                        var id=dguserauth.cells(i,1).getValue();
                                        //    id=trim(id);
                                        for(j=0;j<spmenuid.length;j++)
                                        {
                                            if(trim(spmenuid[j])==trim(id))
                                            {
                                                dguserauth.cells(i,0).setValue(1);
                                            }
                                        }
                                        //var id=dguserauth.cells(i,1).getValue();
                                        //var strmatch=spmenuid.indexOf(id);
                                        //if(strmatch>=0){dguserauth.cells(i,0).setValue(1);}
                                    }    
                                }
                           });
                           
                           dguserauth.attachEvent(\"onEditCell\",function(stage,rowid,colid){
                               // stage 2 is edit closed
                               if(colid==0&&stage==1){fn_getmenuid();}
                               //alert(colid);
                               return true;
                           });
                       }
                       
                       function fn_checkall(chkvalue)
                       {
                           var rwcount=dguserauth.getRowsNum();
                           if(rwcount<=0){fn_dhtmlxmessage('error','Mohon maaf data tidak ada / belum query');return false;}
                           //alert(rwcount);
                           for(i=1;i<=rwcount;i++)
                           {
                               dguserauth.cells(i,0).setValue(chkvalue); 
                               //alert(i+' '+dguserauth.cells(i,0).getValue(chkvalue)); 
                           }
                           if(chkvalue==1){fn_getmenuid();}
                       }
                       function fn_getmenuid()
                       {
                           var rwcount=dguserauth.getRowsNum();
                           var varmenuid='';
                           for(i=1;i<=rwcount;i++)
                           {
                               var id=dguserauth.cells(i,0).getValue();
                               if(id==1){varmenuid=varmenuid+dguserauth.cells(i,1).getValue()+',';}
                           }
                           varmenuid=varmenuid.substring(0,varmenuid.length-1);
                           myFormsearch.setItemValue(\"txtmenuid\",varmenuid);
                           //alert(myFormsearch.getItemValue(\"txtmenuid\"));
                       }
                       
                       function fn_myform_clear()
                       {
                           myFormsearch.getCombo(\"cbokduser\").setComboValue('');
                           myFormsearch.getCombo(\"cbokduser\").setComboText('');
                           myFormsearch.getCombo(\"cbotipemenu\").setComboValue('');
                           myFormsearch.getCombo(\"cbotipemenu\").setComboText('');
                           myFormsearch.disableItem(\"btnloadmenu\");
                           myFormsearch.disableItem(\"btnupdatemenu\");
                           myFormsearch.setItemFocus(\"cbokduser\");
                           
                       }
                  </script>";
            echo $this->FN_CLOSEHEADER();
            echo $this->FN_CREATEBODY();
            echo "  <table width=\"100%\" border=\"0\">
                        <tr>
                            <td valign=\"top\">
                                <div id=\"divformsearch\" style=\"width:100%\"></div>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <div id=\"divdgsearch\" style=\"height:360px;width:720px;overflow:hidden\"></div>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <div id=\"divdgsearchpaging\" style=\"width:720px;margin-top:0px\"></div>
                            </td>
                        </tr>
                    </table>";            
            echo $this->FN_CREATEFOOTER();
        }
        
        public function fn_updatemenuid()
        {
            $kduser=$_REQUEST['kduser'];
            $menuid=$_REQUEST['menuid'];//echo $menutype;return true;
            $tipemenu=$_REQUEST['tipemenu'];//echo $menutype;return true;
            //return false;
            $qry="update ".DB_APORTIL.".tbl_userlogin
                  set ".$tipemenu."menu_id='$menuid',uby='".$_SESSION['nik']."',udt=now()
                  where kduser='$kduser'";
            if($this->executequery($qry))
            {
                echo 'ok|';
                //$msg="Menu baru <b>".strtoupper("$nmuser")."</b> sudah berhasil ditambahkan<br/>";
                //$msg.="Klik ".$this->CREATE_LINK($this->fn_url_home(),"disini","javascript:void(0)","_self","Penambahan Menu Baru");
                //$msg.=" untuk Penambahan Menu Baru. TERIMA KASIH";
                //echo $this->SHOWMESSAGE($msg);    
            }else{echo "failed|".$this->getErrorQuery();}
        }        
        
        public function fn_loadmenu()
        {
            $kduser=$_REQUEST["kduser"];
            $tipemenu=$_REQUEST["tipemenu"];
            //include XML Header (as response will be in xml format)
            header("Content-type: text/xml");
            //encoding may be different in your case
            echo('<?xml version="1.0" encoding="utf-8"?>'); 
            //start output of data
            echo "<rows id=\"0\">";

            $swhere="and menugroup<>'SU'";
            if($kduser=='9999'){$swhere="";}
            //output data from DB as XML
//            $qry="select id,kduser,nmuser,hp,pass,maskpass,groupuser,isactivated from ".DB_APORTIL.".tbl_userlogin
//                  where (nmuser like '%$keyword%' or kduser like '%$keyword%') and kduser<>'9999' and isdeleted=0
//                  order by id asc limit ".TBL_PAGE_LIMIT;
            $qry="select id,menutype,menutext,menudesc,0 ischecked from ".DB_APORTIL.".tbl_".$tipemenu."menu
                  where isdeleted=0 and menuactivated=1 $swhere
                  order by id asc limit ".TBL_PAGE_LIMIT;
            $rs=$this->selectquery($qry);                    
            if($rs)
            {
                $i=1;
                while($row=$this->data_row_array($rs))
                {
                    //create xml tag for grid's row
                    echo ("<row id='".$i."'>");
                            print("<cell><![CDATA[".$row["ischecked"]."]]></cell>");
                            print("<cell><![CDATA[".$row["id"]."]]></cell>");
                            print("<cell><![CDATA[".$row["menutype"]."]]></cell>");
                            print("<cell><![CDATA[".$row["menutext"]."]]></cell>");
                            print("<cell><![CDATA[".$row["menudesc"]."]]></cell>");
                    echo ("</row>");
                    $i+=1;
                }
            }
            else
            {
                //error occurs
                echo mysql_errno().": ".mysql_error()." at ".__LINE__." line in ".__FILE__." file<br>";
            }
            echo "</rows>";
    
        }
        
        public function fn_getkduser()
        {
            $kduser=$_REQUEST["kduser"];
            $getkduser=$this->fn_get_fieldvalue("kduser","select kduser from ".DB_APORTIL.".tbl_userlogin where kduser='$kduser'");
            echo $getkduser;
        }

        public function fn_getmenuid()
        {
            $kduser=$_REQUEST["kduser"];
            $tipemenu=$_REQUEST["tipemenu"];
            $menuid=$this->fn_get_fieldvalue($tipemenu."menu_id","select ".$tipemenu."menu_id from ".DB_APORTIL.".tbl_userlogin where kduser='$kduser'");
            echo $menuid;
            
        }
    }
    
?>