
<?php
if ($_SESSION['FirstName'] == "") {
	echo 'You are not authorized to view this page. <br><br>You may <a href="index.php"><font color="blue">log in here.</font></a>';
	exit;
	}
 if($_SESSION['roladmin'] ==1){$roladmin=1;}
 if($_SESSION['masterAdmin']==1){$masteradmin=1;}
//require_once ('mysql_connect.php');
$action          = $_GET["a"];
include ('includes/admin-config.php');

//echo 'Action = ' . $action; (for testing)
//require_once ('config.inc');
//include_once 'ckeditor/ckeditor.php' ;
//require_once 'ckfinder/ckfinder.php' ;

?>

<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<?php
if ($action == "update") {
	$socialNetworks = array();

	$sql = "SELECT *
			FROM social_networks";
	$result = mysql_query($sql) or die(mysql_error());

	while ($row = mysql_fetch_assoc($result)) {
		$socialNetworks[$row['recordkey']] = $row;
	}

	if (isset($_POST['social_network']) && !empty($_POST['social_network'])) {
		$order = 0;
		foreach ($_POST['social_network'] as $socialNetworkNum => $socialNetwork) {
			$order++;
			$isExisting = false;
			if ($socialNetwork['exists'] > 0) {
				// Existing network
				$id = $socialNetwork['exists'];
				if (!array_key_exists($id, $socialNetworks)) continue;
				$isExisting = true;

				// check if deleted
				if (isset($socialNetwork['delete']) && $socialNetwork['delete'] == 'true') {
					if ($socialNetworks[$id]['locked'] == 1) {
						$sql = "UPDATE social_networks
								SET page_url = ''
								WHERE recordkey = '".$id."'";
					} else {
						$sql = "DELETE FROM social_networks
								WHERE recordkey = '".$id."'";
					}
					mysql_query($sql) or die(mysql_error());
					continue;
				}

				$networkName = $socialNetworks[$id]['locked'] == 1 ? $socialNetworks[$id]['network_name'] : $socialNetwork['network_name'];
				$pageUrl = $socialNetwork['page_url'];
				if (!stristr($pageUrl, 'http://') && !stristr($pageUrl, 'https://')) {
					$pageUrl = 'http://' . $pageUrl;
				}

				$sql = "UPDATE social_networks
						SET 
							network_name = '".mysql_real_escape_string($networkName)."',
							page_url = '".mysql_real_escape_string($pageUrl)."',
							order_sequence = '".$order."'
						WHERE recordkey = '".$id."'";
				mysql_query($sql) or die(mysql_error());


			} else {
				// New social network
				if (isset($socialNetwork['delete']) && $socialNetwork['delete'] == 'true') continue;
				if ($socialNetwork['select_network'] == 'new') {
					$networkName = $socialNetwork['network_name'];
					if (strlen($networkName) < 1) {
						continue;
					}
				} else {
					$id = $socialNetwork['select_network'];
					if (!array_key_exists($id, $socialNetworks)) continue;
					$isExisting = true;
					$networkName = $socialNetworks[$id]['network_name'];
				}
				$pageUrl = $socialNetwork['page_url'];
				if (!stristr($pageUrl, 'http://') && !stristr($pageUrl, 'https://')) {
					$pageUrl = 'http://' . $pageUrl;
				}

				if ($isExisting) {
					$sql = "UPDATE social_networks
							SET 
								network_name = '".mysql_real_escape_string($networkName)."',
								page_url = '".mysql_real_escape_string($pageUrl)."',
								order_sequence = '".$order."'
							WHERE recordkey = '".$id."'";
					mysql_query($sql) or die(mysql_error());
				} else {
					$sql = "INSERT INTO social_networks (
								page_url,
								network_name,
								locked, 
								order_sequence
							) VALUES (
								'".mysql_real_escape_string($pageUrl)."',
								'".mysql_real_escape_string($networkName)."',
								0,
								'".$order."'
							)";
					mysql_query($sql) or die(mysql_error());
					$id = mysql_insert_id();
				}
			}

			// check for uploaded icon
			if ($isExisting == true && $socialNetworks[$id]['locked'] == 1) continue;

			if (isset($_FILES['social_network']['error'][$socialNetworkNum]) && $_FILES['social_network']['error'][$socialNetworkNum] == 0) {
				$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
				$detectedType = exif_imagetype($_FILES['social_network']['tmp_name'][$socialNetworkNum]);
				if (!in_array($detectedType, $allowedTypes)) {
					// invalid file type
					continue;
				}

				$dir = realpath('../custom/images/icons/');
				if ($isExisting == true && !empty($socialNetworks[$id]['icon_name'])) {
					$fileName = $socialNetworks[$id]['icon_name'];
					if (file_exists($dir.'/'. $socialNetworks[$id]['icon_name'])) {
						unlink($dir.'/'. $socialNetworks[$id]['icon_name']);
					}
				}

				// create new file name
				$ext = pathinfo($_FILES['social_network']['name'][$socialNetworkNum], PATHINFO_EXTENSION);
				$origFileName = strtolower(preg_replace("/[^a-zA-Z0-9]+/", "", $networkName)).'-icon';
				$fileName = strtolower(preg_replace("/[^a-zA-Z0-9]+/", "", $networkName)).'-icon';

				
				$fullFileName = $fileName.'.'.$ext;
				$i = 1;
				while (file_exists($dir.'/'.$fullFileName)) {
					$fullFileName = $fileName.$i.'.'.$ext;
					$i++;
				}

				$dest = $dir.'/'.$fullFileName;
				if (move_uploaded_file($_FILES['social_network']['tmp_name'][$socialNetworkNum], $dest)) {
					// resize image
					require_once('includes/smart_resize_image.php');
					smart_resize_image($dest, 78, 78, false, $dest);

					$sql = "UPDATE social_networks
							SET icon_name = '".mysql_real_escape_string($fullFileName)."'
							WHERE recordkey = '".$id."'";
					mysql_query($sql) or die(mysql_error());
				}
			}
			unset($id);
		}
	}

	//echo $query .'<br>';	//for testing
	echo "<div align=center><font color=red>Social networking preferences updated successfully.</font></div>";	


}	//end of update query

