<?
abstract class i_db_object
{
    static $table_name='';
    static $table_title='';
    static $clss=0;
    static $class_descr=[];

    static $auto_generate_uid=0;


    public static function create($form_data, $options=array())
    {
        ob_start();

        // формируем запись для базы
        $data=static::prepare_rec_by_form($form_data);
        $data=static::prepare_rec_to_create($data);

        // добавляем в базу
        $id=adding_rec_to_table(static::$table_name, $data);
        $result['id']=$id;

        // проверка существования записи в базе
        $new_rec=execSQL_van('select * from ' . static::$table_name . ' where pkey=' . $result['id']);
        if ($new_rec['pkey'])
        {
            $result['result']=true;
            $result['reffer']=$new_rec['_reffer'];
            $result['id']=$new_rec['pkey'];
            $result['status']='success';
            $result['info']='успешно - "<strong>' . $result['id'] . '</strong>"';
        }
        else
        {
            $result['result']=false;
            $result['status']='failer';
            $result['info']='Ошибка';
        }

        $text=ob_get_clean();
        $result['debug']=$text;

        return ($result);
    }

    public static function prepare_rec_to_create($data)
     { $data['clss']=static::$clss ;
   		if (static::$auto_generate_uid) $data['uid']=ENGINE()->generate_UID();
       return($data) ;
     }

    public static function get_changes($old_rec,$form_data)
    {   $result=[] ;
        if (sizeof($form_data)) foreach ($form_data as $key=>$value)
        { $text_value=(is_array($value))? print_r($value,true) : $value ;
          if (!isset($old_rec[$key])) $result[$key]=['new'=>$text_value] ;
          else if ($old_rec[$key]!=$value) $result[$key]=['old'=>$old_rec[$key],'new'=>$text_value] ;
        }
        return($result) ;
    }

    public static function save($pkey, $form_data, $options=[])
    {
        $result=[];

        if (!$result['error'])
        { // формируем запись для базы
            $data=static::prepare_rec_by_form($form_data);
            //damp_array($data);
            $old_rec=[] ; $arr_changes=[] ;
            if ($options['check_changes'])
            { $old_rec=static::get_rec_by_id($pkey) ;
              $arr_changes=static::get_changes($old_rec,$form_data) ;
            }

            if (!$options['check_changes'] or sizeof($arr_changes))
            {   // сохраняем данные в базе
            $result_update=update_rec_in_table(static::$table_name, $data, 'pkey=' . $pkey,['debug'=>0]);
            if (!$result_update['warning'])
            {
                $result['status']='success';
                $result['result']=true;
                $result['message']='Сохранено';
            }
            else
            {
                $result['result']=false;
                $result['status']='failer';
            }
        }
            else //if ($options['check_changes'] and !sizeof($arr_changes))
            {
                $result['status']='success';
                $result['result']=true;
                $result['message']='Изменения отсутствуют';
            }

            $result['changes']=$arr_changes;
        }
        //$result['result']=false;
        return $result;
    }

    public static function copy($pkey, $options=[])
    {

        $rec=static::get_rec_by_id($pkey);
        unset($rec['pkey'], $rec['_reffer'], $rec['temp']);
        $id=adding_rec_to_table(static::$table_name, $rec);

        // проверка существования записи в базе
        if ($id)
        {
            $result['id']=$id;
            $result['status']='success';
            $result['info']='<span class="green">Успешно </span>, ID ' . $id;
        }
        else
        {
            $result['status']='failer';
            $result['error']='Ошибка';
        }
        return ($result);
    }

    public static function delete($pkey, $options=[])
    {
        $pkey=(is_array($pkey)) ? implode(',', $pkey) : $pkey;
        $cnt=execSQL_update('delete from ' . static::$table_name . ' where pkey in (' . $pkey . ')');
        $result['status']='success';
        $result=['result'=>true];
        return ($result);
    }

    public static function prepare_rec_by_form($form_data)
    {
        $data=$form_data;
        $data['clss']=static::$clss;
        if (isset($form_data['enabled'])) $data['enabled']=$form_data['enabled'];
        if (isset($form_data['status'])) $data['status']=($form_data['status']) ?: 0;
        if (isset($form_data['account_id'])) $data['account_id']=($form_data['account_id']) ?: 0;
        if (isset($form_data['group_id'])) $data['group_id']=($form_data['group_id']) ?: 0;
        if (isset($form_data['name'])) $data['obj_name']=($form_data['name']) ?: '';
        if (isset($form_data['obj_name'])) $data['obj_name']=($form_data['obj_name']) ?: '';
        return ($data);
    }

