<?php
function sm_pages($campaign) {
	if (isset($_POST['smAddPage'])) {
		$keyword = get_post_meta(111111113, $campaign . 'smkeyword1', TRUE);
		$keyword = urlencode($keyword);

		$pageurl = trim($_POST['pageurl']);
		$pageid = $pageurl;

/*    $regexp = '/^(https?:\/\/)?(www\.)?facebook\.com\/([^\?\/\n]*)/mi';
		$matches = [];
		$matches2 = [];

		if (preg_match($regexp, trim($_POST['pageid']), $matches)) {
			if (!empty($matches[3])) {
				if (preg_match('/^[^\?\/\n]*\-(\d{12,})$/mi', $matches[3], $matches2)) {
					$pageid = $matches2[1];
				} else {
					$pageurl = $matches[3];
					$page = smGetFbPageID($pageurl, $campaign);
					if ($page["success"] === true)  {
						$pageid = $page["id"];
					}
				}
			}
		} */

		$pagename = trim($_POST['pagename']);

		if ($pageid !== '') {
			global $wpdb;
			$tbl_kws_fb = $wpdb->prefix . "smpages";

			$wpdb->insert(
				$tbl_kws_fb,
				array(
					'keyword' => $keyword,
					'node_id' => $pageid,
					'title' => $pagename,
					'talking_about' => 999999999,
					'likes' => 999999999,
					'supressed' => 'NO',
				),
				array(
					'%s',
					'%s',
					'%s',
					'%d',
					'%d',
					'%s',
				)
			);
		}
	}

	$setstatus = plugins_url('smsetPageStatus.php', __FILE__);

	echo "<script type = 'text/javascript'>
	jQuery(document).ready(function () {
		jQuery('.ToggleSwitchSample').toggleSwitch();
	});

	function smchangeStatus(id){
		request = jQuery.ajax({
				type: 'post',
				  url: '" . $setstatus . "',
				  data: { id: id}
				  })
		.done(function( msg ) {
	  });
	}
	</script>";
	// $cron = plugin_dir_url(__FILE__) . 'auto2.php?campaign=' . $campaign;

	// echo '
	// <br />
	// <div style = "float:left; margin:5px;"><strong>The data on this page will be updated regularly (every day or two) but in case you want to do a manual update, click this button... </strong>
	// <a href="' . $cron . '" target="_blank">
	// 	<button class = "button button-primary" >Fetch Data</button>
	// </a>
	// </div>
	// <br />';

	echo '<div>
		<form method="post" action="">
		<table>
			<td>Facebook Fan Page URL: <input type="text" name="pageurl" size = "50"></td><td>Name: <input type="text" name="pagename" size = "50"></td>';
	echo '<td><input name="smAddPage" type="submit" value="Add Page" class = "button button-primary" ></td></tr>
	</table>';

//	if ($pageid === '') {
//		echo '<p style="color: red">Cannot find page id from the given URL</p>';
//	}
	echo '</form>';

	echo '<form id="pagedata" method="post" action="">';
	$wp_list_table = new smPages_Table($campaign);
	$wp_list_table->prepare_items();
	$wp_list_table->display();

	echo '</form>';
}

function smGetFbPageID($name, $campaign) {
	$response = wpsmFacebookQuery($name, '', $campaign);

	if (isset($response["error"])) {
		return array ("success" => false, "message" => $response["error"]["message"]);
	}

	return array ("success" => true, "id" => $response["id"]);
}
