<?php
/**
 * 'menu_class' table.
 *
 * @package model
 */
class menu_class
{

    private $n_RoleId = 'UNKNOWN';

    private $n_StartTaskId = 'UNKNOWN';

    private $n_GlobalAccess = 'N';

    protected $n_MenuInit = 'N';

    protected $n_TaskType = 'UNKNOWN';

    protected $n_TaskId = 'UNKNOWN';

    protected $n_TaskDesc = 'UNKNOWN';

    protected $n_ScriptId = 'UNKNOWN';

    protected $n_SubsysDir = 'UNKNOWN';
    protected $n_ImageDir = 'UNKNOWN';

    protected $n_TaskPrefix = 'UNKNOWN';

    protected $n_IsDisabled = 'Y';

    protected $n_Access = FALSE;

    /**
     * Inicializa los parametros de la clase
     *
     * @param String $role            
     */
    public function getInit( $role )
    {
        /*
         * $c = new Criteria();
         * $c->add(mnu_rolePeer::ROLE_ID, $role);
         * $db_MnuRole = mnu_rolePeer::doSelectOne($c);
         */
        /*$con = Conexion::getConexion();
        $sql = "SELECT * FROM SEG_Rol WHERE IdRol='" . $role . "';";
        $result = mysql_query( $sql, $con->getResource() );
        $db_MnuRole = $result ? mysql_fetch_object( $result ) : null;*/
        $o_SEG_RolFN = new SEG_RolFN();
        $o_SEG_RolBN = $o_SEG_RolFN->selectByPK( $role );
        if( $o_SEG_RolBN )
        {
            $this->n_RoleId = $o_SEG_RolBN->getIdRol();
            $this->n_StartTaskId = $o_SEG_RolBN->getIdTareaInicio();
            $this->n_GlobalAccess = $o_SEG_RolBN->getAccesoGlobal();
            
            $this->n_MenuInit = 'Y';
        }
    }

    /**
     * Retorna la tarea inicial del role
     *
     * @return string
     */
    public function getStartTaskId()
    {
        if( $this->n_MenuInit == 'N' )
            return;
        
        return $this->n_StartTaskId;
    }

    /**
     * Retorna un array de parametros con referencia a la tarea
     * consideracion:
     * si no es inicializado o
     * si tipo de tarea es <> PROC o
     * si la tarea no pertenece al
     * role devuelve un array = NULL
     *
     * @param string $task            
     * @return un array
     */
    public function getTask( $task )
    {
        if( $this->n_MenuInit == 'N' )
            return Array();
        
        $this->getMnuRoleTask( $task );
        
        if( $this->n_TaskType != 'proc' )
            return Array();
        
        $eTask ['TaskId'] = $this->n_TaskId;
        $eTask ['TaskDesc'] = $this->n_TaskDesc;
        $eTask ['ButtonText'] = $this->n_ButtonText;
        $eTask ['TaskType'] = $this->n_TaskType;
        $eTask ['ScriptId'] = $this->n_ScriptId;
        $eTask ['IsDisabled'] = $this->n_IsDisabled;
        $eTask ['SubsysDir'] = $this->n_SubsysDir;
        $eTask ['ImageDir'] = $this->n_ImageDir;
        $eTask ['TaskPrefix'] = $this->n_TaskPrefix;
        $eTask ['Access'] = $this->n_Access;
        $eTask ['NavButton'] = 'UNKNOWN';
        
        if( $eTask ['Access'] && $eTask ['IsDisabled'] == 'N' )
        {
            $eTask ['PathScriptId'] = $eTask ['SubsysDir'] . $eTask ['ScriptId'];
            $eTask ['PathImageId'] = $this->getImagesDir( $eTask ['ImageDir'] ) . substr( $eTask ['ScriptId'], 0, strpos( $eTask ['ScriptId'], "/" ) + 1 ) . $eTask ['TaskId'] . ".gif";
        }
        else
        {
            $eTask ['TaskType'] = 'UNKNOWN';
            $eTask ['PathScriptId'] = 'UNKNOWN';
            $eTask ['PathImageId'] = 'UNKNOWN';
        }
        
        if( $eTask ['TaskType'] == 'proc' )
        {
            $eTask ['NavButton'] = $this->getMnuMenuNav( $eTask ['TaskId'] );
            $eTask ['TaskField'] = $this->getMnuRoleTaskField( $eTask ['TaskId'] );
        }
        else
        {
            $eTask ['NavButton'] = Array();
            $eTask ['TaskField'] = Array();
        }
        
        return $eTask;
    }

