<?php

global $debugCode;
$debugCode = true;  // Activar debug
custom_error(1,"Se inicia el proceso del Backup de la BD"); // To debug

//   require_once("../include/dbcommon.php"); // DataBase PHPRunner

include __DIR__."/mysqldump-php_2.12/autoload.php";

use Ifsnop\Mysqldump as IMysqldump;

$host = $_SESSION['db_host'];
$user = $_SESSION['db_user'];
$pwd = $_SESSION['db_pwd'];
$port = $_SESSION['db_port'];
$sys_dbname = $_SESSION['db_sys_dbname'];

$now = date("Y-m-d H:i:s");  // Date by now
$specials = array(":", " ");
$now = str_replace($specials, "_", $now);

$dumpSettings = array(
    // 'exclude-tables' => array('/^travis*/'),
    // 'compress' => IMysqldump\Mysqldump::GZIP,
    'no-data' => false,
    'add-drop-table' => true,
    'single-transaction' => true,
    'lock-tables' => true,
    'add-locks' => true,
    'extended-insert' => false,
    'disable-keys' => true,
    'skip-triggers' => false,
    'add-drop-trigger' => true,
    'routines' => true,
    'databases' => false,
    'add-drop-database' => false,
    'hex-blob' => true,
    'no-create-info' => false,
    // 'where' => '',
    'default-character-set' => IMysqldump\Mysqldump::UTF8MB4,
    'complete-insert' => true
    );
$pref_file_backup = 'Project_';

$http_referer = $_SERVER['HTTP_REFERER'];
$http_referer_ar = explode('/',$http_referer);
// Ajustar a las características de tu URL | Adjust the characteristics of your URL
$file = $http_referer_ar[0].'//'.$http_referer_ar[2].'/'.$http_referer_ar[3].'/'.'/'.'backup/backup_files/'.$pref_file_backup.$now.'.sql';
// Ajustar a las características de tu URL | Adjust the characteristics of your URL

custom_error(2,"Antes de inciar el proceso del Backup de la BD"); // To debug
try {
    $dump = new IMysqldump\Mysqldump('mysql:host='.$host.';dbname='.$sys_dbname , $user, $pwd , $dumpSettings);
    custom_error(3,"Después de crear la conexión del Backup de la BD"); // To debug
    $dump->start(__DIR__.'/backup_files/'.$pref_file_backup.$now.'.sql');
    custom_error(4,"Después de hacer el Backup de la BD"); // To debug
} catch (\Exception $e) {
    echo 'mysqldump-php error: ' . $e->getMessage();
}

// Dejar sólo los 5 export de base de datos, más recientes.| Leave only the 5 recent database export.
$arrFiles = glob(__DIR__.'/backup_files/'.$pref_file_backup.'*');

rsort($arrFiles);  // Ordenar de mayor a menor

if (count($arrFiles) > 5 ) {
    for ($i = 5; $i < count($arrFiles); $i++) {
        unlink($arrFiles[$i]); // Delete ancient files
    }   
}
$debugCode = false;  // Desactivar debug
