<?php
if ( ! defined( 'ABSPATH' ) ) exit;
require_once( 'legalPages.php' );
global $wpdb;
$lpObj = new legalPages();
$lpObj->lp_enqueue_editor();
$mode = isset($_REQUEST['mode'])?$_REQUEST['mode']:'';
$page = isset($_REQUEST['page'])?$_REQUEST['page']:'';
$baseurl = esc_url(get_bloginfo('url'));
//$baseurl = $_SERVER['PHP_SELF'];

?>
    <div style="width:1000px;float:left;">
        <h1 class="logo-hh"><img style="width: 142px;" src="<?php echo plugin_dir_url(__FILE__); ?>image/wpLegalEagle2.png"></h1> </div>
    <script type="text/javascript">
        function SetName(url, page, tid, tname, mode, nonce) {
            var name = prompt("Please enter template name:", tname);
            if (name != null) {
                location.href = url + "?page=" + page + "&lpid=" + tid + "&name=" + name + "&mode=" + mode + "&_wpnonce=" + nonce;
            }
            else return false;
        }
    </script>
    <div style="clear:both;"></div>
    <div class="wrap">
        <?php
/* Code added for clone */
if(isset($_REQUEST['mode']) && $_REQUEST['mode']=='clone' && isset($_REQUEST['lpid']))
{
	$title = $_REQUEST['name'];
	$tid = $_REQUEST['lpid'];

    $nonce = $_REQUEST['_wpnonce'];

    if(! wp_verify_nonce( $nonce,'my-nonce' ))
    {
        wp_die( __('Invalid Action') );
    }

	$row = $wpdb->get_row($wpdb->prepare('SELECT * from '.$lpObj->tablename.' where id= %d',$tid));
	$wpdb->insert($lpObj->tablename,array('title'=>$title,'content'=>$row->content,'notes' => $row->notes),array('%s','%s','%s'));
	if($wpdb->insert_id){
?>
            <div id="message">
                <p><span class="label label-success myAlert"><?php _e('Template Successfully Cloned.','wplegalpages');?></span></p>
            </div>
            <script type="text/javascript">
                location.href = "<?php echo esc_url($baseurl).'/wp-admin/admin.php?page='.$page ?>";
            </script>
            <?php
	}
}