    /**
     * Enter description here...
     *
     * @param unknown_type $task            
     * @param unknown_type $IsLevel            
     * @return unknown
     */
    public function getMenu( $task, $IsLevel = 0 )
    {
        if( $this->n_MenuInit == 'N' )
        {
            return Array();
        }
        return ( $this->getMenuArray( $task, $IsLevel ) );
    }

    /**
     * Enter description here...
     *
     * @param unknown_type $task            
     * @return unknown
     */
    public function getTaskHelp( $task )
    {
        if( $this->n_MenuInit == 'N' )
            return;
            /*
         * $c = new Criteria();
         * $c->add(help_textPeer::TASK_ID, $task);
         * $db_HelpText = help_textPeer::doSelectOne($c);
         */
        
        /*$con = Conexion::getConexion();
        $sql = "SELECT * FROM SEG_TextoAyuda WHERE IdTarea = '" . $task . "';";
        $result = mysql_query( $sql, $con->getResource() );
        $db_HelpText = $result ? mysql_fetch_object( $result ) : null;*/
        
        $o_SEG_TextoAyudaFN = new SEG_TextoAyudaFN();
        $o_SEG_TextoAyudaBN = $o_SEG_TextoAyudaFN->selectByPK( $task );
        
        if( $o_SEG_TextoAyudaBN )
        {
            return $o_SEG_TextoAyudaBN->getTextoAyuda();
        }
        return;
    }

    public function getGlobalAccess()
    {
        return $this->n_GlobalAccess;
    }
    
