<?php
ini_set('display_errors', 1);


$connection = mysqli_connect("localhost","sajisurx_crm","r~xRn{^r2N&s","sajisurx_crm");


mysqli_query($connection,'SET CHARACTER SET utf8');
mysqli_query($connection,"SET SESSION collation_connection ='utf8_general_ci'");



// Table Name that you want
// to export in csv
$ShowTable = "events";
date_default_timezone_set('Asia/Dhaka');
$dayBookDate1=date('Y-m-d');
$dayBookDate2=date('Y-m-d', strtotime($dayBookDate1. ' + 60 days'));
$FileName_ev = "_event_list_export.csv";
$file = fopen($FileName_ev,"w");

$sqlSelectedLG = "select * from (SELECT v1.* , GROUP_CONCAT(v2.name ORDER BY v2.id) as vd_names FROM (SELECT p1.* , GROUP_CONCAT(p2.name ORDER BY p2.id) as ph_names FROM (select a1.* , a2.name as event_type from (SELECT t1.*, t2.name as client_name, t2.booking_id,t2.booking_name, t2.cell_1,t2.cell_2 FROM `events` as t1 left join bookings as t2 on t1.temp_id=t2.id order by t1.date) as a1 left join event_types as a2 on a1.type=a2.id) as p1 left join artists as p2 ON FIND_IN_SET(p2.id, p1.photographers) group by p1.id) as v1 left join artists as v2 ON FIND_IN_SET(v2.id, v1.videographers) group by v1.id ORDER BY TIMESTAMP(v1.date,v1.time) ) as evtbl where booking_id!=0 AND (date BETWEEN '$dayBookDate1' AND '$dayBookDate2' )";

$sql = mysqli_query($connection, $sqlSelectedLG);

$row = mysqli_fetch_assoc($sql);
// Save headings alon
	$HeadingsArray=array();
	foreach($row as $name => $value){
		$HeadingsArray[]=$name;
	}
	fputcsv($file,$HeadingsArray); 
	
// Save all records without headings

	while($row = mysqli_fetch_assoc($sql)){
	$valuesArray=array();
		foreach($row as $name => $value){
		$valuesArray[]=$value;
		}
	fputcsv($file,$valuesArray); 
	}
	fclose($file);
echo "Complete Event Record saves as CSV in file: <b style=\"color:red;\">$FileName_ev</b>";



$dayBookDate2=date('Y-m-d');
$dayBookDate2=date('Y-m-d', strtotime($dayBookDate2. ' + 2 days'));


$dayBookDate1=date('Y-m-01', strtotime($dayBookDate1. ' - 1 years'));



$FileName_as = "_assignment_list_export.csv";
$file = fopen($FileName_as,"w");

$sqlSelectedLG = "select q1.*,q2.name as ph_editor_name,q3.name as vd_editor_name,q4.name as sp_editor_name from (select h1.* ,h2.editor as ph_editor,h2.sp_editor,h2.ph_sp_status, h2.date as ph_date, h2.hdd as ph_hdd, h2.rg_edit as ph_rg_edit, h2.sp_edit as ph_sp_edit, h2.remarks as ph_remarks, h2.status as ph_status,h3.editor as vd_editor, h3.date as vd_date, h3.hdd as vd_hdd, h3.remarks as vd_remarks, h3.status as vd_status from (SELECT v1.* , GROUP_CONCAT(v2.name ORDER BY v2.id) as vd_names FROM (SELECT p1.* , GROUP_CONCAT(p2.name ORDER BY p2.id) as ph_names FROM (select a1.* , a2.name as event_type from (SELECT t1.*, t2.name as client_name,t2.booking_name, t2.booking_id, t2.cell_1,t2.cell_2,t2.status as booking_status FROM `events` as t1 left join bookings as t2 on t1.temp_id=t2.id order by t1.date) as a1 left join event_types as a2 on a1.type=a2.id) as p1 left join artists as p2 ON FIND_IN_SET(p2.id, p1.photographers) group by p1.id) as v1 left join artists as v2 ON FIND_IN_SET(v2.id, v1.videographers) group by v1.id ORDER BY TIMESTAMP(v1.date,v1.time)) as h1 left join photo_edit as h2 on h1.id=h2.event_id left join vd_edit as h3 on h1.id=h3.event_id) as q1 left join users as q2 on q1.ph_editor=q2.id left join users as q3 on  q1.vd_editor=q3.id left join users as q4 on q1.sp_editor=q4.id where q1.booking_status=1 AND (q1.date BETWEEN '$dayBookDate1' AND '$dayBookDate2') order by q1.date DESC limit 200";

