<?php
session_start();
if (!isset($_SESSION['FirstName'])) {
	die('0');
}

include ('includes/db1config.php');
include ('../includes/mysql_connect.php');

//test logging
$sql = "insert into test_log (field1) values ('triggered category save')";
mysql_query($sql);

if (isset($_POST) && !empty($_POST)) {
	if (isset($_POST['blog_id']) && !empty($_POST['blog_id']) && isset($_POST['category_id']) && !empty($_POST['category_id'])) {
		$blogId = trim($_POST['blog_id']);
		$categoryId = trim($_POST['category_id']);

		if (blogExists($blogId) == false) {
			die('Blog not found.');
		}
		if (categoryExists($categoryId) == false) {
			die('Category not found.');
		}
		if (categoryAssignedToBlog($blogId, $categoryId)) {
			die('Category already assigned to blog.');
		}

		$sql = "INSERT INTO blog_cat_ref (
					blogkey, catkey
				) VALUES (
					'".mysql_real_escape_string($blogId)."', '".mysql_real_escape_string($categoryId)."'
				)";
		mysql_query($sql) or die(mysql_error());
		die('1');
	}
}

die('Unkown Error');

function blogExists($id) {
	$sql = "SELECT * 
			FROM blog
			WHERE postid = '".mysql_real_escape_string($id)."'";
	$result = mysql_query($sql) or die(mysql_error());
	return mysql_num_rows($result) > 0;
}

function categoryExists($id) {
	$sql = "SELECT * 
			FROM blog_categories
			WHERE recordkey = '".mysql_real_escape_string($id)."'";
	$result = mysql_query($sql) or die(mysql_error());
	return mysql_num_rows($result) > 0;
}

function categoryAssignedToBlog($blogId, $categoryId) {
	$sql = "SELECT *
			FROM blog_cat_ref
			WHERE 
				blogkey = '".mysql_real_escape_string($blogId)."'
				AND catkey = '".mysql_real_escape_string($categoryId)."'";
	$result = mysql_query($sql) or die(mysql_error());
	return mysql_num_rows($result) > 0;
}
?>