//$query = "SELECT * from storePrefs";

//echo mysql_error();      // for testing



echo '<div id="single-admin-button">
<ul>
<a href="index.php"><li>BACK TO HOME ADMIN</li></a>
</ul>
</div>';




##******************************************* BEGIN SOCIAL NETWORKING SECTION *****************************************##
//$rt=mysql_query($query); //refresh recordset

//echo "<h3>SOCIAL NETWORKING</h3>";	

// Get all social networks
$socialNetworks = array();
$activeSocialNetworks = array();

$sql = "SELECT *
		FROM social_networks
		ORDER BY order_sequence";
$result = mysql_query($sql) or die(mysql_error());

while ($row = mysql_fetch_assoc($result)) {
	$socialNetworks[$row['recordkey']] = $row;
	if (!empty($row['page_url'])) {
		$activeSocialNetworks[$row['recordkey']] = $row;
	}
}

?>
<table id="add-social-network-template">
</table>
<form id="social-networks-form" action="<?php echo $_SERVER['PHP_SELF']; ?>?a=update" method="post" enctype="multipart/form-data">
	<table>
		<tr>
			<th width="50">Move</th>
			<th width="200">Name</th>
			<th width="250">Page URL</th>
			<th width="150">Icon</th>
			<th width="50">Delete</th>
		</tr>
	</table>
	<table id="social-networks">
		<?php $socialNetworkNum = 1; ?>
		<?php foreach ($activeSocialNetworks as $socialNetwork): ?>
			<tr>
				<td width="50">&nbsp;<img class="handle" src="http://www.pilotwebs.com/images/icon-drag.png" /></td>
				<td width="200">
					<input type="hidden" name="social_networks_order[]" value="<?php echo $socialNetwork['recordkey']; ?>" />
					<input id="social-network-exists-<?php echo $socialNetworkNum; ?>" type="hidden" name="social_network[<?php echo $socialNetworkNum; ?>][exists]" value="<?php echo $socialNetwork['recordkey']; ?>" />
					<?php if ($socialNetwork['locked'] != 1) : ?>
						<input type="text" name="social_network[<?php echo $socialNetworkNum; ?>][network_name]" value="<?php echo $socialNetwork['network_name']; ?>" />
					<?php else: ?>
						<?php echo $socialNetwork['network_name']; ?>
					<?php endif; ?>
				</td>
				<td width="250"><input type="text" name="social_network[<?php echo $socialNetworkNum; ?>][page_url]" value="<?php echo $socialNetwork['page_url']; ?>" /></td>
				<td width="150">
					<?php if (!empty($socialNetwork['icon_name'])): ?>
						<img src="/custom/images/icons/<?php echo $socialNetwork['icon_name']; ?>" width="30" />
					<?php else: ?>
						(No Icon)
					<?php endif; ?>

					<?php if ($socialNetwork['locked'] != 1): ?>
						<div>
							<br />
							Upload New Icon: <input type="file" name="social_network[<?php echo $socialNetworkNum; ?>]" />
						</div>
					<?php endif; ?>
				</td>
				<td width="50" align="center">
					<label>
						<input type="checkbox" name="social_network[<?php echo $socialNetworkNum; ?>][delete]" value="true" />
					</label>
				</td>
			</tr>
			<?php $socialNetworkNum++; ?>
		<?php endforeach; ?>
	</table>
	<table id="buttons-holder" width="100%">
		<tr>
			<td colspan="4">
				<button id="save-button" type="button" onclick="addSocialNetwork()">Add Social Network</button>

				<div style="float:right;">
					<input id="save-button" type="submit" value="Save" />
				</div>
			</td>
		</tr>
	</table>

