<?php
/**
 * IMPORTANT NOTE
 * The code of this system is closed and a private proprietary of Flex Solutions.
 * A written authorization/license from Flex Solutions is required before using or modifying this code.
 * Email: sales@flexsolution.biz, Phone: +962795342585, Website: http://www.flexsolutions.biz
 */
 

class BackupDataBase
{


    public $tables = array();
    public $fp;
    public $file_name;
    public $path = null;
    public $back_temp_file = 'db_backup_';

    public function getColumns($tableName)
    {
        $sql = 'SHOW CREATE TABLE ' . $tableName;
        $cmd = Yii::app()->db->createCommand($sql);
        $table = $cmd->queryRow();

        $create_query = $table['Create Table'] . ';';

        $create_query = preg_replace('/^CREATE TABLE/', 'CREATE TABLE IF NOT EXISTS', $create_query);
        //$create_query = preg_replace('/AUTO_INCREMENT\s*=\s*([0-9])+/', '', $create_query);
        if ($this->fp)
        {
            $this->writeComment('TABLE ' . addslashes($tableName));
            $final = 'DROP TABLE IF EXISTS ' . addslashes($tableName) . ';' . PHP_EOL . $create_query . PHP_EOL . PHP_EOL;
            fwrite($this->fp, $final);
        }
        else
        {
            $this->tables[$tableName]['create'] = $create_query;
            return $create_query;
        }
    }

    public function getData($tableName, $from_date=null, $to_date=null)
    {
        if (($from_date != null) && ($to_date != null) && ($tableName == 'ticket'))
        {
            $sql = 'SELECT * FROM ' . $tableName . ' WHERE date_time BETWEEN "' . $from_date . '" AND "' . $to_date . '"';
        }
        else
        {
            $sql = 'SELECT * FROM ' . $tableName;
        }
        $cmd = Yii::app()->db->createCommand($sql);
        $dataReader = $cmd->query();

        $data_string = '';


        $values = "";
        $data = "";
        $row_number = 1;
        $rows = array();
        foreach ($dataReader as $data)
        {
            $itemNames = array_keys($data);
            $itemNames = array_map("addslashes", $itemNames);
            $items = join('`,`', $itemNames);
            $itemValues = array_values($data);
            $itemValues = array_map("addslashes", $itemValues);
            $valueString = join("','", $itemValues);

            $valueString = str_replace("''", 'NULL',$valueString);
            $valueString = "('" . $valueString . "'),";
            $values = $values . "\n" . $valueString;
            if ($row_number % 600 == 0)
            {
                if ($values != "")
                {
                    $data_string = "INSERT INTO `$tableName` (`$items`) VALUES" . rtrim($values, ",") . ";" . PHP_EOL;
                    array_push($rows, $data_string);
                    $data_string = '';
                    $values = "";
                }
            }
            $row_number++;
        }
        if ($values != "")
        {
            $data_string = "INSERT INTO `$tableName` (`$items`) VALUES" . rtrim($values, ",") . ";" . PHP_EOL;
            array_push($rows, $data_string);
        }

        if (count($rows) == 0)
            return null;

        if ($this->fp)
        {
            $this->writeComment('TABLE DATA ' . $tableName);
            foreach ($rows as $row_data)
            {
                $final = $row_data . PHP_EOL . PHP_EOL . PHP_EOL;
                fwrite($this->fp, $final);
            }
        }
        else
        {
            $this->tables[$tableName]['data'] = $data_string;
            return $data_string;
        }
    }

    public function getTables($dbName = null)
    {
        $sql = 'SHOW TABLES';
        $cmd = Yii::app()->db->createCommand($sql);
        $tables = $cmd->queryColumn();
        return $tables;
    }

    public function StartBackup($addcheck = true, $type='')
    {

//        $this->file_name = $this->path . $this->back_temp_file . date('Y.m.d_H.i.s') . $type . '.sql';
        $this->file_name = $this->path . date('Y.m.d_H.i.s') . $type . '.sql';

        $this->fp = fopen($this->file_name, 'w+');

        if ($this->fp == null)
            return false;
        fwrite($this->fp, '-- -------------------------------------------' . PHP_EOL);
        if ($addcheck)
        {
            fwrite($this->fp, 'SET AUTOCOMMIT=0;' . PHP_EOL);
            fwrite($this->fp, 'START TRANSACTION;' . PHP_EOL);
            fwrite($this->fp, 'SET SQL_QUOTE_SHOW_CREATE = 1;' . PHP_EOL);
        }
        fwrite($this->fp, 'SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;' . PHP_EOL);
        fwrite($this->fp, 'SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;' . PHP_EOL);
        fwrite($this->fp, '-- -------------------------------------------' . PHP_EOL);
        $this->writeComment('START BACKUP');
        return true;
    }

    public function EndBackup($addcheck = true)
    {
        fwrite($this->fp, '-- -------------------------------------------' . PHP_EOL);
        fwrite($this->fp, 'SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;' . PHP_EOL);
        fwrite($this->fp, 'SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;' . PHP_EOL);

        if ($addcheck)
        {
            fwrite($this->fp, 'COMMIT;' . PHP_EOL);
        }
        fwrite($this->fp, '-- -------------------------------------------' . PHP_EOL);
        $this->writeComment('END BACKUP');
        fclose($this->fp);
        $this->fp = null;
    }

    public function writeComment($string)
    {
        fwrite($this->fp, '-- -------------------------------------------' . PHP_EOL);
        fwrite($this->fp, '-- ' . $string . PHP_EOL);
        fwrite($this->fp, '-- -------------------------------------------' . PHP_EOL);
    }

    public function fullBackup($conatin_structure=false, $conatin_data=false)
    {
        $tables = $this->getTables();

        if ($this->StartBackup(true, '__FullBackup'))
        {
            if ($conatin_structure)
            {
                foreach ($tables as $tableName)
                {
                    if (substr($tableName, 0, 2) != "v_")
                        $this->getColumns($tableName);
                }
            }
            if ($conatin_data)
            {
                foreach ($tables as $tableName)
                {
                    if (substr($tableName, 0, 2) != "v_")
                        $this->getData($tableName);
                }
            }
            $this->EndBackup();
        }
    }

    public function partialBackup($conatin_structure=false, $conatin_data=false, $from_date=null, $to_date=null, $type='')
    {
        $tables = $this->getTables();

        if ($this->StartBackup(true, '_' . $type))
        {
            if ($conatin_structure)
            {
                foreach ($tables as $tableName)
                {
                    if (substr($tableName, 0, 2) != "v_")
                        $this->getColumns($tableName);
                }
            }
            if ($conatin_data)
            {
                foreach ($tables as $tableName)
                {
                    if (substr($tableName, 0, 2) != "v_")
                        $this->getData($tableName, $from_date, $to_date);
                }
            }
            $this->EndBackup();
        }
    }

}