<?php 
defined('BASEPATH') OR exit('No direct script access allowed');

/*the class creates a .sql file in Export_Database function and a zip archive of the all file in the system(create_zip function).
stores the in  backups folder and send email with attachment*/
class System_backup extends CI_Controller {

	//ENTER THE RELEVANT INFO BELOW
    private $mysqlUserName      = "saccoadmin";
    private $mysqlPassword      = "24042015Ken";
    private $mysqlHostName      = "localhost";
    private $DbName             = "saccoManager";
	private $backup_name        = "mybackup.sql";
    //private $backup_name        = date("j-M-Y-H:i").".sql";
    //private $tables             = "Your tables";
	private $document_root;		
	
	
	function __construct()
	{
		parent:: __construct();
		$this->load->library('email');
		date_default_timezone_set("Africa/Nairobi");
		$this->document_root = $_SERVER['DOCUMENT_ROOT'];
	}

	

   //or add 5th parameter(array) of specific tables:    array("mytable1","mytable2","mytable3") for multiple tables
	
	function index()
	{
		$current_time = time();
		//$this->Export_Database($this->mysqlHostName,$this->mysqlUserName,$this->mysqlPassword,$this->DbName, $current_time, $tables=false, $backup_name=false );
		$this->create_zip($current_time);
		
	}
    

    function Export_Database($host,$user,$pass,$name, $current_time, $tables=false, $backup_name=false )
    {
        $mysqli = new mysqli($host,$user,$pass,$name); 
        $mysqli->select_db($name); 
        $mysqli->query("SET NAMES 'utf8'");

        $queryTables    = $mysqli->query('SHOW TABLES'); 
        while($row = $queryTables->fetch_row()) 
        { 
            $target_tables[] = $row[0]; 
        }   
        if($tables !== false) 
        { 
            $target_tables = array_intersect( $target_tables, $tables); 
        }
        foreach($target_tables as $table)
        {
            $result         =   $mysqli->query('SELECT * FROM '.$table);  
            $fields_amount  =   $result->field_count;  
            $rows_num=$mysqli->affected_rows;     
            $res            =   $mysqli->query('SHOW CREATE TABLE '.$table); 
            $TableMLine     =   $res->fetch_row();
            $content        = (!isset($content) ?  '' : $content) . "\n\n".$TableMLine[1].";\n\n";

            for ($i = 0, $st_counter = 0; $i < $fields_amount;   $i++, $st_counter=0) 
            {
                while($row = $result->fetch_row())  
                { //when started (and every after 100 command cycle):
                    if ($st_counter%100 == 0 || $st_counter == 0 )  
                    {
                            $content .= "\nINSERT INTO ".$table." VALUES";
                    }
                    $content .= "\n(";
                    for($j=0; $j<$fields_amount; $j++)  
                    { 
                        $row[$j] = str_replace("\n","\\n", addslashes($row[$j]) ); 
                        if (isset($row[$j]))
                        {
                            $content .= '"'.$row[$j].'"' ; 
                        }
                        else 
                        {   
                            $content .= '""';
                        }     
                        if ($j<($fields_amount-1))
                        {
                                $content.= ',';
                        }      
                    }
                    $content .=")";
                    //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
                    if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) 
                    {   
                        $content .= ";";
                    } 
                    else 
                    {
                        $content .= ",";
                    } 
                    $st_counter=$st_counter+1;
                }
            } $content .="\n\n\n";
        }
        $backup_name = $backup_name ? $backup_name : $name."_".date('d-M-Y',$current_time)."_".date('H-i-s',$current_time).".sql";
        $backup_name = $backup_name ? $backup_name : $name.".sql";		
		
		$repository = $this->document_root."/documents/backups/database/";
		$fp = fopen($repository.$backup_name,"w+");
		fwrite($fp,$content);
		fclose($fp);
		
		$time = date('d-M-Y H-i-s',$current_time);
		$file_path = $repository.$backup_name;
		$this->send_database_backup_email($time,$file_path);
		
		//Setting header to send the file to the browser
        /*header('Content-Type: application/octet-stream');   
        header("Content-Transfer-Encoding: Binary"); 
        header("Content-disposition: attachment; filename=\"".$backup_name."\"");
		echo $content; exit;*/
    }
	
	function send_database_backup_email($time,$file_path)
	{	
		$to = 'thomasnjoroge10@gmail.com';	
		$emailBody = "
Dear SaccoManager.com Admin,

Attached is .sql file for regular database backups at $time.

Kind regards,
SaccoManager.com
		
		";
		
		$this->email->from('admin@saccomanager.com', 'SaccoManager Admin');
		$this->email->reply_to('admin@sacccomanager.com', 'SaccoManager Admin');
		$this->email->to($to); 
		
		$this->email->subject("SaccoManager Database Backup at $time");
		$this->email->message($emailBody);
		$this->email->attach($file_path);
		
		$this->email->send();
		
		//echo $this->email->print_debugger();
	}
	
	//zip all files in the system
	function create_zip($time)
	{
		// Get real path for our folder
		$rootPath = realpath($this->document_root);
		$zip_file = $this->document_root."/documents/backups/files/SaccoManager"."_".date('d-M-Y',$time)."_".date('H-i-s',$time).".zip";
		
		// Initialize archive object
		$zip = new ZipArchive();
		$zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE);
		
		// Create recursive directory iterator
		/** @var SplFileInfo[] $files */
		$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootPath),RecursiveIteratorIterator::LEAVES_ONLY);
		
		foreach ($files as $name => $file)
		{
			// Skip directories (they would be added automatically)
			if (!$file->isDir())
			{
				// Get real and relative path for current file
				$filePath = $file->getRealPath();
				$relativePath = substr($filePath, strlen($rootPath) + 1);
		
				// Add current file to archive
				$zip->addFile($filePath, $relativePath);
			}
		}
		
		// Zip archive will be created only after closing object
		$zip->close();
	}
}
?>