<?php
session_start();

if (isset($_POST['pid']) and $_POST['pid']!= '') {
	
	include ("../includes/db.php");
	$userId = $_SESSION['id'];
	
	$pid = mysql_escape_string($_POST['pid']);
	$public = 0; //mysql_escape_string($_POST['public']);
	
	// CHECK EXISTANCE
	$query = "SELECT Id FROM page WHERE PageId = '$pid' ";
	$res = mysql_query ($query);
	$nr = mysql_num_rows ($res);
	if ($nr == 0) {
		// INSERT PAGE
		$query = "INSERT INTO page (PageId, Public, Verified) VALUES ('$pid', '$public', 0) ";
		mysql_query ($query);
		// INSERT USER_PAGE_SUBMISSION
		if (isset($_SESSION['id'])) {
			$pgid = mysql_insert_id();
			$query = "INSERT INTO user_page_submission (UserId, PageId) VALUES ('$userId', '$pgid') ";
			mysql_query ($query);
			
			$note = "Page with Id " . $pid . " is successfully submitted and will be indexed within 24 hours.";
		}
	} else {
		// PAGE ALREADY EXISTS
		$row = mysql_fetch_array ($res);
		extract ($row);
		$pgid = $Id;
		// INSERT USER_PAGE_SUBMISSION
		if (isset($_SESSION['id'])) {
			$query = "INSERT INTO user_page_submission (UserId, PageId) VALUES ('$userId', '$pgid') ";
			mysql_query ($query);
			
			$note = "Page already exists. You are able to see page statistics immediately.";
		}
	}
	// INSER NOTE
	$query = "INSERT INTO note (PageId, Content) VALUES ('$pgid', '$note') ";
	mysql_query ($query);
	
	
	// INSERT USER_PAGE_NOTE
	if (isset($_SESSION['id'])) {
		$noteId = mysql_insert_id();
		$query = "INSERT INTO user_note (UserId, NoteId) VALUES ('$userId', '$noteId') ";
		mysql_query ($query);	
	}
	
	echo 'success';
}

?>