<?php
// function that runs when shortcode is called
function showall_weblink_shortcode() { 

if( ! get_current_user_id())
{
	echo "Please login to view the content";
	return;
}
if(isset($_GET['deleteid']))
{

			$post_author_id = get_post_field( 'post_author', $_GET['deleteid'] );
			if($post_author_id == get_current_user_id())
			{
				wp_delete_post( $_GET['deleteid'] , true );
				echo "<p>Web Link Deleted </p>";
			}
			else
				echo "<p style= 'color: red'>Unauthorised Access, Please contact Administrator.</p>";
}

if(isset($_GET['editid']) && ! (isset( $_POST['cpt_nonce_field'] )))
{

			$post_author_id = get_post_field( 'post_author', $_GET['editid'] );
			if($post_author_id == get_current_user_id())
			{
				//editing the weblink
				$weblink_url = get_post_meta( $_GET['editid'], 'weblink_url', true ); 
				$weblink_desc = get_post_meta( $_GET['editid'], 'weblink_desc', true );
				//get all tags
				$weblink_tags = wp_get_post_terms( $_GET['editid'], 'tag_weblink',array( 'fields' => 'names' ));
				$weblink_tags = implode(",",$weblink_tags);
				$weblink_cat = wp_get_post_terms( $_GET['editid'], 'category_weblink',array( 'fields' => 'ids' ));
				$weblink_cat = implode(",",$weblink_cat);
?>
<form class="form-horizontal" method = "post" name="weblinkform" onsubmit="return validateForm()">
<fieldset>

<!-- Form Name -->
<legend>Edit Link</legend>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="title">Story Title[Title Can not be edited]</label>  
  <div class="col-md-5">
  <input id="title" name="title" type="text" placeholder="Add Story Title" class="form-control input-md" readonly value="<?php echo get_the_title(  $_GET['editid']  ); ?>">
    
  </div>
</div>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="title">Story Link</label>  
  <div class="col-md-5">
  <input id="link" name="link" type="text" placeholder="Add Story Link" class="form-control input-md" required="" value="<?php echo $weblink_url; ?>">
    
  </div>
</div>

<!-- Select Basic -->
<div class="form-group">
  <label class="col-md-4 control-label" for="category">Select Category</label>
  <div class="col-md-5">
    <select id="category" name="category" class="form-control">
		<option value="">Please Select</option>
	<?php 
	//$terms = wp_get_post_terms( $post->ID, array( 'category_weblink') ); 
	$terms = get_terms( array(
    'taxonomy' => 'category_weblink',
    'hide_empty' => false
) );	
						foreach ( $terms as $term ) : 
								$selected = "";
								if($weblink_cat == $term->term_id)
									$selected = "selected";
							echo  '<option value=" ' . $term->name . '" ' .$selected .'>' . $term->name . '</option>' ;
						endforeach; ?>
    </select>
  </div>
</div>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="tags">Tags</label>  
  <div class="col-md-5">
  <input id="tags" name="tags" type="text" placeholder="Add Tags separeted by comma(,)" class="form-control input-md" value="<?php echo $weblink_tags; ?>">
    
  </div>
</div>

<!-- Textarea -->
<div class="form-group">
  <label class="col-md-4 control-label" for="description">Description</label>
  <div class="col-md-4">                     
    <textarea class="form-control" id="description" name="description"><?php echo $weblink_desc; ?></textarea>
  </div>
</div>

<!-- Button -->
<div class="form-group">
  <label class="col-md-4 control-label" for="submitlink"></label>
  <div class="col-md-4">
    <button id="submitlink" name="submitlink" class="btn btn-primary">Submit</button>
  </div>
</div>
<!-- We will Add JS Now -->
<script>
function validateForm() {
  var weblink = document.forms["weblinkform"]["link"].value;
  var weblinkcat = document.forms["weblinkform"]["category"].value;
  regexp =  /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
        if (! regexp.test(weblink))
		{
			alert("Please Check The link you provided");
			return false;
		}
		if(weblinkcat == "")
		{
			alert("Please Select Category");
			return false;
		}
		return true;
        
}</script>
<?php wp_nonce_field( 'cpt_nonce_action', 'cpt_nonce_field' ); ?>

</fieldset>
</form>
<?php					
			}
			else
				echo "<p style= 'color: red'>Unauthorised Access, Please contact Administrator.</p>";
}
//upadating data
if (isset( $_POST['cpt_nonce_field'] ) && wp_verify_nonce( $_POST['cpt_nonce_field'], 'cpt_nonce_action' ) ) 
	{
		
		//first check if tag term exist or not. If not then create it. 
		$alltags = explode(",",$_POST['tags']);
		$alltags = array_map('strtolower', $alltags);
		$alltagid = array();
		for($i=0;$i<count($alltags);$i++)
		{
			if($check_term = term_exists( $alltags[$i], "tag_weblink" ) )
				$alltagid[ ] = $check_term;
			else
			{
				 $newterm = wp_insert_term( $alltags[$i], "tag_weblink");
				 $alltagid[ ] = $newterm['term_id'];
			}
		}
		update_post_meta( $_GET['editid'], 'weblink_url', $_POST['link'] ); 
		update_post_meta( $_GET['editid'], 'weblink_desc', $_POST['description'] ); 
		wp_set_object_terms( $_GET['editid'], $_POST['tags'], 'tag_weblink' );
		wp_set_object_terms( $_GET['editid'], $_POST['category'], 'category_weblink' );
		echo "<h2 style='color:green;margin-top : 0;'>Link Edited Successfully.</h2>";
		
	}

//data updated

if(! isset($_GET['editid']))
{
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
     'post_type' => 'weblink',
	 'author' => get_current_user_id(),
     'posts_per_page' => 10,
     'paged' => $paged
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
     // CPT content
	 $weblink_url = get_post_meta( get_the_ID(), 'weblink_url', true ); 
	$weblink_desc = get_post_meta( get_the_ID(), 'weblink_desc', true );
	 ?>
	 <div itemscope="" itemtype="http://schema.org/Article" class="stories" id="xnews-1977">

			<div class="story_data">
				  			<div class="votebox votebox-new">
								<div class="title" id="title-1977">
									<span itemprop="name">
										<h2 dir="ltr">
											<a href="<?php echo the_permalink(); ?>"><?php echo the_title(); ?></a>
																</h2>
									</span>	
			<span class="subtext">
				<span id="ls_avatar-1977"><img  style= "display : inline;" itemprop="image" src="<?php echo plugin_dir_url( __FILE__ ) . 'img/avtar.png'; ?>" width="32px" height="32px"></span>				<span itemprop="author" itemscope="" itemtype="http://schema.org/Person">
				<span itemprop="name">
				<?php
				global $post;
				$a_id=$post->post_author;
				the_author_meta( 'user_nicename', $a_id ); ?>  
				</span></span>
				<i class="fa fa-clock-o"></i>
				<span itemprop="datePublished"><?php the_date(); ?></span>
				
				<i class="fa fa-folder"></i> 
				<?php $terms = wp_get_post_terms( $post->ID, array( 'category_weblink') ); ?>
						<?php
						$index = 0;
						foreach ( $terms as $term ) : 
						if($index) echo " , ";
						?>
						<?php echo $term->name; $index = $index + 1 ;?>
						<?php endforeach; ?>
                    				
															<i class="fa fa-tag"></i>
																						<?php $terms = wp_get_post_terms( $post->ID, array( 'tag_weblink') ); ?>
						<?php
						$index = 0;
						foreach ( $terms as $term ) : 
						if($index) echo " , ";
						echo $term->name; $index = $index + 1 ;?>
						<?php endforeach; ?>						
									<i class="fa fa-globe"></i>
					<a href="<?php echo $weblink_url; ?>" rel="nofollow"><?php echo $weblink_url; ?></a>

												&nbsp;
 
				                
			</span>
		</div><!-- /.title -->
	</div> <!-- /.story_data -->
	<span itemprop="articleBody">
	<div class="storycontent">
									
			<div class="news-body-text" id="ls_contents-1977" dir="ltr">
															
						<?php echo $weblink_desc; ?>							 
																																																																
				
				<div class="clearboth"></div> 
                </div>
						</div><!-- /.storycontent -->
	</span>
	</div>
	  <a href="?editid=<?php echo get_the_ID(); ?>" ><button type="button" class="btn btn-primary">Edit Link</button></a>
	    <a href="?deleteid=<?php echo get_the_ID(); ?>" onclick="return deleteweblink()"><button type="button" class="btn btn-danger">Delete Link</button></a>
<hr>
<script>
function deleteweblink() {
  var r = confirm("Do you want to delete the link?");
  if (r == true) {
    return true;
  } else {
    return false;
  }
  
}
</script>
	<?php
endwhile;
?>
<div class="pagination">
     <?php
     $big = 999999999;
     echo paginate_links( array(
          'base' => str_replace( $big, '%#%', get_pagenum_link( $big ) ),
          'format' => '?paged=%#%',
          'current' => max( 1, get_query_var('paged') ),
          'total' => $loop->max_num_pages,
          'prev_text' => '&laquo;',
          'next_text' => '&raquo;'
     ) );
?>
</div>

<?php wp_reset_postdata(); 

}

 }



// register shortcode
add_shortcode('user_weblink_manage', 'showall_weblink_shortcode');