/*  Retrieve values from URL which are set to
*   multi Clone the Templates.
*   The Ids in URL are in string Format. So Convert them back to Array.
*/
if(isset($_REQUEST['mode']) && $_REQUEST['mode']=='bulk_clone' && isset($_REQUEST['lpid'])){

    $selected_clone_ids_str = $_REQUEST['lpid'];
    $selected_clone_ids_arr = explode(",", $selected_clone_ids_str);

    $nonce = $_REQUEST['_wpnonce'];

    if(! wp_verify_nonce( $nonce,'my-nonce' ))
    {
        wp_die( __('Invalid Action') );
    }

    $result = $wpdb->get_results("select * from $lpObj->tablename");
    foreach ($selected_clone_ids_arr as $key) {

        foreach ($result as $res) {

            $id = $res->id;
            if($id == $key){
                $title = $res->title;           /*  The newly Cloned templates will have 'Copy of' Prefix   */
                $title = "Copy of ".$title;
                $row = $wpdb->get_row("select * from $lpObj->tablename where id in (".$selected_clone_ids_str.")");
                $wpdb->insert($lpObj->tablename,array('title'=>$title,'content'=>$row->content,'notes' => $row->notes),array('%s','%s','%s'));
            }
        }
    }
    if($wpdb->insert_id){
    ?>
                <div id="message">
                    <p><span class="label label-success myAlert"><?php _e('Selected Templates Cloned Successfully.','wplegalpages');?></span></p>
                </div>
                <?php
    }
    ?>
                    <script type="text/javascript">
                        location.href = "<?php echo esc_url($baseurl).'/wp-admin/admin.php?page='.$page ?>";
                    </script>
                    <?php
}
if(isset($_REQUEST['mode']) && $_REQUEST['mode']=='delete')
{

	$nonce = $_REQUEST['_wpnonce'];

	if(! wp_verify_nonce( $nonce,'my-nonce' ))
	{
		wp_die( __('Invalid Action') );
	}

    $wpdb->delete($lpObj->tablename,array('id' => $_REQUEST['lpid']),array('%d'));
    ?>
                        <div id="message">
                            <p><span class='label label-success myAlert'><?php _e('Template Deleted Successfully.','wplegalpages');?></span></p>
                        </div>
                        <script type="text/javascript">
                            location.href = "<?php echo esc_url($baseurl).'/wp-admin/admin.php?page='.$page ?>";
                        </script>
                        <?php
}
/*  Retrieve values from URL which are set to
*   multi Delete the Templates.
*/
if( isset($_REQUEST['mode']) && $_REQUEST['mode'] == "bulk_delete"){

    $nonce = $_REQUEST['_wpnonce'];

    if(! wp_verify_nonce( $nonce,'my-nonce' ))
    {
        wp_die( __('Invalid Action') );
    }
    $posts_to_delete = sanitize_text_field(esc_attr($_REQUEST['lpid']));

    $wpdb->query("delete from $lpObj->tablename where id in (".$posts_to_delete.")");
    ?>
                            <div id="message">
                                <p><span class='label label-success myAlert'><?php _e('Selected Templates Deleted Successfully.','wplegalpages');?></span></p>
                            </div>
                            <script type="text/javascript">
                                location.href = "<?php echo esc_url($baseurl).'/wp-admin/admin.php?page='.$page ?>";
                            </script>
                            <?php
}

if(!empty($_POST) && isset($_POST['lp-submit'])) :
$title = $_POST['lp-title'];
$content = $_POST['lpcontent'];
$notes = $_POST['lp-notes'];
if($mode=='edit'){
	$update=$wpdb->update($lpObj->tablename,array('title'=>sanitize_text_field(esc_attr($_POST['lp-title'])),'content'=>sanitize_text_field(esc_attr($_POST['lpcontent'])),'notes' => sanitize_text_field(esc_attr($_POST['lp-notes'])),'contentfor'=>sanitize_text_field(esc_attr($_POST['contentfor']))),array('id'=>intval($_REQUEST['lpid'])),array('%s','%s','%s','%s'));

	if($update){
 ?>
                                <div id="message">
                                    <p><span class='label label-success myAlert'><?php _e('Template Successfully Updated.','wplegalpages');?></span></p>
                                </div>
                                <?php
}else{
	echo "<span class='label label-danger myAlert'>Error Updating Template</span>";
}
}else{
$wpdb->insert($lpObj->tablename,
array('title'=>sanitize_text_field(esc_attr($_POST['lp-title'])),
'content'=>sanitize_text_field(esc_attr($_POST['lpcontent'])),
'notes' => sanitize_text_field(esc_attr($_POST['lp-notes']))),
array('%s','%s','%s'));
if($wpdb->insert_id){
 ?>
                                    <div id="message" class="updated">
                                        <p><span class="label label-success myAlert"><?php _e('Template Successfully Created.','wplegalpages');?></span></p>
                                    </div>
                                    <?php
}else{
	echo "<span class='label label-danger myAlert'>_e('Error Saving Template','wplegalpages');</span>";
}
}
	  endif;

	  $general = get_option('wpgattack_general');
	  $checked = 'checked="checked"'; $selected = 'selected="selected"';
