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


class Backup extends CI_Controller
{


  function __construct()
  {
    parent::__construct();
    ini_set('max_execution_time', 10000);
    ini_set("memory_limit", "-1");
    
    $this->load->model('Settings_model', 'Settings');


  }

  /***default function, redirects to login page if no admin logged in yet***/
  public function index()
  {

  }
  public function download(){

    $smtp_settings = $this->Settings->select_settings('*',array("settings_category"=>"SMTP"))->result();
    foreach ($smtp_settings as $key => $value) {
      ${$value->settings_name} = $value->value;
    }

    $company_details = $this->Settings->select_settings('*',array("settings_category"=>"Company Details"))->result();
    foreach ($company_details as $key => $value) {
      ${$value->settings_name} = $value->value;
    }

    $file_name = str_replace(' ', '_', $company_name);

    // Load the DB utility class
    $this->load->dbutil();
    $prefs = array(
      'format'        => 'zip',                       // gzip, zip, txt
      'filename'      => $file_name.'_database.sql'             // File name - NEEDED ONLY WITH ZIP FILES
    );
    $backup = $this->dbutil->backup($prefs);
    $db_name = $file_name.'_db_backup-on-'. date("Y-m-d-H-i-s") .'.zip';
    //       Writ File to Server
    $this->load->helper('file');
    write_file(FCPATH.'/db_backup/'.$db_name, $backup);

    // Load the download helper and send the file to your desktop
    $this->load->helper('download');
    force_download($db_name, $backup);
  }
  public function save(){
    // Get Backup Email
    $url = "http://clients.genovatechnologies.com/login/get_backup_email";
    //  Initiate curl
    $ch = curl_init();
    // Will return the response, if false it print the response
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Set the url
    curl_setopt($ch, CURLOPT_URL,$url);
    // Execute
    $result=curl_exec($ch);
    // Closing
    curl_close($ch);
    // Will dump a beauty json :3
    $response = json_decode($result, true);
    if(isset($response) && isset($response['email']) && $response['email']!=''){
      $to = $response['email'];
    }else{
      $to = 'genovabackup@gmail.com';
    }

    $smtp_settings = $this->Settings->select_settings('*',array("settings_category"=>"SMTP"))->result();
    foreach ($smtp_settings as $key => $value) {
      ${$value->settings_name} = $value->value;
    }

    $company_details = $this->Settings->select_settings('*',array("settings_category"=>"Company Details"))->result();
    foreach ($company_details as $key => $value) {
      ${$value->settings_name} = $value->value;
    }
    $file_name = str_replace(' ', '_', $company_name);
    $file_name = preg_replace('/[^A-Za-z0-9\-]/', '', $file_name); // Removes special chars.
    $file_name =  preg_replace('/-+/', '_', $file_name); // Replaces multiple hyphens with single one.


    // Load the DB utility class
    $this->load->dbutil();
    $prefs = array(
      'format'        => 'zip',                       // gzip, zip, txt
      'filename'      => $file_name.'_database.sql'             // File name - NEEDED ONLY WITH ZIP FILES
    );
    $backup = $this->dbutil->backup($prefs);
    $db_name = $file_name.'_db_backup-on-'. date("Y-m-d-H-i-s") .'.zip';
    //       Writ File to Server
    $this->load->helper('file');
    $file_save_status = write_file(FCPATH.'/db_backup/'.$db_name, $backup);

    $subject = $company_name." Database Backup";


    if(isset($_POST['email'])){
      $to = $_POST['email'];
    }
    $message = "Database Backup on ".date("Y-m-d-H-i-s");

    $mail_sent_status = 0;
    $mail_error = "";

    $this->load->library('My_PHPMailer');
    $mail = new PHPMailer();
    $mail->IsSMTP(); // we are going to use SMTP
    $mail->SMTPAuth   = true; // enabled SMTP authentication
    $mail->SMTPSecure = "ssl";  // prefix for secure protocol to connect to the server
    $mail->Host       = $smtp_host;      // setting GMail as our SMTP server
    $mail->Port       = $smtp_port;                   // SMTP port to connect to GMail
    $mail->Username   = $smtp_username;  // user email address
    $mail->Password   = $smtp_password;            // password in GMail
    $mail->SetFrom($smtp_username, $company_name);  //Who is sending the email
    $mail->Subject = $subject;
    $mail->Body = $message;
    $mail->AltBody = "Plain text message";
    $mail->AddAttachment(FCPATH.'/db_backup/'.$db_name);
    $destino = $to; // Who is addressed the email to
    $mail->AddAddress($destino);
    if($mail->Send()){
      $mail_sent_status = 1;
    }else{
      $mail_error =  $mail->ErrorInfo;
    }
    $return_data = array();
    $return_data['file_save_status'] = $file_save_status;
    $return_data['mail_sent_status'] = $mail_sent_status;
    $return_data['mail_error'] = $mail_error;

    echo '[{"file_save_status":"'.$file_save_status.'","mail_sent_status":"'.$mail_sent_status.'","mail_error":"'.$mail_error.'"}]';
  }


  function delete_backups($days_to_keep){
    $path = './db_backup/';
    if ($handle = opendir($path)) {
      while (false !== ($file = readdir($handle))) {
        $filelastmodified = filemtime($path . $file);
        //24 hours in a day * 3600 seconds per hour
        if((time() - $filelastmodified) > $days_to_keep*24*3600 && is_file($path.$file))
        {
          unlink($path . $file);
        }

      }
      closedir($handle);
    }
  }
  public function delete_log_files($days_to_keep) {
    $path1 = 'application/logs/';
    if (is_dir($path1)) {
      if ($handle = opendir($path1)) {
        while (false !== ($file = readdir($handle))) {
          $filelastmodified = filemtime($path1 . $file);
          //24 hours in a day * 3600 seconds per hour
          if((time() - $filelastmodified) > $days_to_keep*24*3600 && is_file($path1.$file))
          {
            unlink($path1 . $file);
          }
        }
        closedir($handle);
      }
    }

    $path2 = 'application/ci_sessions/';
    if (is_dir($path2)) {
      if ($handle = opendir($path2)) {
        while (false !== ($file = readdir($handle))) {
          $filelastmodified = filemtime($path2 . $file);
          //24 hours in a day * 3600 seconds per hour
          if((time() - $filelastmodified) > $days_to_keep*24*3600 && is_file($path2.$file))
          {
            unlink($path2 . $file);
          }
        }
        closedir($handle);
      }
    }

    $path3 = 'system/cache/';
    if (is_dir($path3)) {
      if ($handle = opendir($path3)) {
        while (false !== ($file = readdir($handle))) {
          $filelastmodified = filemtime($path3 . $file);
          //24 hours in a day * 3600 seconds per hour
          if((time() - $filelastmodified) > $days_to_keep*24*3600 && is_file($path3.$file))
          {
            unlink($path3 . $file);
          }
        }
        closedir($handle);
      }
    }

    // Delete CI Session table Data
    $this->db->query('DELETE FROM ci_sessions  WHERE  timestamp < NOW() - INTERVAL 1 DAY');
    $this->db->query('OPTIMIZE TABLE ci_sessions');

    $this->db->query('DELETE FROM app_api_logs  WHERE  time < NOW() - INTERVAL 72 HOUR');

    foreach(glob('*.zip') as $file){
      echo "Zip File Exist - ".$file."<br/>";
    }
  }
  function delete_backups_logs($days_to_keep=2){
    $this->delete_backups($days_to_keep);
    $this->delete_log_files($days_to_keep);
  }
  function upload_folder_size ($dir = 'uploads/')
  {

  }

}