    /**
     * Retorna el menu
     * 1-mnu_menuPeer::MENU_ID
     * 2-mnu_menuPeer::TASK_ID_JNR
     * 3-mnu_menuPeer::SORT_SEQ
     * 4-mnu_menuPeer::BUTTON_TEXT
     * 5-mnu_taskPeer::TASK_DESC
     * 6-mnu_taskPeer::TASK_TYPE
     * 7-mnu_taskPeer::SCRIPT_ID
     * 8-mnu_taskPeer::IS_DISABLED
     *
     * @param string $menu            
     * @return array
     */
    private function getMnuMenu( $menu )
    {
        /*
         * $menu_lst = Array();
         * $c = new Criteria();
         * $c->add(mnu_menuPeer::MENU_ID, $menu);
         *
         * mnu_menuPeer::addSelectColumnsSome($c);
         * $db_MnuMenu = mnu_menuPeer::doSelectRS($c);
         */
        //$con = Conexion::getConexion();

        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //TEMPORAL
        //para aplicar la gestion de permisos
        $o_SEG_MenuFN = new SEG_MenuFN();
        $o_SEG_MenuFN->setIdMenu( $menu );
        $a_SEG_Menu = $o_SEG_MenuFN->select();

        /*$s_Sql = "SELECT * FROM SEG_Menu WHERE IdMenu = '".$menu."';";
        $result = mysql_query( $s_Sql, $con->getResource() );*/
        if( $a_SEG_Menu )
        {
            //while( $db_MnuMenu = mysql_fetch_object( $result ) )
            foreach( $a_SEG_Menu as $o_SEG_MenuBN )
            {
                $IdTarea = $o_SEG_MenuBN->getIdTareaHijo();

                $a_Data = explode( ".", $IdTarea );

                if( count( $a_Data ) < 4 )
                {
                    continue;
                }

                $s_ScriptId = $a_Data[2]."/".$a_Data[3];

                $IdSubSistema = "s".$a_Data[0].".".$a_Data[1];

                $TareaDescripcion = $o_SEG_MenuBN->getBotonTexto();

                $s_Sql = "
                            REPLACE INTO SEG_Tarea
                            ( IdTarea, TareaDescripcion, BotonTexto, TareaTipo, ScriptId, DeshabilitadoFlg, IdPatron, IdSubSistema,  FechaCreacion, UsuarioCreacion )
                            VALUES
                            ( '".$IdTarea."', '$TareaDescripcion', '$TareaDescripcion', 'proc', '$s_ScriptId', 'N', 'list001', '$IdSubSistema', '".date( 'Y-m-d H:i:s' )."', 'wtaype' );
                        ";
                $o_DBConnect = Conexion::getConexion();
                $o_Statement = $o_DBConnect->createStatement();
                $o_Statement->executeQuery( $s_Sql );
                //mysql_query( $s_Sql, Conexion::getConexion()->getResource() );
            }
        }
        
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        $sql = "SELECT SEG_Menu.IdMenu, SEG_Menu.IdTareaHijo, SEG_Menu.Secuencia, SEG_Menu.BotonTexto, SEG_Menu.Estado, SEG_Tarea.TareaDescripcion,SEG_Tarea.TareaTipo, SEG_Tarea.ScriptId, SEG_Tarea.DeshabilitadoFlg
                FROM SEG_Menu
                  Inner Join SEG_Tarea ON SEG_Menu.IdTareaHijo = SEG_Tarea.IdTarea
                WHERE IdMenu = '" . $menu . "'";
        $o_Resource = Conexion::getConexion();
        $o_Statement = $o_Resource->prepareStatement( $sql );
        $o_ResultSet = $o_Statement->executeQuery();
        $i_NumRows = $o_ResultSet->getRecordCount();

        /*$result = mysql_query( $sql, $con->getResource() );
        $num_rows = mysql_num_rows( $result );*/
        
        $menu_lst = array();
        if( $i_NumRows > 0 )
        {
            //while( $db_MnuMenu = mysql_fetch_object( $result ) )
            while( $o_ResultSet->next() ) 
            {
                $db_MnuMenu = $o_ResultSet->getRow(); //devuele array
                
                $seq = $db_MnuMenu['Secuencia'];
                
                $menu_lst[$seq]['TaskId']     = $db_MnuMenu['IdTareaHijo'];
                $menu_lst[$seq]['ButtonText'] = $db_MnuMenu['BotonTexto'];
                $menu_lst[$seq]['MenuEstado'] = $db_MnuMenu['Estado'];
                $menu_lst[$seq]['TaskDesc']   = $db_MnuMenu['TareaDescripcion'];
                $menu_lst[$seq]['TaskType']   = $db_MnuMenu['TareaTipo'];
                $menu_lst[$seq]['IsDisable']  = $db_MnuMenu['DeshabilitadoFlg'];
                
                $this->getMnuRoleTask( $menu_lst[$seq]['TaskId'] ); // condicionar
                $menu_lst [$seq] ['Access']       = $this->n_Access;
                $menu_lst [$seq] ['PathScriptId'] = $this->n_SubsysDir . $db_MnuMenu['ScriptId'];
            }
            
            if( count( $menu_lst ) > 0 )
                return $menu_lst;
        }
        return array();
    }

