<?php


    class procesy
    {

        public static $sql_table = 'procesy';

        public static $own_listing = false;
        public static $own_listing_parse = false;
        public static $own_options = false;
        
        public function __construct()
        {
        }
        
        public static function getList()
        {
            
        }
        
        /**
         * 
         */
        public static function Clear( $uid )
        {
            
            if( !is_numeric( $uid ) ) return;
            
            if( user::$i->mode == 'user' )
            {

                db::$i->q("
                DELETE FROM `".( self::$sql_table )."` 
                WHERE 
                    `user`='".esc( $uid )."' 
                    AND 
                    `end` IS NULL
                ");
                
                    return true;
            }

        }
        
        public static function get( $ProcesId )
        {
            $data = db::$i->row("
            SELECT * 
            FROM `".( self::$sql_table )."` 
            WHERE `id`='".( $ProcesId )."'
            ");   
            
            if( $data )
            {
                return self::parse( $data );
            }
            
                return; 
        }
        
        
        //CreateRanking
        public static function getWithDetails( $ProcesId )
        {
            $data = db::$i->row("
            SELECT * 
            FROM `".( self::$sql_table )."` 
            WHERE `id`='".( $ProcesId )."'
            ");   
            
            if( $data )
            {
                
                list( $userfirstname , $userlastname , $useremail ) = db::$i->row("SELECT `firstname`,`lastname`,`email` FROM `user` WHERE `id`='".( $data['user'] )."'"); 
                $data['user_name'] = ( $userfirstname ? ( $userfirstname . ( $userlastname ? ( ' ' . $userlastname ) : '' ) ) : ( $useremail ) );
                list( $data['temat_name'] ) = db::$i->row("SELECT `nazwa` FROM `tematy` WHERE `id`='".( $data['temat_id'] )."'");
                
                $query = db::$i->q("SELECT * FROM `wartosci` WHERE `proces_id`='".( $ProcesId )."'" , true );
                if( db::$i->rows )
                {
            
                    while( $item = db::$i->f( $query ) )
                    {
                        $alternatywy[$item['alternatywa_id']][$item['kryterium_id']] = $item['wartosc'];
                        $Wagi[$item['kryterium_id']] = $item['waga'];
                    }
                    
                    $data['ranking'] = alternatywy::CreateRanking( $alternatywy , $Wagi );
                    
                }
                
                
                return self::parse( $data );
            }
            
                return; 
        }
        
        public static function add( $name , $UserId , $Therapist , $TematId )
        {

            if( empty( $name ) )
            {
                statement::$i->set(l('Podaj nazwę dla procesu'),'danger');
                return;
            }
                        
            if( empty( $TematId ) )
            {
                statement::$i->set(l('Wybierz temat'),'danger');
                return;
            }
            
            if( db::$i->insert( self::$sql_table , array(
                'nazwa' => esc( $_REQUEST['nazwa'] ),
                'user' => $UserId,
                'therapist' => $Therapist,
                'temat_id' => $TematId
            ) ) )
            {
                $ProcesId = db::$i->insert_id;

                return $ProcesId;
            } 
            
                return;
        }
        
        public static function copy( $ProcesId , $NewName , $User , $Therapist )
        {
            $Proces = self::get( $ProcesId );
            
            if( $Proces->id )
            {
               db::$i->insert( self::$sql_table , array(
                    'user' => $User,
                    'nazwa' => esc( $NewName ),
                    'therapist' => $Therapist,
                    'temat_id' => $Proces->temat_id,
                    'wektor' => $Proces->wektor,
                    'end' => null
               ));
               
               $NewProcesId = db::$i->insert_id;
               
               // Kopiowanie alternatywy
               // Predefiniowany
               if( !$Proces->user )
               {
                    $query = db::$i->q("SELECT * FROM `alternatywy` WHERE `temat_id`='".( $Proces->temat_id )."' AND `proces_id` IS NULL" , true );            
               } 
               else 
               {
                    $query = db::$i->q("SELECT * FROM `alternatywy` WHERE `proces_id`='".( $Proces->id )."'" , true );           
               }

                $AltCount = 0;
                if( db::$i->rows )
                {
                    $AltCount = db::$i->rows;
                    $AlternatywyID = array();
                    
                    while( $item = mysqli_fetch_array( $query , MYSQLI_ASSOC ) )
                    {
                        $OldID = $item['id'];
                        unset( $item['id'] );
                        
                        $item['user'] = $User;
                        $item['therapist'] = $Therapist;
                        $item['proces_id'] = $NewProcesId;
                        
                        // Przypisanie nowych ID do starych / do uzycia przy podmianie podczas kopiowania wartosci
                        if( db::$i->insert('alternatywy', $item ) )
                        {
                            $AlternatywyID[$OldID] = db::$i->insert_id;
                        } else $sql_errors[] = db::$i->error . ': ' . db::$i->query;
                        

                    }    
                }   

                if( !$AltCount OR $AltCount != count( $AlternatywyID ) )
                {
                    statement::$i->set('Problem podczas kopiowania alternatyw','danger');
                }
                                            
               // Kopiowanie kryteriow
               // Predefiniowany
               if( !$Proces->user )
               {
                    $query = db::$i->q("SELECT * FROM `kryteria` WHERE `temat_id`='".( $Proces->temat_id )."' AND `proces_id` IS NULL" , true );            
               } 
               else 
               {
                    $query = db::$i->q("SELECT * FROM `kryteria` WHERE `proces_id`='".( $Proces->id )."'" , true );           
               }

                $KrytCount = 0;
                if( db::$i->rows )
                {
                    $KrytCount = db::$i->rows;
                    $KryteriaID = array();
                    
                    while( $item = mysqli_fetch_array( $query , MYSQLI_ASSOC ) )
                    {
                        $OldID = $item['id'];
                        unset( $item['id'] );

                        $item['proces_id'] = $NewProcesId;
                        
                        // Przypisanie nowych ID do starych / do uzycia przy podmianie podczas kopiowania wartosci
                        if( db::$i->insert('kryteria', $item ) )
                        {
                            $KryteriaID[$OldID] = db::$i->insert_id;
                        } else $sql_errors[] = db::$i->error. ': ' . db::$i->query;

                    }    
                }   
                
                if( !$KrytCount OR $KrytCount != count( $KryteriaID ) )
                {
                    statement::$i->set('Problem podczas kopiowania kryteriów','danger');
                }
               
               // Kopia wartości + Podmiana alternatywa_id, kryterium_id
               $query = db::$i->q("SELECT * FROM `wartosci` WHERE `proces_id`='".( $ProcesId )."' ORDER BY `id` ASC" , true );
               $AllValues = 0;
               
               if( db::$i->rows )
               {
                    $AllValues = db::$i->rows;
                    $sql = array();
                    
                    while( $item = mysqli_fetch_array( $query , MYSQLI_ASSOC ) )
                    {
                       unset( $item['id'] );
                       $item['proces_id'] = $NewProcesId;
                       $item['kryterium_id'] = $KryteriaID[$item['kryterium_id']];
                       $item['alternatywa_id'] = $AlternatywyID[$item['alternatywa_id']];
                       $sql[] = $item;
                    }
                    
                    $NewValue = 0;
                    foreach( $sql as $SqlQuery )
                    {
                        if( db::$i->insert( 'wartosci' , $SqlQuery ) )
                        {
                            $NewValue++;
                        } else $sql_errors[] = db::$i->error. ': ' . db::$i->query;
                    }
               }
               
               if( !$AllValues OR $NewValue != $AllValues )
               {
                    statement::$i->set('Problem podczas kopiowania wartości','danger');
               }
               
               // Debuger
               //if( count( $sql_errors ) ) debug::printr( $sql_errors );
               
                    if( $NewValue AND $AltCount AND $KrytCount ) return $NewProcesId;
               
               
               
            }
                return;
        }
        
        public static function close( $ProcesId )
        {
            if( !$ProcesId ) return;
            
            $Proces = self::get( $ProcesId );
            
            if( $Proces->id AND !$Proces->end )
            {
                return db::$i->update( self::$sql_table , array(
                    'end' => crt()
                ) , $Proces->id );
            } 
            
                return;
        }
        
        public static function unfinished( $UserId )
        {
            $query = db::$i->q("
            SELECT p.*,t.nazwa as tnazwa 
            FROM `".( self::$sql_table )."` p,`tematy` t
            WHERE 
                ( ( p.user='".( $UserId )."' 
                 ) OR p.user IS NULL )
                AND 
                t.id = p.temat_id
            ORDER BY p.user ASC,p.crt ASC
            " , true );

            if( db::$i->rows )
            {
                
                $List = new stdClass;
                $List->Count = db::$i->rows;
                
                while( $item = db::$i->f( $query ) )
                {
                    $List->Items[] = self::parse( $item );
                }
                
                    return $List;
            }
            
            return;
        }
        
        public static function parse( $item )
        {
            return core::object( $item );
        }
        
        public static function options()
        {
            
        }   
        
        public static function details_parse()
        {
            
        }
        
    }
    
?>