    public static function prepare_public_info(&$rec)
    {

    }

    public static function get_rec_by_pkey($pkey, $options=[])
    {
        $_usl=[];
        $_usl[]='pkey=' . $pkey;
        $usl=implode(' and ', $_usl);
        $rec=execSQL_van('select * from ' . static::$table_name . ' where ' . $usl,$options);
        static::prepare_public_info($rec) ;
        return ($rec);
    }

    public static function get_rec_by_id($pkey, $options=[])
    {   $rec=static::get_rec_by_pkey($pkey, $options);
        static::prepare_public_info($rec) ;
        return ($rec);
    }

    public static function get_id_by_name($name)
    {
        $id=execSQL_value('select pkey from ' . static::$table_name . ' where obj_name=:name', array(':name' => $name));
        return ($id);
    }


    // специально для записей, где идентификатор в id
    public static function get_rec_by_dID($idd, $options=[])
    {
        $_usl=[];
        $_usl[]='id=' . $idd;
        if (static::$clss)
        {
            $_usl[]='clss=' . static::$clss;
        }
        $usl=implode(' and ', $_usl);
        $rec=execSQL_van('select * from ' . static::$table_name . ' where ' . $usl);
        static::prepare_public_info($rec) ;
        return ($rec);
    }

    public static function get_reffer_by_id($id)
    {
        $reffer=$id . '.' . _DOT(static::$table_name)->pkey;
        return ($reffer);
    }

    public static function get_rec_by_uid($uid, $options=[])
    {
        $_usl=[];
        $_usl[]='uid="' . $uid . '"';
        if (static::$clss)
        {
            $_usl[]='clss=' . static::$clss;
        }
        $usl=implode(' and ', $_usl);
        $rec=execSQL_van('select * from ' . static::$table_name . ' where ' . $usl);
        static::prepare_public_info($rec) ;
        return ($rec);
    }

    public static function get_rec($fields_usl=[])
   	{
   		$arr_params=[] ; $_usl_select=[];
   		if (sizeof($fields_usl)) foreach ($fields_usl as $fname=>$fvalue)
   		{
   			if (!is_array($fvalue))
   			{ $_usl_select[]=$fname.'=:'.$fname;
   		   	$arr_params[$fname]=$fvalue;
   			}
   			else
   			{
   				$_usl_select[]=$fname.' in ('.implode(',',$fvalue).')';
   				//$arr_params[$fname]=$fvalue;
   			}
   		}
   		$usl_select=(sizeof($_usl_select))? ' where '.implode(' and ',$_usl_select):'' ;
   		$rec=execSQL_van('select * from '.static::$table_name.$usl_select.' order by obj_name',['sql_params'=>$arr_params,'debug'=>0]);
        static::prepare_public_info($rec) ;
   		return ($rec);
   	}

    public static function get_recs($fields_usl=[])
   	{
   		$arr_params=[] ; $_usl_select=[];
   		if (sizeof($fields_usl)) foreach ($fields_usl as $fname=>$fvalue)
   		{
   			if (!is_array($fvalue))
   			{ $_usl_select[]=$fname.'=:'.$fname;
   		   	$arr_params[$fname]=$fvalue;
   			}
   			else
   			{
   				$_usl_select[]=$fname.' in ('.implode(',',$fvalue).')';
   				//$arr_params[$fname]=$fvalue;
   			}
   		}
   		$usl_select=(sizeof($_usl_select))? ' where '.implode(' and ',$_usl_select):'' ;
   		$recs=execSQL('select * from '.static::$table_name.$usl_select.' order by obj_name',['sql_params'=>$arr_params,'debug'=>0]);
        if (_sizeof($recs)) foreach ($recs as $id=>$rec) static::prepare_public_info($recs[$id]) ;
   		return ($recs);
   	}

    public static function get_last_id_of_parent($parent)
    {
        $last_id=execSQL_value('select max(id) from obj_site_list where parent=' . $parent);
        $last_id++;
        return ($last_id);
    }

    public static function reg_class()
    {
        $descr_class=[];
        $descr_class[static::$clss]=static::$class_descr;
        SETUP()->reg_class($descr_class);
    }

	public static function create_table_for_clss()
	{
		$pattern=[] ;
		$pattern['table_title'] = static::$table_title;
		$pattern['use_clss'] = static::$clss;
		$pattern['table_name'] = static::$table_name;
		$pattern['table_clss'] = 101;
		if (isset(static::$def_recs)) $pattern['def_recs'] = static::$def_recs;
		SETUP()->create_table_by_pattern($pattern);
	}
}

?>
