<?php
namespace admin\factory;
class Backups
{
  public static function backups_list()
  {
    if ( $handle = opendir( '../backups' ) )
    {
      while ( false !== ( $file = readdir( $handle ) ) )
      {
        if ( $file != "." && $file != ".." )
        {
          $row['name'] = $file;
          $dir[] = $row;
        }
      }
      closedir( $handle );
    }
    return $dir;
  }

  public static function backup_save()
  {
    global $mdb, $database;

    $dbhost = $database['host'];
    $dbuser = $database['user'];
    $dbpsw  = $database['password'];
    $dbname = $database['name'];

    $connection = mysqli_connect( $dbhost, $dbuser, $dbpsw, $dbname );
    mysqli_set_charset( $connection, 'utf8' );
    
    if ( !file_exists( '../backups' ) )
      mkdir( "../backups", 0755 );
    
    $backupfile = date( "Y_m_d_H_i_s" );
    include('../libraries/MySQLDump.php');
    $dump = new \MySQLDump( $connection );
    $dump -> save( '../backups/' . $backupfile . '.sql' );

    $zipTo  = '../backups/' . $backupfile . '.zip';
    $zip    = new \ZipArchive();
    $zip -> open( $zipTo, \ZipArchive::CREATE );
    $folder = '../';
    $iter   = new \RecursiveIteratorIterator(
                new \RecursiveDirectoryIterator( $folder, \RecursiveDirectoryIterator::SKIP_DOTS ),
                \RecursiveIteratorIterator::SELF_FIRST,
                \RecursiveIteratorIterator::CATCH_GET_CHILD 
              );
    
    foreach ( $iter as $file )
    {
      if ( !strstr( $file, '../backups' ) and !strstr( $file, ' ../temp' ) and !strstr( $file, '../updates' ) )
      {
        if ( is_dir( $file ) )
        {
          $zip -> addEmptyDir( str_replace( $folder, '', $file . '/' ) );
        }
        else if ( is_file( $file ) )
        {
          $zip -> addFromString( str_replace( $folder, '', $file ),
                  file_get_contents( $file ) );
        }
      }
    }
    $zip -> close();
    return true;
  }

  public static function backup_delete( $file )
  {
    if ( file_exists( '../backups/' . $file ) )
      unlink( '../backups/' . $file );
    return true;
  }
}