<?php
//include 'dbconnection2.php';
include 'dbconnection.php';
// Perform queries
$Email = $_GET['Email']; 
$ComID =$_GET['ID'];
$tablanueva = 'messages'.$ComID;
$file= 'chat/'.$tablanueva.'.php';


$DB = mysqli_query($mysql,"SELECT dbname,Chat,Chatdir FROM tb_users WHERE email ='$Email'");
while($row = mysqli_fetch_array($DB)){
$dbname = $row ['dbname'];
$Chatdir = $row ['Chatdir'];
$Chat = $row['Chat'];
}


$hostname2 = "localhost";
$username2 = "tempdpe5_nicolas";
$password2= "(Made7575)";
$conn = mysqli_connect($hostname2,$username2,$password2,$dbname);
if (mysqli_connect_errno()){
  printf("Connect failed: %s\n", mysqli_connect_error());
  exit();
} 
mysqli_set_charset($conn ,"utf8");

mysqli_query($conn,"CREATE TABLE ".$tablanueva." LIKE messages");
mysqli_query($conn,"UPDATE comunicacion SET Chattabla ='$tablanueva',file ='$file' WHERE ComID ='$ComID'");
mysqli_query($conn,"UPDATE comunicacion SET file ='$file' WHERE ComID ='$ComID'");

$file = $Chatdir.'chatapp.php';
$newfile = $Chatdir.$tablanueva.'.php';
copy($file, $newfile);

foreach(glob($Chatdir.$tablanueva.'.php') as $path_to_file) {
    $file_contents = file_get_contents($path_to_file);
    $file_contents = str_replace("tablanueva","$tablanueva",$file_contents);
    file_put_contents($path_to_file,$file_contents);
}

mysqli_query($conn,"UPDATE comunicacion SET Status ='Chat' WHERE ComID ='$ComID'");

mysqli_close($conn);
mysqli_close($con);

echo "<script>window.location.href='comunicacion';</script>";
?>