<?php
include("../../includes/connect.php");
print_r($_POST);
echo "<hr />";

$cname = $_POST['campaignName'];
$clink = $_POST['campaignLink'];

$ctitle = $_POST['campaignTitle'];
$cdescr = $_POST['campaignDescription'];
$clayout = $_POST['campaignLayout']; // ADDON giugno 2021

$aname = $_POST['agencyName'];
$cowner = $_POST['campaignOwner'];
$clanguage = $_POST['campaignLanguage'];
$questionset = $_POST['question_set'];
$fbCommentSet = $_POST['comment_set'];
$redirectSet = $_POST['redirect_set'];
$sharingText = $_POST['sharingText'];

$questionset_after = $_POST['question_set_after'];

$saveanswers = $_POST['saveanswers'];
$campaign_start_date = $_POST['campaignStartDate'];
$campaign_start_date_timestamp = strtotime($campaign_start_date);
$campaign_end_date = $_POST['campaignEndDate'];

$mainColor = $_POST['main-color'];
$borderColor = $_POST['border-color'];

$campaign_end_date_timestamp = strtotime($campaign_end_date);
$data = date('Y-m-d H:i:s');
$folder_name = str_replace(" ","-",strtolower($clink));

// fields 
$fieldNames = array("sesso","nome","cognome","email","nascita","nazione","cap,","citta","cellulare","privacy1","privacy2","privacy3","privacy4","privacy5","privacy6","privacy7","privacy8");


$fields = "{";
for($f = 0; $f < count($fieldNames); $f++)
{
$nomeCampo = $fieldNames[$f];

$valoreCampo = isset($_POST["f_" . $nomeCampo]) ? 1 : 0;

$fields .= "\"$nomeCampo\" : \"$valoreCampo\"";
if($f < count($fieldNames)-1)
{
	$fields .= ",";
}
}

$fields .= "}";

echo $fields;

// domande e risposte



$bg =$_POST['file1'];
$frontDesktop =$_POST['file2'];
$frontMobile =$_POST['file3'];
$regolamento = $_POST['file4'];
$privacy = $_POST['file5'];
$cookie= $_POST['file6'];


$connection->query("INSERT INTO campaigns (campaign_name,campaign_owner,campaign_creation) VALUES ('$cname','$cowner','$data')");
//print_r($connection->errorInfo());
$id = $connection->lastInsertId();

$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','campaign_name','$cname')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','campaign_link','$clink')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','campaign_title','$ctitle')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','campaign_description','$cdescr')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','campaign_layout','$clayout')"); // ADDON Giugno 2021
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','agency_name','$aname')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','campaign_folder','$folder_name')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','language','$clanguage')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','saveanswer','$saveanswers')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','start','$campaign_start_date')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','start_ts','$campaign_start_date_timestamp')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','end','$campaign_end_date')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','end_ts','$campaign_end_date_timestamp')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','bg','$bg')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','mainColor','$mainColor')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','borderColor','$borderColor')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','front_desktop','$frontDesktop')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','front_mobile','$frontMobile')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','fieldsVisibility','$fields')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','commentsSet','$fbCommentSet')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','redirectSet','$redirectSet')");
$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','sharingText','$sharingText')");

// se il set di domande non è pre-esistente lo creo
/*
if($questionset == "")
{
	
	echo "Creo il nuovo set di domande";
	$questionSetName = $_POST['questionSetName'];
	
	$connection->query("INSERT INTO questions_sets (set_name,set_language) VALUES ('$questionSetName','$clanguage')");
	$questionset = $connection->lastInsertId();
	$domande = $_POST['domande'];


for($d = 0; $d < count($domande); $d++)
{
	$questionText = $domande[$d]['domanda'];
	$connection->query("INSERT INTO questions (text,sets_in) VALUES ('$questionText','$questionset')");
	$idQuestion = $connection->lastInsertId();
	for($r = 0; $r < count($domande[$d]['risposte']); $r++)
	{
		$answerText = $domande[$d]['risposte'][$r]['risposta'];
		$connection->query("INSERT INTO answers (question_id,text) VALUES ('$idQuestion','$answerText')");
	}
}


}
*/

$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','questionset','$questionset')");

// se il set di domande di profilazione non è pre-esistente lo creo
/*
if($questionset_after == "")
{
    
    echo "Creo il nuovo set di domande (Dopo il form)";
    $questionSetNameAfter = $_POST['questionSetNameAfter'];
    
    $connection->query("INSERT INTO profilation_sets (set_name,set_language) VALUES ('$questionSetNameAfter','$clanguage')");
    $questionset_after = $connection->lastInsertId();
    $domande = $_POST['domandeAfter'];


for($d = 0; $d < count($domande); $d++)
{
    $questionText = $domande[$d]['domanda'];
    $connection->query("INSERT INTO profilation_questions (text,sets_in) VALUES ('$questionText','$questionset_after')");
    $idQuestion = $connection->lastInsertId();
    for($r = 0; $r < count($domande[$d]['risposte']); $r++)
    {
        $answerText = $domande[$d]['risposte'][$r]['risposta'];
        $connection->query("INSERT INTO profilation_answers (question_id,text) VALUES ('$idQuestion','$answerText')");
    }
}

}
*/

