<?php 
global $wpdb;
$table_name = $wpdb->prefix . 'visitors_edits';
if(isset($_GET["delete"])){
	$wpdb->delete($table_name, array( 'edit_id' => $_GET["delete"] ) );
	flashMessage("The review was deleted","danger");
}
if(!empty($_POST)){
    wp_update_post([
		"ID"=>$_POST["ID"],
		"post_content"=>$_POST["post_content"]
	]);
	$wpdb->delete($table_name, array( 'edit_id' => $_POST["edit_id"] ) );
	flashMessage("The post was updated successfully","");
    //Notify visitor
    if(isset($_POST["notify_visitor"])){
    require 'mail.php';
        $post = get_post($_POST["ID"]);
        $mail = [
            "visitor_name"=>$_POST["visitor_name"],
            "post_title"=>$post->post_title,
            "post_url"=>get_permalink($_POST["ID"]),
            "blog_title" => get_bloginfo("name"),
            "admin_message"=>$_POST["admin_message"]
        ];
        $visitor_submitionMail=new visitors_edits_EMAIL($mail,"visitor_approval");
        $visitor_submitionMail->send($_POST["visitor_email"]);
    }
}
$edits = $wpdb->get_results("SELECT * FROM ".$table_name);
for ($r=0; $r <count($edits); $r++) { 
	$edits[$r]->post=get_post($edits[$r]->post_id);
}
?>
<h1 class="visitors_edits_no_data" <?php if(count($edits)==0){echo 'style="display:block"';}?>>
    Emty pending list
</h1>
<div class="visitors_edits_pending" <?php if(count($edits)==0){echo 'style="display:none"';}?>>
    <h1>Pending reviews (<?php echo count($edits);?>)</h1>
    <table class="widefat pending">
        <thead>
            <tr>
                <th>Post</th>
                <th>Author</th>       
                <th>Author comment</th>
                <th>Date</th>
                <th>Options</th>
            </tr>
        </thead>
        <tbody>
<?php
for ($i=0; $i < count($edits); $i++) { 
	$edit=$edits[$i];
	?>
       <tr>
         <td><?php echo $edit->post->post_title; ?></td>
         <td><?php echo $edit->visitor_name?></td>
         <td>
            <?php echo stripslashes($edit->visitor_comment); ?>
         </td>
         <td><?php
         	$creationDate=date_create($edit->edit_time);
         	echo date_format($creationDate,"m/d/Y")." at ".date_format($creationDate,"h:i a")
         	?></td>
         <td>
         	<a class="button-primary" href="<?php echo menu_page_url('visitors_edits_approve',false);?>&edit=<?php echo $edit->edit_id;?>">Review</a>
    		<a class="button-secondary" href="<?php echo menu_page_url('visitors_edits_main',false);?>&delete=<?php echo $edit->edit_id;?>">Delete</a>
    	</td>
       </tr>
	<?php 
}
?>
        </tbody>
    </table>
</div>
<?php
function flashMessage($msg,$type){
    ?>
    <div class="visitors_flashMessage <?php echo $type ?>">
        <p>
            <?php echo $msg ;?>
        </p>
    </div>
    <?php
}
?>