$sql = mysqli_query($connection, $sqlSelectedLG);

$row = mysqli_fetch_assoc($sql);
// Save headings alon
	$HeadingsArray=array();
	foreach($row as $name => $value){
		$HeadingsArray[]=$name;
	}
	fputcsv($file,$HeadingsArray); 
	
// Save all records without headings

	while($row = mysqli_fetch_assoc($sql)){
	$valuesArray=array();
		foreach($row as $name => $value){
		$valuesArray[]=$value;
		}
	fputcsv($file,$valuesArray); 
	}
	fclose($file);
echo "Complete Ass Record saves as CSV in file: <b style=\"color:red;\">$FileName_as</b>";


$dayBookDate2=date('Y-m-31');
$dayBookDate1=date('Y-m-01', strtotime($dayBookDate1. ' - 1 years'));

$FileName_bk = "_booking_list_export.csv";
$file = fopen($FileName_bk,"w");

$sqlSelectedLG = "select f1.* , f2.ev_total+IFNULL(f3.ev_total_later,0) ev_total,f2.ev_value,IFNULL(f3.added_later,0) added_later from (SELECT t1.id, t1.booking_id,t1.booking_name,t1.cell_1,t1.cell_2,t1.name,t1.approved_at,t1.added_at,t1.discount,t1.status, t2.paid FROM `bookings` as t1 LEFT JOIN (SELECT temp_booking_id, sum(amount) as paid FROM `transactions` GROUP BY temp_booking_id) as t2 on t1.id=t2.temp_booking_id) as f1 left join (SELECT temp_id, count(id) ev_total, sum(ev_value) ev_value FROM `events` where added_later='no' GROUP BY temp_id) as f2 on f1.id=f2.temp_id left join (SELECT temp_id, IFNULL(count(id),0) ev_total_later, sum(ev_value) added_later FROM `events` where added_later='yes' GROUP BY temp_id) as f3 on f1.id=f3.temp_id where f1.status=1 AND (date(approved_at) BETWEEN '$dayBookDate1' AND '$dayBookDate2' ) ";

$sql = mysqli_query($connection, $sqlSelectedLG);

$row = mysqli_fetch_assoc($sql);
// Save headings alon
	$HeadingsArray=array();
	foreach($row as $name => $value){
		$HeadingsArray[]=$name;
	}
	fputcsv($file,$HeadingsArray); 
	
// Save all records without headings

	while($row = mysqli_fetch_assoc($sql)){
	$valuesArray=array();
		foreach($row as $name => $value){
		$valuesArray[]=$value;
		}
	fputcsv($file,$valuesArray); 
	}
	fclose($file);
echo "Complete Booking Record saves as CSV in file: <b style=\"color:red;\">$FileName_bk</b>";



$dayBookDate2=date('Y-m-31');
$dayBookDate1=date('Y-m-01', strtotime($dayBookDate1. ' - 1 years'));

$FileName_py = "_payment_list_export.csv";
$file = fopen($FileName_py,"w");

$sqlSelectedLG = "select f1.* , f2.name from (SELECT t1.*,t2.booking_id FROM `transactions` as t1 left join bookings as t2 on t1.temp_booking_id=t2.id) as f1 left join users as f2 on f1.updated_by = f2.id  where f1.date BETWEEN '$dayBookDate1' AND '$dayBookDate2' order by f1.date desc";

$sql = mysqli_query($connection, $sqlSelectedLG);

$row = mysqli_fetch_assoc($sql);
// Save headings alon
	$HeadingsArray=array();
	foreach($row as $name => $value){
		$HeadingsArray[]=$name;
	}
	fputcsv($file,$HeadingsArray); 
	
// Save all records without headings

	while($row = mysqli_fetch_assoc($sql)){
	$valuesArray=array();
		foreach($row as $name => $value){
		$valuesArray[]=$value;
		}
	fputcsv($file,$valuesArray); 
	}
	fclose($file);