$tabellaprofilazione = "campaign" . $id . "_user_answers";
$connection->query("CREATE TABLE `$tabellaprofilazione` (
  `id` int(11) NOT NULL,
  `campaign_id` int(11) NOT NULL,
  `externalId` varchar(250) COLLATE utf8_bin NOT NULL,
  `questionId` int(11) NOT NULL,
  `answerId` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

ALTER TABLE `$tabellaprofilazione`
  ADD PRIMARY KEY (`id`);


ALTER TABLE `$tabellaprofilazione`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;");

/* DOMANDE PRE-FORM */

$tabellaprofilazione_preform = "campaign" . $id . "_user_answers_preform";
$connection->query("CREATE TABLE `$tabellaprofilazione_preform` (
  `id` int(11) NOT NULL,
  `campaign_id` int(11) NOT NULL,
  `externalId` varchar(250) COLLATE utf8_bin NOT NULL,
  `questionId` int(11) NOT NULL,
  `answerId` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

ALTER TABLE `$tabellaprofilazione_preform`
  ADD PRIMARY KEY (`id`);


ALTER TABLE `$tabellaprofilazione_preform`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;");


$connection->query("INSERT INTO campaigns_meta (campaign_id,meta_key,meta_value) VALUES ('$id','questionset_after','$questionset_after')");

$tabellalead = "campaign" . $id . "_leads";

$connection->query("CREATE TABLE `$tabellalead` (
  `id` int(11) NOT NULL,
  `campaignId` int(11) NOT NULL,
  `externalid` varchar(250) COLLATE utf8_bin NOT NULL,
  `nome` varchar(255) COLLATE utf8_bin NOT NULL,
  `cognome` varchar(255) COLLATE utf8_bin NOT NULL,
  `sesso` varchar(6) COLLATE utf8_bin NOT NULL,
  `nascita` date NOT NULL,
  `email` varchar(250) COLLATE utf8_bin NOT NULL,
  `cellulare` varchar(50) COLLATE utf8_bin NOT NULL,
  `cap` int(11) NOT NULL,
  `citta` varchar(255) COLLATE utf8_bin NOT NULL,
  `indirizzo` varchar(255) COLLATE utf8_bin NOT NULL,
  `civico` varchar(255) COLLATE utf8_bin NOT NULL,
  `privacy` tinyint(1) NOT NULL DEFAULT '0',
  `privacy2` tinyint(1) NOT NULL DEFAULT '0',
  `privacy3` tinyint(1) NOT NULL DEFAULT '0',
  `privacy4` tinyint(1) NOT NULL DEFAULT '0',
  `privacy5` tinyint(4) NOT NULL DEFAULT '0',
  `privacy6` tinyint(4) NOT NULL DEFAULT '0',
  `privacy7` tinyint(4) NOT NULL DEFAULT '0',
  `privacy8` tinyint(1) NOT NULL DEFAULT '0',
  `validata` int(1) NOT NULL DEFAULT '0',
  `ip` varbinary(32) NOT NULL,
  `timestamp` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

ALTER TABLE `$tabellalead` ADD PRIMARY KEY (`id`);

ALTER TABLE `$tabellalead`  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;");

mkdir("../../../" . $folder_name);

function custom_copy($src, $dst) {  
  
    // open the source directory 
    $dir = opendir($src);  
  
    // Make the destination directory if not exist 
    @mkdir($dst);  
  
    // Loop through the files in source directory 
    while( $file = readdir($dir) ) {  
  
        if (( $file != '.' ) && ( $file != '..' )) {  
            if ( is_dir($src . '/' . $file) )  
            {  
  
                // Recursively calling custom copy function 
                // for sub directory  
                custom_copy($src . '/' . $file, $dst . '/' . $file);  
  
            }  
            else {  
                copy($src . '/' . $file, $dst . '/' . $file);  
            }  
        }  
    }  
  
    closedir($dir); 
}  

custom_copy("../../../baseAssets","../../../" . $folder_name );

if($bg != "")
{
rename("../../tmp/$bg", "../../../$folder_name/assets/$bg");
}
if($frontDesktop != "")
{
rename("../../tmp/$frontDesktop", "../../../$folder_name/assets/$frontDesktop");
}
if($frontMobile != "")
{
rename("../../tmp/$frontMobile", "../../../$folder_name/assets/$frontMobile");
}

if($regolamento != "")
{
rename("../../tmp/$regolamento", "../../../$folder_name/docs/regolamento.pdf");
}
if($privacy != "")
{
rename("../../tmp/$privacy", "../../../$folder_name/docs/privacy.pdf");
}
if($cookie != "")
{
rename("../../tmp/$cookie", "../../../$folder_name/docs/cookie.pdf");
}
echo "ID CAMPAGNA: $id";

$dataFile = fopen("../../../$folder_name/cdata.txt", "w") or die("Unable to open file!");
fwrite($dataFile, $id);
fclose($dataFile);


?>