<?php
require_once("dbconn.php");
/*
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "caregiver";
$conn = new mysqli($servername, $username, $password, $dbname);
*/
if ($conn->connect_error) {
	WriteLog("Connection failed: " . $conn->connect_error);
    die("Connection failed: " . $conn->connect_error);
	
}
$currdate="tbl_start_report_";
$table=$currdate.date('Ymd');
$sql = "CREATE TABLE  $table  LIKE tbl_start_report";
if ($conn->query($sql) === TRUE) {
	WriteLog("New Table '".$table."' is Created Successfully.....!<br>");
	$sql2 = "INSERT INTO $table (SELECT * FROM tbl_start_report WHERE add_date <= NOW() - INTERVAL 30 DAY)";

if ($conn->query($sql2) === TRUE) {
	WriteLog(" Record Inserted Successfully in table '".$table."'...! <br>");
	$sql3="DELETE FROM tbl_start_report WHERE add_date <= NOW() - INTERVAL 30 DAY";
	if ($conn->query($sql3) === TRUE){
		 WriteLog("Record Deleted Successfully from tbl_start_report...!<br>");
	}else{
		 WriteLog("Error: " . $sql3 . "<br>" . $conn->error ."<br>");
	}
} else {
    WriteLog ("Error: " . $sql2 . "<br>" . $conn->error ."<br>");
}
} else {
    WriteLog ("Error:". $sql . "<br>" . $conn->error  ."<br>");
}

function WriteLog($string) {
		$myFile = "Data_log".date('Y-m-d').".txt";
		$fh = fopen($myFile, 'a') or die("can't open file");
		$current = date('Y-m-d H:i:s');
		$stringData = "[$current] : $string\r\n\r\n";
		fwrite($fh, $stringData);
		fclose($fh);		
	}
$conn->close();
?>