    /**
     * Retorna el menu_nav
     * $db_MnuMenu->getString(1) task_id_snr
     * $db_MnuMenu->getString(3) sort_seq
     * $db_MnuMenu->getString(2) task_id_jnr
     * $db_MnuMenu->getString(4) button_text
     *
     * @param string $menu            
     * @return array
     */
    private function getMnuMenuNav( $menu )
    {
        /*
         * $menu_lst = Array();
         * $c = new Criteria();
         * $c->add(mnu_nav_buttonPeer::TASK_ID_SNR, $menu);
         * $db_MnuMenu = mnu_nav_buttonPeer::doSelectRS($c);
         */
        // falta
        //$con = Conexion::getConexion();
        $sql = "SELECT b.IdTareaHijo, b.DescripcionBoton, b.Secuencia, t.TareaDescripcion, t.TareaTipo, t.DeshabilitadoFlg, b.bar_type, t.Settings, t.ScriptId
                FROM SEG_NavBoton b
                  Inner Join SEG_Tarea t ON b.IdTareaHijo = t.IdTarea
                WHERE b.IdNavegation = '" . $menu . "';";
        // $sql = "SELECT * FROM mnu_nav_button b Inner Join mnu_task t ON b.task_id_jnr = t.task_id WHERE b.task_id_snr = '".$menu."';";
        
        $o_Resource = Conexion::getConexion();
        $o_Statement = $o_Resource->prepareStatement( $sql );
        $o_ResultSet = $o_Statement->executeQuery();
        $i_NumRows = $o_ResultSet->getRecordCount();
        
        /*$result = mysql_query( $sql, $con->getResource() );
        $num_rows = mysql_num_rows( $result );*/
        // $db_HelpText = $result ? mysql_fetch_object($result) : null;
        $menu_lst = array();
        if( $i_NumRows > 0 )
        {
            //while( $ob_mnuNavButton = mysql_fetch_object( $result ) )
            while( $o_ResultSet->next() ) 
            {
                $ob_mnuNavButton = $o_ResultSet->getRow(); //devuele array
                // $ob_mnuNavButton = new mnu_nav_button();
                // $ob_mnuNavButton->hydrate($db_MnuMenu);
                
                $seq = $ob_mnuNavButton['Secuencia'];
                
                $menu_lst[$seq]['TaskId']     = $ob_mnuNavButton['IdTareaHijo'];
                $menu_lst[$seq]['ButtonText'] = $ob_mnuNavButton['DescripcionBoton'];
                $menu_lst[$seq]['TaskDesc']   = $ob_mnuNavButton['TareaDescripcion']; // TASK
                $menu_lst[$seq]['TaskType']   = $ob_mnuNavButton['TareaTipo']; // task
                $menu_lst[$seq]['IsDisable']  = $ob_mnuNavButton['DeshabilitadoFlg']; // task
                $menu_lst[$seq]['BarType']    = $ob_mnuNavButton['bar_type'];
                $menu_lst[$seq]['Settings']   = $ob_mnuNavButton['Settings']; // task

                $this->getMnuRoleTask( $menu_lst[$seq]['TaskId'] );
                $menu_lst[$seq]['Access']       = $this->n_Access;
                $menu_lst[$seq]['PathScriptId'] = $this->n_SubsysDir.$ob_mnuNavButton['ScriptId']; // task
                $menu_lst[$seq]['PathImageId']  = $this->getImagesDir( $this->n_ImageDir ) . $menu_lst[$seq]['TaskId'].".gif";
            }
            if( count( $menu_lst ) > 0 )
            {
                ksort( $menu_lst );
                return $menu_lst;
            }
        }
        
        return array();
    }