echo "Complete Booking Record saves as CSV in file: <b style=\"color:red;\">$FileName_py</b>";





/**
 * This file contains the Backup_Database class wich performs
 * a partial or complete backup of any given MySQL database
 * @author Daniel López Azaña <daniloaz@gmail.com>
 * @version 1.0
 */

/**
 * Define database parameters here
 */
define("DB_USER", 'sajisurx_crm');
define("DB_PASSWORD", 'r~xRn{^r2N&s');
define("DB_NAME", 'sajisurx_crm');
define("DB_HOST", 'localhost');
define("BACKUP_DIR", 'db_backup'); // Comment this line to use same script's directory ('.')
define("TABLES", '*'); // Full backup
//define("TABLES", 'table1, table2, table3'); // Partial backup
define("CHARSET", 'utf8');
define("GZIP_BACKUP_FILE", true); // Set to false if you want plain SQL backup files (not gzipped)
define("DISABLE_FOREIGN_KEY_CHECKS", true); // Set to true if you are having foreign key constraint fails
define("BATCH_SIZE", 1000); // Batch size when selecting rows from database in order to not exhaust system memory
                            // Also number of rows per INSERT statement in backup file

/**
 * The Backup_Database class
 */
class Backup_Database {
    /**
     * Host where the database is located
     */
    var $host;

    /**
     * Username used to connect to database
     */
    var $username;

    /**
     * Password used to connect to database
     */
    var $passwd;

    /**
     * Database to backup
     */
    var $dbName;

    /**
     * Database charset
     */
    var $charset;

    /**
     * Database connection
     */
    var $conn;

    /**
     * Backup directory where backup files are stored 
     */
    var $backupDir;

    /**
     * Output backup file
     */
    var $backupFile;

    /**
     * Use gzip compression on backup file
     */
    var $gzipBackupFile;

    /**
     * Content of standard output
     */
    var $output;

    /**
     * Disable foreign key checks
     */
    var $disableForeignKeyChecks;

    /**
     * Batch size, number of rows to process per iteration
     */
    var $batchSize;

    /**
     * Constructor initializes database
     */
    public function __construct($host, $username, $passwd, $dbName, $charset = 'utf8') {
        $this->host                    = $host;
        $this->username                = $username;
        $this->passwd                  = $passwd;
        $this->dbName                  = $dbName;
        $this->charset                 = $charset;
        $this->conn                    = $this->initializeDatabase();
        $this->backupDir               = BACKUP_DIR ? BACKUP_DIR : '.';
        $this->backupFile              = 'db-backup-'.date("Ymd", time()).'.sql';
        $this->gzipBackupFile          = defined('GZIP_BACKUP_FILE') ? GZIP_BACKUP_FILE : true;
        $this->disableForeignKeyChecks = defined('DISABLE_FOREIGN_KEY_CHECKS') ? DISABLE_FOREIGN_KEY_CHECKS : true;
        $this->batchSize               = defined('BATCH_SIZE') ? BATCH_SIZE : 1000; // default 1000 rows
        $this->output                  = '';
    }

    protected function initializeDatabase() {
        try {
            $conn = mysqli_connect($this->host, $this->username, $this->passwd, $this->dbName);
            if (mysqli_connect_errno()) {
                throw new Exception('ERROR connecting database: ' . mysqli_connect_error());
                die();
            }
            if (!mysqli_set_charset($conn, $this->charset)) {
                mysqli_query($conn, 'SET NAMES '.$this->charset);
            }
        } catch (Exception $e) {
            print_r($e->getMessage());
            die();
        }

        return $conn;
    }