</form>

<script type="text/javascript">
var socialNetworks = <?php echo json_encode($socialNetworks); ?>;
var socialNetworkNum = '<?php echo $socialNetworkNum; ?>';

$(document).ready(function() {
	$(document).on('change', '.select-network', function() {
		socialNetworkChanged($(this));
	});

	$("#social-networks tbody").sortable({
		helper: fixHelper,
		update: function(event, ui) {
			updateOrder();
		}
	}).disableSelection();
});

function socialNetworkChanged(obj) {
	var networkNum = obj.data('social-network-num');
	var selectedVal = obj.val();

	if (selectedVal == 'new') {
		$('#social-network-name-'+networkNum).show();
		$('#social-network-upload-icon-'+networkNum).show();
		$('#social-network-icon-'+networkNum).html('(No Icon)');
	} else {
		$('#social-network-name-'+networkNum).hide();

		// upload icon
		if (socialNetworks[selectedVal].icon_name.length > 0) {
			var iconHtml = '<img src="/custom/images/icons/'+(socialNetworks[selectedVal].icon_name)+'" width="30" />';
		} else {
			var iconHtml = '(No Icon)';
		}
		$('#social-network-icon-'+networkNum).html(iconHtml);
		
		// can they upload icon?
		if (socialNetworks[selectedVal].locked == 1) {
			$('#social-network-upload-icon-'+networkNum).hide();
		} else {
			$('#social-network-upload-icon-'+networkNum).show();
		}
	}
}

function addSocialNetwork() {
	var content = '<tr>\
			<td width="50">&nbsp;<img class="handle" src="http://www.pilotwebs.com/images/icon-drag.png" /></td>\
			<td width="200">\
				<input id="social-network-exists-'+socialNetworkNum+'" type="hidden" name="social_network['+socialNetworkNum+'][exists]" value="0" />\
				<select id="select-network-'+socialNetworkNum+'" class="select-network" name="social_network['+socialNetworkNum+'][select_network]" data-social-network-num="'+socialNetworkNum+'">\
					<?php foreach ($socialNetworks as $socialNetwork): ?>
						<option value="<?php echo $socialNetwork['recordkey']; ?>"><?php echo $socialNetwork['network_name']; ?></option>\
					<?php endforeach; ?>
					<option value="new">Add New Network</option>\
				</select>\
				<input id="social-network-name-'+socialNetworkNum+'" type="text" name="social_network['+socialNetworkNum+'][network_name]" value="" style="display:none;" />\
			</td>\
			<td width="250"><input type="text" name="social_network['+socialNetworkNum+'][page_url]" value="" /></td>\
			<td width="150">\
				<div id="social-network-icon-'+socialNetworkNum+'">\
				</div>\
				<div id="social-network-upload-icon-'+socialNetworkNum+'" style="display:none;">\
					<br />\
					Upload New Icon: <input type="file" name="social_network['+socialNetworkNum+']" />\
				</div>\
			</td>\
			<td width="50" align="center">\
				<label>\
					<input type="checkbox" name="social_network['+socialNetworkNum+'][delete]" value="true" />\
				</label>\
			</td>\
		</tr>';

	$('#social-networks').append(content);
	socialNetworkChanged($('#select-network-'+socialNetworkNum));

	socialNetworkNum++;
}

var fixHelper = function(e, ui) {
	ui.children().each(function() {
		$(this).width($(this).width());
		$(this).height($(this).height());
	});
	return ui;
};

function updateOrder() {
	$.ajax({
		type: 'POST',
		url: 'save_social_networks_order.php',
		data: $('#social-networks-form').serialize()
	}).done(function(response) {
		if (response != '1') {
			alert('Error updating social networks order.');
		}
	});
}
</script>

<?php
##******************************************* END SOCIAL NETWORKING SECTION *****************************************##

echo"</div>";	
?>