?>
                                        <style type="text/css">
                                            .clear {
                                                clear: both;
                                            }

                                            #lp_generalid {
                                                padding: 5px 20px 20px 20px;
                                                width: 800px;
                                                float: left;
                                            }

                                            #lp_generalid_right {
                                                float: left;
                                                width: 280px;
                                                margin-left: 20px;
                                                margin-top: 20px;
                                                border-radius: 5px;
                                                -moz-border-radius: 5px;
                                                -webkit-border-radius: 5px;
                                                padding-bottom: 10px;
                                            }

                                            #lp_generalid p {
                                                font-size: 16px;
                                            }

                                            #lp_generalid input[type=text] {
                                                width: 800px;
                                                height: 30px;
                                                color: #666;
                                                font-size: 20px;
                                                padding: 3px 4px;
                                            }

                                            #lp_generalid input[type=submit] {
                                                width: 100px;
                                                height: 30px;
                                                color: #000;
                                                cursor: pointer;
                                                font-size: 20px;
                                                padding: 3px 4px;
                                            }

                                            #lp_generalid_right li {
                                                list-style: square;
                                                line-height: 20px;
                                                list-style-position: inside;
                                                padding-left: 10px;
                                            }

                                            #lp_generalid_right li span {
                                                font-size: 16px;
                                                cursor: pointer;
                                            }

                                            #lp_generalid p a {
                                                text-decoration: none;
                                            }

                                            #content p {
                                                width: 800px;
                                            }
                                            /*Bulk Delete CSS*/

                                            input#lp-bulkdel-1,
                                            input#lp-bulkdel-2 {
                                                margin-left: 0;
                                            }

                                            .bulk-action-select-box {
                                                padding: 5px 0;
                                            }
                                        </style>
                                        <!-- Script to Select and Deselect Multiple Checkboxes -->
                                        <script>
                                            jQuery(document).ready(function () {
                                                jQuery("#lp-bulkdel-1,#lp-bulkdel-2").click(function () {
                                                    if (this.checked) {
                                                        // Iterate each checkbox
                                                        jQuery(':checkbox').each(function () {
                                                            this.checked = true;
                                                        });
                                                    }
                                                    else {
                                                        jQuery(':checkbox').each(function () {
                                                            this.checked = false;
                                                        });
                                                    }
                                                });
                                            });
                                        </script>
                                        <h2 class="hndle title-head"> <?php _e('Available Templates','wplegalpages');?> </h2>
                                        <!-- Bulk Action Select Box at TOP-->
                                        <form method="post">
                                            <div class="bulk-action-select-box ">
                                                <select name="lp-select-action" id="lp-bulk-action-selector-top">
                                                    <option name="-1" selected="selected"><?php _e('Bulk Action','wplegalpages');?></option>
                                                    <option name="delete"><?php _e('Delete','wplegalpages');?></option>
                                                    <option name="clone"><?php _e('Clone','wplegalpages');?></option>
                                                </select>
                                                <input type="submit" name="lp-doaction" class="btn btn-primary" style="padding:3px 6px;" value="<?php _e('Apply','wplegalpages');?>">
                                                <br> </div>
                                            <table class="widefat fixed comments table table-striped">
                                                <thead>
                                                    <tr>
                                                        <th width="5%">
                                                            <input id="lp-bulkdel-1" type="checkbox"> </th>
                                                        <th width="5%"><?php _e('S.No.','wplegalpages');?></th>
                                                        <th width="30%"><?php _e('Template Title','wplegalpages');?></th>
                                                        <th width="20%"><?php _e('Shortcode','wplegalpages');?></th>
                                                        <th width="10%"><?php _e('Notes','wplegalpages');?></th>
                                                        <th width="15%"><?php _e('Action','wplegalpages');?></th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
	$result = $wpdb->get_results("select * from $lpObj->tablename");
	if( $result ) { ?>
                                                        <?php
            $count = 1;
            $class = '';

            foreach( $result as $res ) {
               ?>
                                                            <tr<?php echo $class; ?>>
                                                                <td>
                                                                    <input class="lp-del-single" name="check_list<?php echo $res->id;?>" value="<?php echo $count;?>" type="checkbox"> </td>
                                                                <td>
                                                                    <?php echo $count; ?>
                                                                </td>
                                                                <td>
                                                                    <?php echo $res -> title; ?>
                                                                </td>
                                                                <td>
                                                                    <?php echo "[wp-legalpage tid=$res->id]"; ?>
                                                                </td>
                                                                <td>
                                                                    <?php echo $res -> notes; ?>
                                                                </td>
                                                                <?php
                $nonce = wp_create_nonce( 'my-nonce' );

                $delurl=esc_url($baseurl).'/wp-admin/admin.php?page='.$page.'&lpid='.$res->id.'&mode=delete'.'&_wpnonce='.$nonce;
                ?>
                                                                    <td> <a href="<?php echo esc_url($baseurl);?>/wp-admin/admin.php?page=<?php echo $page;?>&lpid=<?php echo $res->id;?>&mode=edit#edit"><?php _e('Edit','wplegalpages');?></a> | <a href="javascript:void(0);" onclick="SetName('<?php echo esc_url($baseurl);?>/wp-admin/admin.php','<?php echo $page;?>','<?php echo $res->id;?>','<?php echo $res->title?>','clone','<?php echo $nonce;?>');"><?php _e('Clone','wplegalpages');?></a> | <a href="<?php echo $delurl; ?>" onclick="return confirm('Template will be permanently deleted. Are you sure you want to delete?')"><?php _e('Delete','wplegalpages');?></a></td>
                                                                    </tr>
                                                                    <?php
                $count++;
            }
            ?>
                                                                        <?php } else { ?>
                                                                            <tr>
                                                                                <td colspan="3"><?php _e('No posts yet','wplegalpages');?></td>
                                                                            </tr>
                                                                            <?php } ?>
                                                </tbody>
                                                <tfoot>
                                                    <tr>
                                                        <th width="5%">
                                                            <input id="lp-bulkdel-2" type="checkbox"> </th>
                                                        <th width="5%"><?php _e('S.No.','wplegalpages');?></th>
                                                        <th width="30%"><?php _e('Template Title','wplegalpages');?></th>
                                                        <th width="20%"><?php _e('Shortcode','wplegalpages');?></th>
                                                        <th width="10%"><?php _e('Notes','wplegalpages');?></th>
                                                        <th width="15%"><?php _e('Action','wplegalpages');?></th>
                                                    </tr>
                                                </tfoot>
                                            </table>
                                            <!-- Bulk Action Select Box at Bottom -->
                                            <div class="bulk-action-select-box">
                                                <select name="lp-select-action-2" id="lp-bulk-action-selector-bottom">
                                                    <option name="-1" selected="selected"><?php _e('Bulk Action','wplegalpages');?></option>
                                                    <option name="delete"><?php _e('Delete','wplegalpages');?></option>
                                                    <option name="clone"><?php _e('Clone','wplegalpages');?></option>
                                                </select>
                                                <input type="submit" name="lp-doaction-2" class="btn btn-primary" style="padding:3px 6px;" value="<?php _e('Apply','wplegalpages');?>">
                                                <br> </div>
                                        </form>
                                        <br/>
                                        <?php

    /*
    *  Variable Initializations
    */
    $selected_option = "";
    $checkedArray = array();
    $bulk_delete_url = array();
    $values_to_delete ="";

    /* Handle Form action when 'Bulk Action' select box is Set and
     * anyone of 'Apply' button is pressed.
    */
    if( isset($_POST['lp-doaction']) || isset($_POST['lp-doaction-2']) ){

        if( isset($_POST['lp-select-action']) ){
            if( $_POST['lp-select-action'] != "Bulk Action")
            $selected_option = $_POST['lp-select-action'];
        }
        if( isset($_POST['lp-select-action-2']) ){
            if( $_POST['lp-select-action-2'] != "Bulk Action")
            $selected_option = $_POST['lp-select-action-2'];
        }

        /*  $checkedArray Array holds all the post Ids
        *   which are selected.
        */

        foreach ($result as $res) {
                # code...
                if( isset( $_POST['check_list'.$res->id] ) ){
                    $checkedElement = $res->id;
                    array_push($checkedArray, $checkedElement);
                }
        }

        if( $selected_option == 'Delete' ) {
            $values_to_delete = implode(",", $checkedArray);
            ?>
                                            <script type="text/javascript">
                                                var confirm_msg = confirm('Are you sure to Want to Delete Selected Templates ?');
                                                var bulk_delete_url = "<?php echo esc_url($baseurl).'/wp-admin/admin.php?page='.$page.'&lpid='.$values_to_delete.'&mode=bulk_delete'.'&_wpnonce='.$nonce ?>";
                                                if (confirm_msg) {
                                                    location.href = bulk_delete_url;
                                                }
                                            </script>
                                            <?php
        }
        if( $selected_option == 'Clone' ) {
            echo "You selected Clone";
            $values_to_clone = implode(",", $checkedArray);
            ?>
                                                <script type="text/javascript">
                                                    var bulk_clone_url = "<?php echo esc_url($baseurl).'/wp-admin/admin.php?page='.$page.'&lpid='.$values_to_clone.'&mode=bulk_clone'.'&_wpnonce='.$nonce ?>";
                                                    location.href = bulk_clone_url;
                                                </script>
                                                <?php
        }
}
?>
                                                    <div class="postbox" style="width:850px;">
                                                        <?php $row='';?>
                                                            <?php if(isset($_REQUEST['mode']) && $_REQUEST['mode']=='edit' && isset($_REQUEST['lpid']))

	$row = $wpdb->get_row($wpdb->prepare('SELECT * from '.$lpObj->tablename.' where id= %d',$_REQUEST['lpid']));
	?>
                                                                <h3 class="hndle" style=" padding:7px 10px;"><a name="edit" style="text-decoration:none; cursor:pointer; font-size:20px;" ><?php if($mode=='edit')echo _e('Edit','wplegalpages');else _e('Create','wplegalpages');?><?php _e('Template','wplegalpages');?>:</a></h3>
                                                                <div id="lp_generalid">
                                                                    <form name="terms" method="post" enctype="multipart/form-data">
                                                                        <p>
                                                                            <input type="text" class="form-control myText" name="lp-title" id="lp-title" value="<?php echo $row?$row->title:'';?>" /> </p>
                                                                        <p><strong class="field_title"><?php _e('Notes','wplegalpages');?></strong></strong>
                                                                            <input type="text" class="form-control myText" name="lp-notes" id="lp-notes" value="<?php echo $row?$row->notes:'';?>" /> </p>
                                                                        <p>
                                                                            <div id="poststuff">
                                                                                <div id="<?php echo user_can_richedit() ? 'postdivrich' : 'postdiv'; ?>">
                                                                                   <?php wp_editor(html_entity_decode(stripslashes($row?$row->content:'')),'content'); ?>
                                                                                </div>
                                                                                <script type="text/javascript">
                                                                                    function sp_content_save() {
                                                                                        var obj = document.getElementById('lpcontent');
                                                                                        var content = document.getElementById('content');
                                                                                        tinyMCE.triggerSave(0, 1);
                                                                                        obj.value = content.value;
                                                                                    }
                                                                                </script>
                                                                                <textarea id="lpcontent" name="lpcontent" value="5" style="display:none" rows="10"></textarea>
                                                                            </div>
                                                                        </p>
                                                                        <p>
                                                                            <input type="hidden" name="contentfor" value="<?php echo $row?$row->contentfor:'';?>" />
                                                                            <input type="submit" class="btn btn-primary mybtn" onclick="sp_content_save();" name="lp-submit" value="<?php if($mode=='edit') _e('Edit','wplegalpages');else _e('Save','wplegalpages');?>" /> </p>
                                                                    </form>
                                                                </div>
                                                                <div class="clear"></div>
                                                    </div>