    /**
     * Backup the whole database or just some tables
     * Use '*' for whole database or 'table1 table2 table3...'
     * @param string $tables
     */
    public function backupTables($tables = '*') {
        try {
            /**
             * Tables to export
             */
            if($tables == '*') {
                $tables = array();
                $result = mysqli_query($this->conn, 'SHOW TABLES');
                while($row = mysqli_fetch_row($result)) {
                    $tables[] = $row[0];
                }
            } else {
                $tables = is_array($tables) ? $tables : explode(',', str_replace(' ', '', $tables));
            }

            $sql = 'CREATE DATABASE IF NOT EXISTS `'.$this->dbName."`;\n\n";
            $sql .= 'USE `'.$this->dbName."`;\n\n";

            /**
             * Disable foreign key checks 
             */
            if ($this->disableForeignKeyChecks === true) {
                $sql .= "SET foreign_key_checks = 0;\n\n";
            }

            /**
             * Iterate tables
             */
            foreach($tables as $table) {
                $this->obfPrint("Backing up `".$table."` table...".str_repeat('.', 50-strlen($table)), 0, 0);

                /**
                 * CREATE TABLE
                 */
                $sql .= 'DROP TABLE IF EXISTS `'.$table.'`;';
                $row = mysqli_fetch_row(mysqli_query($this->conn, 'SHOW CREATE TABLE `'.$table.'`'));
                $sql .= "\n\n".$row[1].";\n\n";

                /**
                 * INSERT INTO
                 */

                $row = mysqli_fetch_row(mysqli_query($this->conn, 'SELECT COUNT(*) FROM `'.$table.'`'));
                $numRows = $row[0];

                // Split table in batches in order to not exhaust system memory 
                $numBatches = intval($numRows / $this->batchSize) + 1; // Number of while-loop calls to perform

                for ($b = 1; $b <= $numBatches; $b++) {
                    
                    $query = 'SELECT * FROM `' . $table . '` LIMIT ' . ($b * $this->batchSize - $this->batchSize) . ',' . $this->batchSize;
                    $result = mysqli_query($this->conn, $query);
                    $realBatchSize = mysqli_num_rows ($result); // Last batch size can be different from $this->batchSize
                    $numFields = mysqli_num_fields($result);

                    if ($realBatchSize !== 0) {
                        $sql .= 'INSERT INTO `'.$table.'` VALUES ';

                        for ($i = 0; $i < $numFields; $i++) {
                            $rowCount = 1;
                            while($row = mysqli_fetch_row($result)) {
                                $sql.='(';
                                for($j=0; $j<$numFields; $j++) {
                                    if (isset($row[$j])) {
                                        $row[$j] = addslashes($row[$j]);
                                        $row[$j] = str_replace("\n","\\n",$row[$j]);
                                        $row[$j] = str_replace("\r","\\r",$row[$j]);
                                        $row[$j] = str_replace("\f","\\f",$row[$j]);
                                        $row[$j] = str_replace("\t","\\t",$row[$j]);
                                        $row[$j] = str_replace("\v","\\v",$row[$j]);
                                        $row[$j] = str_replace("\a","\\a",$row[$j]);
                                        $row[$j] = str_replace("\b","\\b",$row[$j]);
                                        if ($row[$j] == 'true' or $row[$j] == 'false' or preg_match('/^-?[0-9]+$/', $row[$j]) or $row[$j] == 'NULL' or $row[$j] == 'null') {
                                            $sql .= $row[$j];
                                        } else {
                                            $sql .= '"'.$row[$j].'"' ;
                                        }
                                    } else {
                                        $sql.= 'NULL';
                                    }
    
                                    if ($j < ($numFields-1)) {
                                        $sql .= ',';
                                    }
                                }
    
                                if ($rowCount == $realBatchSize) {
                                    $rowCount = 0;
                                    $sql.= ");\n"; //close the insert statement
                                } else {
                                    $sql.= "),\n"; //close the row
                                }
    
                                $rowCount++;
                            }
                        }
    
                        $this->saveFile($sql);
                        $sql = '';
                    }
                }

                /**
                 * CREATE TRIGGER
                 */

                // Check if there are some TRIGGERS associated to the table
                /*$query = "SHOW TRIGGERS LIKE '" . $table . "%'";
                $result = mysqli_query ($this->conn, $query);
                if ($result) {
                    $triggers = array();
                    while ($trigger = mysqli_fetch_row ($result)) {
                        $triggers[] = $trigger[0];
                    }
                    
                    // Iterate through triggers of the table
                    foreach ( $triggers as $trigger ) {
                        $query= 'SHOW CREATE TRIGGER `' . $trigger . '`';
                        $result = mysqli_fetch_array (mysqli_query ($this->conn, $query));
                        $sql.= "\nDROP TRIGGER IF EXISTS `" . $trigger . "`;\n";
                        $sql.= "DELIMITER $$\n" . $result[2] . "$$\n\nDELIMITER ;\n";
                    }

                    $sql.= "\n";

                    $this->saveFile($sql);
                    $sql = '';
                }*/
 
                $sql.="\n\n";

                $this->obfPrint('OK');
            }

            /**
             * Re-enable foreign key checks 
             */
            if ($this->disableForeignKeyChecks === true) {
                $sql .= "SET foreign_key_checks = 1;\n";
            }

            $this->saveFile($sql);

            if ($this->gzipBackupFile) {
                $this->gzipBackupFile();
            } else {
                $this->obfPrint('Backup file succesfully saved to ' . $this->backupDir.'/'.$this->backupFile, 1, 1);
            }
        } catch (Exception $e) {
            print_r($e->getMessage());
            return false;
        }

        return true;
    }

