<?php 

session_start();
if (isset($_SESSION['user_email'])){

require '../../config.php';
require '../functions.php';

$connect = connect($database);

$check_access = check_access($connect);

if ($check_access['user_role'] == 1 || $check_access['user_role'] == 2){

// Get all stores for dropdown
$query = $connect->query("SELECT store_id, store_title FROM stores WHERE store_status = 1 ORDER BY store_title ASC");
$stores = $query->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] == 'POST'){

	$campaign_title = cleardata($_POST['campaign_title']);
	$campaign_store = !empty($_POST['campaign_store']) ? (int)$_POST['campaign_store'] : NULL;
	$campaign_link = cleardata($_POST['campaign_link']);
	$campaign_order = (int)$_POST['campaign_order'];
	$campaign_status = (int)$_POST['campaign_status'];
	$campaign_sidebar = isset($_POST['campaign_sidebar']) ? (int)$_POST['campaign_sidebar'] : 0;

	$extsAllowed = array('jpg', 'jpeg', 'png', 'gif', 'webp', 'avif');
	$campaign_image = 'default-campaign.png';

	// Handle File Upload
	if (isset($_FILES['campaign_image']) && $_FILES['campaign_image']['error'] == 0) {
		$extUpload = strtolower( substr( strrchr($_FILES['campaign_image']['name'], '.') ,1) ) ;

		if (in_array($extUpload, $extsAllowed) ) { 

			$image = $_FILES['campaign_image']['tmp_name'];
			$imagefile = explode(".", $_FILES["campaign_image"]["name"]);
			$renamefile = round(microtime(true)) . '.' . end($imagefile);
			$image_upload = '../../images/';
			move_uploaded_file($image, $image_upload . 'campaign_' . $renamefile);
			$campaign_image = 'campaign_' . $renamefile;
		}
	}

	// Handle CDN fields
	$campaign_image_cdn_url = isset($_POST['campaign_image_cdn_url']) ? cleardata($_POST['campaign_image_cdn_url']) : '';
	$campaign_use_cdn = isset($_POST['campaign_use_cdn']) ? 1 : 0;

	$statment = $connect->prepare("INSERT INTO campaigns (campaign_id, campaign_title, campaign_image, campaign_store, campaign_link, campaign_order, campaign_status, campaign_sidebar, campaign_image_cdn_url, campaign_use_cdn) VALUES (null, :campaign_title, :campaign_image, :campaign_store, :campaign_link, :campaign_order, :campaign_status, :campaign_sidebar, :campaign_image_cdn_url, :campaign_use_cdn)");

	$statment->execute(array(
		':campaign_title' => $campaign_title,
		':campaign_image' => $campaign_image,
		':campaign_store' => $campaign_store,
		':campaign_link' => $campaign_link,
		':campaign_order' => $campaign_order,
		':campaign_status' => $campaign_status,
		':campaign_sidebar' => $campaign_sidebar,
		':campaign_image_cdn_url' => $campaign_image_cdn_url,
		':campaign_use_cdn' => $campaign_use_cdn
	));

	header('Location: ./campaigns.php');

}

require '../views/header.view.php';
require '../views/new.campaign.view.php';

}else{
	
	header('Location:'.SITE_URL);
}

require '../views/footer.view.php';

}else {

	header('Location: ./login.php');	

}

?>
