<?php
class DataBase
{  
  public function updateDataBase()
  {
    global $db;
    
    $query = $db -> query( 'SHOW COLUMNS FROM pp_settings' );
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
    {
      if ( $row['Field'] == 'value' && $row['Type'] != 'text' )
        $query = $db -> query( 'ALTER TABLE pp_settings CHANGE value value TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL' );
    }
    $query -> closeCursor();
    
    $query = $db -> query( 'SELECT 1 FROM pp_langs_text WHERE text = "T_PROSZE_WYBRAC_KOSZT_TRANSPORTU"' );
    if ( !$query -> rowCount() )
      $db -> query( 'INSERT INTO pp_langs_text ( text, pl ) VALUES ( "T_PROSZE_WYBRAC_KOSZT_TRANSPORTU", "Proszę wybrać koszt transportu." )' );
    
    $query = $db -> query( 'SELECT 1 FROM pp_langs_text WHERE text = "T_KOSZT_TRANSPORTU"' );
    if ( !$query -> rowCount() )
      $db -> query( 'INSERT INTO pp_langs_text ( text, pl ) VALUES ( "T_KOSZT_TRANSPORTU", "Koszt transportu" )' );
    
    $query = $db -> query( 'CREATE TABLE IF NOT EXISTS `pp_transport` (
                              `id` int(11) NOT NULL AUTO_INCREMENT,
                              `name` varchar(255) COLLATE utf8_polish_ci NOT NULL,
                              `cost` decimal(12,2) NOT NULL,
                              `enabled` int(11) NOT NULL DEFAULT \'0\',
                              PRIMARY KEY (`id`)
                            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1;' );
    
    self::add_column_if_not_exist( 'pp_products', 'round_unit', 'INTEGER DEFAULT 0' );
    self::add_column_if_not_exist( 'pp_orders', 'transport_name', 'varchar(255) DEFAULT NULL' );
    self::add_column_if_not_exist( 'pp_orders', 'transport_cost', 'decimal(12,2) DEFAULT NULL' );
  }
  
  public function add_column_if_not_exist( $table, $column, $column_attr = "VARCHAR( 255 ) NULL" )
  {
    global $db;
    
    $query = $db -> query( 'SHOW COLUMNS FROM ' . $table . ' LIKE "' . $column . '"' );
    if ( !$query -> rowCount() )
      $db -> query( 'ALTER TABLE ' . $table . ' ADD ' . $column . ' ' . $column_attr );
    $query -> closeCursor();
  }
  
  public static function SaveData( $db_edit_table, $db_edit_key, $db_edit_val, $db_edit_pols, $db_edit_pass, $db_edit_pols_t )
  {
    global $lang, $db;

    $sql = '';

    if ( is_array( $db_edit_pols ) ) foreach ( $db_edit_pols as $val )
    {
      if ( $sql && $val != 'image' )
        $sql .= ',';
      if ( $val != 'image' )
        $sql .= $val . "='" . addslashes( \System::saveString( \System::formGet( $val ) ) ) . "'";
    }

    if ( $db_edit_pass )
    {
      $name   = $db_edit_pass['nazwa1'];
      $pass1  = \System::saveString( \System::formGet( $name ) );
      $pass2  = \System::saveString( \System::formGet( $name . '_repeat' ) );
      if ( $pass1 != $pass2 )
        \System::setAlert( $lang -> getTrans( 'T_HASLA_ROZNE' ) );
      else
      {
        if ( strlen($pass1) >= 5 )
        {
          if ( $sql )
            $sql .= ',';
          $sql .= $name . "='" . md5($pass1) . "'";
        }
        else
        {
          if ( strlen( $pass1 ) < 5 )
            \System::setAlert( $lang -> getTrans( 'T_HASLA_ZA_KROTKIE' ) );
        }
      }
    }

    if ( $db_edit_table && $db_edit_key && $db_edit_val && $db_edit_pols )
    {
      $db_edit_table  = \System::saveString( $db_edit_table );
      $db_edit_key    = \System::saveString( $db_edit_key );
      $db_edit_val    = \System::saveString( $db_edit_val );

      $query = $db -> query( "UPDATE " . $db_edit_table . " SET " . $sql . " WHERE " . $db_edit_key . "='" . $db_edit_val . "'" );

      for ( $i = 0; $i < count( $db_edit_pols_t ); $i++ )
      {
        if ( $db_edit_pols_t[$i] == 'file' && is_array( $_FILES[$db_edit_pols[$i]] ) )
        {
          $file   = $_FILES[$db_edit_pols[$i]];
          if ( $file['name'] )
            $name   = explode( '.' , $file['name'] );
          if ( isset( $name ) && is_array( $name ) )
            $patch  = '../' . \System::formGet( 'image_folder' ) . md5( time() ). '.' . strtolower( $name[count( $name ) - 1] );

          if ( $file['type'] == 'image/pjpeg' || $file['type'] == 'image/jpg' || $file['type'] == 'image/jpeg' || $file['type'] == 'image/gif' || $file['type'] == 'image/png' )
          {
            if ( $file['size'] < 5000000 )
            {
              $x = getimagesize( $file['tmp_name'] );
              if ( is_array( $x ) or $x[0] < 2)
              {
                $query = $db -> prepare( "SELECT " . $db_edit_pols[$i] . " FROM " . $db_edit_table . " WHERE " . $db_edit_key . "='" . $db_edit_val . "'" );
                $query -> execute();
                if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
                {
                  if ( file_exists( '../' . $row[0] ) )
                    unlink( '../' . $row[0] );
                }
                $query -> closeCursor();

                if ( file_exists( $patch ) )
                  unlink( $patch );
                
                rename( $file['tmp_name'] , $patch );
                chmod( $patch , 0755 );
                $patch = str_replace( '../' , '' , $patch );
                $query = $db -> query( "UPDATE " . $db_edit_table . " SET " . $db_edit_pols[$i] ."='" . $patch . "' WHERE " . $db_edit_key . "='" . $db_edit_val . "'" );
              }
            }
          }
        }
      }
      \System::setAlert( $lang -> getTrans( 'T_ZAKTUALIZOWANO_ELEMENT' ) );
    }
    $saveFlag = true;
    \System::deleteCacheAdmin();
    \System::deleteCache();
  }

  public static function addData( $db_edit_table , $db_edit_pols , $db_edit_pols_hidden , $db_edit_pols_t , $time , $db_edit_pass = '' )
  {
    global $lang , $db;

    $flag   = true;
    $idk    = '';
    $key    = '';
    $val    = '';
    $value  = '';

    if ( $time == \System::getSessionVar( 'dbedit_add_time' ) ) return false;

    if ( is_array( $db_edit_pols ) ) foreach ( $db_edit_pols as $val )
    {
      if ( !$idk )
        $idk = $val;
      if ( $key )
        $key .= ',';
      if ( $value )
        $value .= ',';
      $key .= $val;
      $value .= "'" . \System::saveString( \System::formGet( $val ) ) . "'";
    }

    if ( is_array( $db_edit_pols_hidden ) ) foreach ( $db_edit_pols_hidden as $val )
    {
      if ( $key )
        $key .= ',';
      if ( $value )
        $value .= ',';
      $key .= $val;
      $value .= "'" . \System::saveString( \System::formGet( $val ) ) . "'";
    }

    if ( $db_edit_pass )
    {
      $name   = $db_edit_pass['nazwa1'];
      $pass1  = \System::saveString( \System::formGet( $name ) );
      $pass2  = \System::saveString( \System::formGet( $name . '_repeat' ) );
      if ( $pass1 != $pass2 )
      {
        \System::setAlert( $lang -> getTrans( 'T_HASLA_ROZNE' ) );
        $flag = false;
      }
      else
      {
        if ( strlen($pass1) >= 5 )
        {
          if ( $key )
            $key .= ',';
          $key .= $name;
          if ( $value )
            $value .= ',';
          $value .= "'" . md5( $pass1 ) . "'";
        }
        else
        {
          if ( $pass1 )
          {
            $flag = false;
            \System::setAlert( $lang -> getTrans( 'T_HASLA_ZA_KROTKIE' ) );
          }
        }
      }
    }

    if ( $db_edit_table && $db_edit_pols && $flag )
    {
    $check = true;
    $db_edit_table  = \System::saveString( $db_edit_table );
    try
    {
      $query = $db -> prepare( "INSERT INTO " . $db_edit_table . " (" . $key . ") VALUES (" . $value . ")");
      $query -> execute();
    }
    catch(PDOException $e)
    {
      $check = false;
    }

    $id = $db -> lastInsertId();
    $query -> closeCursor();

    for ( $i = 0; $i < count( $db_edit_pols_t ); $i++ )
    {
      if ( $db_edit_pols_t[$i] == 'file' && is_array($_FILES[$db_edit_pols[$i]]) )
      {
        $file   = $_FILES[$db_edit_pols[$i]];
        $name   = explode( '.' , $file['name'] );
        $patch  = '../' . \System::formGet( 'image_folder' ) . md5( time() ). '.' . strtolower( $name[count( $name ) - 1] );

        if ( $file['type'] == 'image/pjpeg' || $file['type'] == 'image/jpg' || $file['type'] == 'image/jpeg' || $file['type'] == 'image/gif' || $file['type'] == 'image/png' )
        {
          if ( $file['size'] < 5000000 )
          {
            if ( !is_dir( '../' . \System::formGet( 'image_folder' ) ) ) mkdir( '../' . \System::formGet( 'image_folder' ), 0775, true);
            $x = getimagesize( $file['tmp_name'] );
            if ( is_array( $x ) or $x[0] < 2)
            {
              if ( file_exists( $patch ) )
                unlink( $patch );

              @rename( $file['tmp_name'] , $patch );
              chmod( $patch , 0755 );
              $patch = str_replace( '../' , '' , $patch );

              $query = $db -> prepare( "UPDATE " . $db_edit_table . " SET " . $db_edit_pols[$i] . "='" . $patch . "' WHERE id='" . $id . "'" );
              $query -> execute();
              $query -> closeCursor();
            }
          }
        }
      }
    }
    if ( $check )
      \System::setAlert( 'Nowy element został dodany.' );
    else
      \System::setAlert( 'Podane dane są nieprawidłowe.' );
    $addFlag = true;
    }
    else
      \System::setAlert( 'Podane dane są nieprawidłowe.' );

    \System::setSessionVar( 'dbedit_add_time' , $time );
    \System::deleteCacheAdmin();
    \System::deleteCache();
  }
}
?>