<?php
class DbModel
{
  public $data;
  public $table;
  public $table_key = 'id';

  public function __construct( $id )
  {
    global $mdb;

    if ( $id )
    {
      $result = $mdb -> get( $this -> table, '*', [ $this -> table_key => $id ] );
      if ( is_array( $result ) ) foreach ( $result as $key => $val )
        $this -> $key = $val;

        if ( is_array( $this -> otm ) ) foreach ( $this -> otm as $otm )
        {
          if ( $otm['skey'] )
          {
            $result2 = $mdb -> select( $otm['table'], '*', [ $otm['fkey'] => $id ] );
            if ( is_array( $result2 ) ) foreach ( $result2 as $row2 )
            {
              $this -> data[ $otm['name'] ][ $row2[ $otm['skey'] ] ] = $row2;
            }
          }
          else
            $this -> data[ $otm['name'] ] = $mdb -> select( $otm['table'], '*', [ $otm['fkey'] => $id ] );
        }

        if ( is_array( $this -> sotm ) ) foreach ( $this -> sotm as $sotm )
        {
          $this -> data[ $sotm['name'] ] = $mdb -> select( $sotm['table'], $sotm['column'], [ $sotm['fkey'] => $id ] );
        }
    }
  }

  public function __get( $variable )
  {
    if ( array_key_exists( $variable, $this -> data ) )
      return $this -> data[$variable];
  }

  public function __set( $variable, $value )
  {
    $this -> data[$variable] = $value;
  }

  public function save()
  {
    global $mdb;

    if ( $this -> __get( $this -> table_key ) )
    {
      $table_id_param = $this -> table_key;
      $table_id_value = $this -> __get( $this -> table_key );
      $data_tmp =  $this -> data;
      unset( $data_tmp[ $table_id_param ] );

      $mdb -> update( $this -> table, $data_tmp, [ $table_id_param => $table_id_value ] );

      return $table_id_value;
    }
    else
    {
      $mdb -> insert( $this -> table, $this -> data );
      $this -> __set( $this -> table_key, $mdb -> id() );
    }
    return $this -> __get( $this -> table_key );
  }

  public function delete()
  {
    global $mdb;
    return $mdb -> delete( $this -> table, [ $this -> table_key => $this -> __get( $this -> table_key ) ] );
  }

}
