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

class Sistema extends Admin_Controller
{
    function __construct() 
    {
        parent::__construct();
    }
    
    public function teste()
    {
        var_dump(dirname(dirname(__FILE__,4)));
    }
    
    /*public function teste()
    {
        $this->load->library('phpsass/SassParser');
        $sass = new SassParser();
        
        $res = $this->db->where('id_user','1')->get('blg_tema')->row();
        
        unset($res->id);
        unset($res->id_user);
        
        $theme = file_get_contents(base_url('themes/blog/css/theme_default.scss'));
        
        $bg_op = array('menu_b','body_b','footer_b');
        
        foreach($res as $key=>$value)
        {
            if(substr($key,0,3) !== 'op_') 
            {
                if(!empty($value))
                {
                    if(in_array($key,$bg_op))
                    {
                        $op = 'op_'.$key;
                        if($res->$op == 2)
                        {
                            $value = 'url(backgrounds/'.$value.')';
                        }
                    }
                    $theme = str_replace('$'.$key,$value,$theme);
                }
                else 
                {
                  
                }
            }
        }
        
        $css = $sass->toCss(trim($theme)); 
        
        $path = 'assets/teste';
        
        file_put_contents($path.'.css',$css);
        file_put_contents($path.'.scss',$css);
    }*/
    
    public function clear($clear = null)
    {
        switch ($clear) {
            case 'cache':
                Assets::clear_cache();
                $files = glob(APPPATH.'cache/*'); // get all file names
                foreach($files as $file){ // iterate files
                  if(is_file($file))
                    unlink($file); // delete file
                }
                e('no more cache ;)');
            break;
            case 'session':
                $this->session->sess_destroy();
                e('no more session ;)');
            break;
            default:
                e('comando inválido :(');
            break;
        }
    }
    
    public function backup($type = null, $op = null)
    {
        switch ($type) {
            case 'full':
                $this->full_backup();
            break;
            case 'database':
                $this->db_backup($op);
            break;
            case 'application':
                $this->app_backup($op);
            break;
            default:
                e('comando inválido :(');
            break;
        }
    }
    
    private function full_backup()
    {
        echo $this->generate_db_bk(false,true);
        $this->generate_app_bk(false,true);
        
    }
    
    private function db_backup($op = null)
    {
        switch ($op) {
            case 'full':
                $return = $this->generate_db_bk(true,true);
                e($return);
            break;
            case 'download':
                $return = $this->generate_db_bk(true,false);
            break;
            case 'file':
                $return = $this->generate_db_bk(false,true);
                e($return);
            break;
            default:
                e('comando inválido :(');
            break;
        }
    }
        
    private function app_backup($op = null)
    {
        switch ($op) {
            case 'full':
                $return = $this->generate_app_bk(true,true);
                e($return);
            break;
            case 'download':
                $return = $this->generate_app_bk(true,false);
            break;
            case 'file':
                $return = $this->generate_app_bk(false,true);
                e($return);
            break;
            default:
                e('comando inválido :(');
            break;
        }
    }
    
    private function generate_db_bk($down,$file)
    {
        // Load the DB utility class
        $this->load->dbutil();
        
        // Backup your entire database and assign it to a variable
        $backup = $this->dbutil->backup();
        
        if($file === true)
        {
            // Load the file helper and write the file to your server
            $this->load->helper('file');
            //$res = write_file('../backup/database/db-'.date('Y-m-d-H-i-s').'.gz', $backup);
            $res = write_file('/home/vbqiclub/backup/database_'.date('Y_m_d').'.gz', $backup);
            
        }
        if($down === true)
        {
            // Load the download helper and send the file to your desktop
            $this->load->helper('download');
            force_download('db-'.date('Y-m-d-H-i-s').'.gz', $backup); 
        }
        if(isset($res)) return ($res == 1) ? 'Backup gerado com Sucesso!' : 'Erro ao gerar backup :(';
    }
    
    private function generate_app_bk($down,$file)
    {
        $path = '/home/vbqiclub/backup/application_'.date('Y_m_d').'.zip';

        /*$teste = shell_exec('sudo -u vbqiclub mkdir '.$path);
        
        var_dump($teste);break;*/
        
        //$output = shell_exec('zip -r /var/www/application/logs/app.zip /var/www/');
        //$output = shell_exec('zip -r /home/vbqiclub/backup/application.zip /var/www/');
        $output = shell_exec('zip -r '.$path.' /var/www/');
        echo "<pre>$output</pre>";
        
        /*$this->load->helper('directory');
        
        $map = directory_map('/var/www/application', FALSE, TRUE);
        
        var_dump($map);*/ exit();
        
        $this->load->library('zip');
        $this->zip->compression_level = 9;
        
        $paths = array(
            array('path'=>'/var/www/','dir'=>'application/'),
            /*array('path'=>'/var/www/','dir'=>'builder/'),
            array('path'=>'/var/www/','dir'=>'html/'),
            array('path'=>'/var/www/','dir'=>'system/')*/
        );
        
        foreach($paths as $path)
        {
            $this->zip->add_dir($path['dir']);
            $this->get_files_from_folder(implode("",$path), $path['dir']);
        }
        
        if($file === true)
        {
            // Load the file helper and write the file to your server
            $this->load->helper('file');
            $res = $this->zip->archive('../backup/application/app-'.date('Y-m-d-H-i-s').'.zip');
        }
        if($down === true)
        {
            $this->zip->download('my_backup.zip');
        }
        if(isset($res)) return ($res == 1) ? 'Backup da Aplicação gerado com Sucesso!' : 'Erro ao gerar backup da aplicação :(';
    }
    
    /*public function teste()
    {
        //chmod("../system/backup/database/db-2017-02-24-00-55-36.gz",0755);
        // Load the file helper and write the file to your server
        $this->load->helper('file');
        delete_files('../backup/database/');
    }*/
    
    function get_files_from_folder($directory, $put_into) 
    {
        if ($handle = opendir($directory)) 
        {
            while (false !== ($file = readdir($handle))) 
            {
                if (is_file($directory.$file)) 
                {
                    $fileContents = file_get_contents($directory.$file);
                    $this->zip->add_data($put_into.$file, $fileContents);
                } 
                elseif ($file != '.' and $file != '..' and is_dir($directory.$file)) 
                {
                    $this->zip->add_dir($put_into.$file.'/');
                    $this->get_files_from_folder($directory.$file.'/', $put_into.$file.'/');
                }
            }//end while
        }//end if
        closedir($handle);
    }
    
    /*public function app_backup()
    {
        $this->load->library('zip');
        $this->zip->compression_level = 9;
        
        $paths = array(
            array('path'=>'/var/www/','dir'=>'application/'),
            array('path'=>APPPATH,'dir'=>'logs/')
        );
        
        foreach($paths as $path)
        {
            $this->zip->add_dir($path['dir']);
            $this->get_files_from_folder(implode("",$path), $path['dir']);
        }
        
        // $this->zip->download('my_backup.zip');
    }*/

}