<?php
include '../../pagename.php';
include '../../'.$session;
Session::checkSession_app();
include '../../../config.php';
function sanitize_input($data) { //filter value function
    global $db;

    return mysqli_real_escape_string($db->link, htmlspecialchars(stripslashes(trim($data))));
}

$s_id = '';
$c_from = '';
$c_name = '';
$c_sub = '';
$c_msg = '';
$c_unsub = '';

$user_id = $_SESSION['id'];
$s_id = sanitize_input($_POST['s_id']);
$c_from = sanitize_input($_POST['c_from']);
$c_name = sanitize_input($_POST['c_list']);
$c_sub = sanitize_input($_POST['c_sub']);
$c_msg = sanitize_input($_POST['c_msg']);
$c_unsub = $_POST['c_unsub'];
if ($c_unsub === 'true') {
	$c_unsub = 'true';
}
elseif ($c_unsub === 'false') {
	$c_unsub = 'false';
}; 
$c_date = date('Y-m-d H:i:s');

if(!empty($user_id) && !empty($s_id) && !empty($c_from) && !empty($c_name) && !empty($c_sub)){
	$check_sql = $db->select("SELECT c_name, c_user_id FROM evp_campaign_list WHERE c_name='$c_name' and c_user_id='$user_id'");
	$check_sql = mysqli_num_rows($check_sql);
		if($check_sql == 0) {
		$insert_edata = $db->select("INSERT INTO evp_send_email_list (email_add, list_name)
		SELECT elist.email_name, '$c_name'
		FROM evp_email_list elist
		INNER JOIN evp_tag_list etag 
		ON etag.target_csv_name = elist.csv_file_name
		WHERE
		etag.list_name = '$c_name' AND
		etag.user_id = '$user_id' AND
		elist.email_status = 'VALID'");
	
		$insert_cdata = $db->select("INSERT INTO evp_campaign_list (c_user_id, c_name, s_id, c_from, c_sub, c_msg, c_unsub, c_date) Values ('$user_id', '$c_name', '$s_id', '$c_from', '$c_sub', '$c_msg', '$c_unsub', '$c_date')");

		$update_cdata = $db->select("UPDATE evp_campaign_list e_data 
									JOIN (select list_name, count(*) as cnt
										FROM evp_send_email_list
											group by list_name
										) elist
										ON e_data.c_name = elist.list_name
										SET e_data.total_amount = elist.cnt
										WHERE
										 e_data.c_name = '$c_name'");


		return print_r(json_encode(array('title' => 'Success','text' => 'Campaign successfully created!','type' =>'success')));
		
		} else {
			/*
			echo 'sorry, campaign already exists!';	
			header('HTTP/1.1 500 Internal Server...');
			header('Content-Type: application/json; charset=UTF-8');
			die(json_encode(array('type' => 'error', 'code' => 1337)));
			*/
			return print_r(json_encode(array('title' => 'Caution','text' => 'This campaign already exists!','type' =>'info')));
		}
} else{
	return print_r(json_encode(array('title' => 'Error','text' => 'Sorry, no data received!','type' =>'error')));
	header("Location: ../../../".$index);
}

?>