    /**
     * Enter description here...
     *
     * @param unknown_type $taskId            
     * @return unknown
     */
    private function getMnuRoleTaskField( $taskId )
    {
        $FieldLst = Array();
        
        if( $this->n_GlobalAccess == 'N' )
        {
            /*
             * $c = new Criteria();
             * $c->add(mnu_role_taskfieldPeer::ROLE_ID, $this->n_RoleId);
             * $c->add(mnu_role_taskfieldPeer::TASK_ID, $taskId);
             * $db_MnuTaskFields = mnu_role_taskfieldPeer::doSelectRS($c);
             */
            
            return null;
            //SE TIENE QUE IMPLEMENTAR...
            
            $con = Conexion::getConexion();
            $sql = "SELECT * FROM SEG_RolTareaCampo WHERE IdRol = '" . $this->n_RoleId . "' AND IdTarea = '" . $taskId . "';";
            //echo $sql."<br>";
            $result = mysql_query( $sql, $con->getResource() );
            $num_rows = mysql_num_rows( $result );
            // $db_HelpText = $result ? mysql_fetch_object($result) : null;
            
            if( $num_rows > 0 )
            {
                while( $ob_mnuTaskField = mysql_fetch_object( $result ) )
                {
                    
                    // $ob_mnuTaskField = new mnu_role_taskfield();
                    // $ob_mnuTaskField->hydrate($db_MnuTaskFields);
                    
                    $FieldLst [$ob_mnuTaskField->field_id] = $ob_mnuTaskField->AccesoTipo;
                    /*
                     * switch( $ob_mnuTaskField->getAccessType() ){
                     * case 'FULL':
                     * $FieldLst[$ob_mnuTaskField->getFieldId()]='';
                     * break;
                     * case 'NDI' :
                     * $FieldLst[$ob_mnuTaskField->getFieldId()]='disabled';
                     * break;
                     * case 'NED' :
                     * $FieldLst[$ob_mnuTaskField->getFieldId()]='readonly';
                     * break;
                     * }
                     */
                }
                // if (count($FieldLst) > 0)
                // return $FieldLst;
            }
        }
        return $FieldLst;
    }

    /**
     * Enter description here...
     *
     * @param string $task            
     * @return bool (TRUE/FALSE)
     */
    private function getMnuRoleTask( $task )
    {
        $this->n_TaskId = 'UNKNOWN';
        $this->n_TaskDesc = 'UNKNOWN';
        $this->n_ButtonText = 'UNKNOWN';
        $this->n_TaskType = 'UNKNOWN';
        $this->n_ScriptId = 'UNKNOWN';
        $this->n_IsDisabled = 'Y';
        $this->n_SubsysDir = 'UNKNOWN';
        $this->n_TaskPrefix = 'UNKNOWN';
        $this->n_Access = 0;
        
        if( ! $this->getMnuTask( $task ) )
        {
            return ( FALSE );
        }
        
        if( $this->n_GlobalAccess == 'N' )
        {
            /*$con = Conexion::getConexion();
            $sql = "SELECT * FROM SEG_TareaRol WHERE IdRol = '" . $this->n_RoleId . "' AND IdTarea = '" . $task . "';";
            $result = mysql_query( $sql, $con->getResource() );
            $db_MnuRoleTask = $result ? mysql_fetch_object( $result ) : null;*/
            
            $o_SEG_TareaRolFN = new SEG_TareaRolFN();
            $o_SEG_TareaRolBN = $o_SEG_TareaRolFN->selectByPK( $this->n_RoleId, $task );
            
            if( $o_SEG_TareaRolBN )
            {
                $this->n_Access = 1;
            }
        }
        else
        {
            $this->n_Access = 1;
        }
        
        return ( true );
    }

