<?php
/**
 * Created by PhpStorm.
 * User: neosoft
 * Date: 22/11/14
 * Time: 10:53 AM
 */

class Cron extends CI_Controller
{

    /**
     * Function index
     * default functionality for the user.
     * Controllers default method.
     *
     * @author    Himanshu Charegaonkar
     * @access    public
     */
    public function index()
    {
        $this->load->view('welcome_message');
    }

    public function fnSendEmail()
    {
        $this->load->model('subscribers');
        $arrSubscriptionDetails = $this->subscribers->fnCronToGetExpireMagazines();
        
    }

    // Back up Start Function
    public function BackupDB()
    {
        $folder_name = date("Y-m-d-H-i-s");
        $this->CreateFolder($folder_name);

        $this->load->dbutil();

        $prefs = array(     
            'format'      => 'zip',
            'filename'    => 'db_backup.sql'
        );
        
        $backup =& $this->dbutil->backup($prefs); 

        $db_zip_file = 'db-'. $folder_name .'.zip';
        $save_db_zip = './uploads/backups/'.$folder_name.'/'.$db_zip_file;
        
        $this->load->helper('file');
        write_file($save_db_zip, $backup);
        
        $this->CreateZip_Application_dir($folder_name);
        $this->SendEmail_Backup($folder_name);

    } // /BackupDB

    public function CreateFolder($folder_name = null)
    {
        if(!empty($folder_name)) {
            if (!is_dir('./uploads/backups/'.$folder_name)) {
                if(mkdir('./uploads/backups/' . $folder_name, 0777, TRUE)) {
                    return $folder_name;
                }else {
                    return FALSE;
                }
            }else {
                return FALSE;
            }
        }
    } // /CreateFolder


    public function CreateZip_Application_dir($folder_name)
    {
        $this->load->library('zip');
        // Add file to zip
        $this->zip->read_dir($_SERVER['DOCUMENT_ROOT'].'/magazine/application/');
        // save zip file on server
        $this->zip->archive($_SERVER['DOCUMENT_ROOT'].'/magazine/uploads/backups/'.$folder_name.'/application.zip');
    } // /CreateZip_Application_dir


    public function SendEmail_Backup($folder_name)
    {
        $this->load->library('email');

        $this->email->from('server@nurturecraftmagazines.com', 'Back Up');
        $this->email->to('sambob316@gmail.com');
        $this->email->attach($_SERVER['DOCUMENT_ROOT'].'/magazine/uploads/backups/'.$folder_name.'/db-'.$folder_name.'.zip');
        $this->email->attach($_SERVER['DOCUMENT_ROOT'].'/magazine/uploads/backups/'.$folder_name.'/application.zip');
        $this->email->subject('Site Back up');
        $this->email->message('Please find the attachments..');

        $this->email->send();
    }// /SendEmail_Backup

}// /class