    /**
     * Save SQL to file
     * @param string $sql
     */
    protected function saveFile(&$sql) {
        if (!$sql) return false;

        try {

            if (!file_exists($this->backupDir)) {
                mkdir($this->backupDir, 0777, true);
            }

            file_put_contents($this->backupDir.'/'.$this->backupFile, $sql, FILE_APPEND | LOCK_EX);

        } catch (Exception $e) {
            print_r($e->getMessage());
            return false;
        }

        return true;
    }

    /*
     * Gzip backup file
     *
     * @param integer $level GZIP compression level (default: 9)
     * @return string New filename (with .gz appended) if success, or false if operation fails
     */
    protected function gzipBackupFile($level = 9) {
        if (!$this->gzipBackupFile) {
            return true;
        }

        $source = $this->backupDir . '/' . $this->backupFile;
        $dest =  $source . '.gz';
        
        $this->obfPrint('Gzipping backup file to ' . $dest . '... ', 1, 0);
        $this->obfPrint('Download Now By Clicking <a href=' . $dest . '>  <b> *** DownLoad *** </b></a> ', 1, 0);
        $mode = 'wb' . $level;
        if ($fpOut = gzopen($dest, $mode)) {
            if ($fpIn = fopen($source,'rb')) {
                while (!feof($fpIn)) {
                    gzwrite($fpOut, fread($fpIn, 1024 * 256));
                }
                fclose($fpIn);
            } else {
                return false;
            }
            gzclose($fpOut);
            if(!unlink($source)) {
                return false;
            }
        } else {
            return false;
        }
        
        $this->obfPrint('OK');
        return $dest;
    }

    /**
     * Prints message forcing output buffer flush
     *
     */
    public function obfPrint ($msg = '', $lineBreaksBefore = 0, $lineBreaksAfter = 1) {
        if (!$msg) {
            return false;
        }

        if ($msg != 'OK' and $msg != 'KO') {
            $msg = date("Y-m-d H:i:s") . ' - ' . $msg;
        }
        $output = '';

        if (php_sapi_name() != "cli") {
            $lineBreak = "<br />";
        } else {
            $lineBreak = "\n";
        }

        if ($lineBreaksBefore > 0) {
            for ($i = 1; $i <= $lineBreaksBefore; $i++) {
                $output .= $lineBreak;
            }                
        }

        $output .= $msg;

        if ($lineBreaksAfter > 0) {
            for ($i = 1; $i <= $lineBreaksAfter; $i++) {
                $output .= $lineBreak;
            }                
        }


        // Save output for later use
        $this->output .= str_replace('<br />', '\n', $output);

        echo $output;


        if (php_sapi_name() != "cli") {
            if( ob_get_level() > 0 ) {
                ob_flush();
            }
        }

        $this->output .= " ";

        flush();
    }

    /**
     * Returns full execution output
     *
     */
    public function getOutput() {
        return $this->output;
    }
}

/**
 * Instantiate Backup_Database and perform backup
 */

// Report all errors
error_reporting(E_ALL);
// Set script max execution time
set_time_limit(900); // 15 minutes

if (php_sapi_name() != "cli") {
    echo '<div style="font-family: monospace;">';
}

$backupDatabase = new Backup_Database(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, CHARSET);
$result = $backupDatabase->backupTables(TABLES, BACKUP_DIR) ? 'OK' : 'KO';
$backupDatabase->obfPrint('Backup result: ' . $result, 1);

// Use $output variable for further processing, for example to send it by email
$output = $backupDatabase->getOutput();

if (php_sapi_name() != "cli") {
    echo '</div>';
}


?>