    /**
     * Retorno el nodo de la tarea
     * es llamado solo por getMnuRoleTask()
     * 
     * @param string $task            
     * @return bool (TRUE/FALSE)
     */
    private function getMnuTask( $task )
    {
        //$con = Conexion::getConexion();
        $sql = "SELECT *
                FROM SEG_Tarea
                  Inner Join SEG_SubSistema ON SEG_Tarea.IdSubSistema = SEG_SubSistema.IdSubSistema
                WHERE IdTarea = '" . $task . "';";
        $o_Resource = Conexion::getConexion();
        $o_Statement = $o_Resource->prepareStatement( $sql );
        $o_ResultSet = $o_Statement->executeQuery();
        $i_NumRows   = $o_ResultSet->getRecordCount();
        
        //$result = mysql_query( $sql, $con->getResource() );
        //$db_MnuTask = $result ? mysql_fetch_object( $result ) : null;
        
        //if( $db_MnuTask )
        if( $i_NumRows > 0 )
        {
            $o_ResultSet->next();
            $db_MnuTask = $o_ResultSet->getRow(); //devuele array
            
            $this->n_TaskId = $db_MnuTask['IdTarea'];
            $this->n_TaskDesc = $db_MnuTask['TareaDescripcion'];
            $this->n_ButtonText = $db_MnuTask['BotonTexto'];
            $this->n_TaskType = $db_MnuTask['TareaTipo'];
            $this->n_ScriptId = $db_MnuTask['ScriptId'];
            $this->n_IsDisabled = $db_MnuTask['DeshabilitadoFlg'];
            //$this->n_SubsysDir = $db_MnuTask->SubSistemaDir;
            //aqui se implementa la constante del proyecto - directorio
            $this->n_SubsysDir = Constantes::ROOT_DIR_APP.$db_MnuTask['SubSistemaDir'];
            $this->n_ImageDir = Constantes::APP_CREDENTIALS."/".$db_MnuTask['SubSistemaDir'];
            $this->n_TaskPrefix = $db_MnuTask['TareaPrefijo'];
            return ( TRUE );
        }
        return ( FALSE );
    }

    /**
     * Recupera la estructura del menu en un array()
     *
     * @param String $task            
     * @return array
     */
    private function getMenuArray( $task, $IsLevel )
    {
        $menu_lst = Array();
        
        $this->getMnuRoleTask( $task );
        
        if( $this->n_TaskType == 'menu' )
        {
            $menu = $this->getMnuMenu( $this->n_TaskId );
        }
        else
        {
            $menu = Array();
        }
        
        // /return $this->n_Access;
        if( count( $menu ) <= 0 )
            ;
        else
        {

            ksort( $menu );
            for( reset( $menu ); $key = key( $menu ); next( $menu ) )
            {
                $menu_lst[$key]['TaskId']       = $menu[$key]['TaskId'];
                $menu_lst[$key]['ButtonText']   = $menu[$key]['ButtonText'];
                $menu_lst[$key]['MenuEstado']   = $menu[$key]['MenuEstado'];
                $menu_lst[$key]['TaskDesc']     = $menu[$key]['TaskDesc'];
                $menu_lst[$key]['TaskType']     = $menu[$key]['TaskType'];
                $menu_lst[$key]['IsDisable']    = $menu[$key]['IsDisable'];
                $menu_lst[$key]['PathScriptId'] = $menu[$key]['PathScriptId'];
                $menu_lst[$key]['Access']       = $menu[$key]['Access'];
                
                if( $IsLevel == 1 && $menu_lst [$key] ['Access'] && $menu_lst [$key] ['IsDisable'] && $menu_lst [$key] ['TaskType'] == 'menu' )
                    $menu_lst [$key] ['NextMenu'] = $this->getMenuArray( $menu [$key] ['TaskId'], $IsLevel );
                else
                    $menu_lst [$key] ['NextMenu'] = array();
            }
        }
        return $menu_lst;
    }

    /**
     * Enter description here...
     *
     * @param unknown_type $dir            
     * @return unknown
     */
    private function getImagesDir( $dir )
    {
        $a = strpos( $dir, ".php" );
        $ap = substr( $dir, 0, $a );
        $a = strpos( $dir, "/", 1 );
        $ap .= substr( $dir, $a );
        
        return Constantes::ROOT_DIR_IMG . $ap;
    }
} // mnu_class
<<<TODO
 roleid de ser verificado por la clase
 el nav_buttom falta verificar(solo es en caso PROC)***confirmar***
 mostrar la opcion en disable para el usuario
 mostrar la opcion en disable para el sistema
 validar recursividad infinita
TODO
?>