<?php
defined( 'ABSPATH' ) or die( 'Direct access is not permitted' );
global $wpdb;
// Upload file
function upload_file($args){
  if($args['file']['name'] != ''){
    $uploadedfile = $args['file'];
    $upload_overrides = array( 'test_form' => false );
    $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
    $imageurl = array();
    if ($movefile && ! isset( $movefile['error'] ) ) {
       $imageurl["url"] = $movefile['url'];
       //$imageurl["url"] = $movefile['url'];
       $imageurl["status"] = true;
       //echo "url : ".$imageurl;
    } else {
       //echo $movefile['error'];
       $imageurl["status"] = false;
       $imageurl["error"] = $movefile['error'];
    }
  }

  return $imageurl;
}

function check_empty_file($args)
{
  $error["status"] = array();
  $error["status"] = false;
  if(empty($args["type_of_account"]) || empty($args["type_of_form"])){
    $error["status"] = true;
    $error["error"] = "Please select type of account and type of form ";
  }
  return $error;
}

if(isset($_POST['but_submit']) && $_POST['but_submit'] == 'Submit'){
  if(isset($_POST["image_url"]) && !empty($_POST["image_url"])){
    $imageurl["status"] = true;
    $imageurl["url"] = $_POST["image_url"];
  }else{
    $imageurl = upload_file($_FILES);
  }
  $check_data = check_empty_file($_POST);
  if($check_data["status"] || !$imageurl["status"]){
    echo "<script>location.replace('admin.php?page=list&error=1');</script>";
    //echo "<script>location.header('admin.php?page=list&error='".$error["error"]."');</script>";
    //$urlto ='admin.php?page=list&error='.$error["error"];
    //wp_redirect( $urlto ); 
  }elseif($imageurl["status"]){
    $image_url = $imageurl["url"];
    $type_of_account = $_POST['type_of_account'];
    $type_of_form = $_POST['type_of_form'];
    $slug = $_POST['slug'];
    $ordering = $_POST['ordering'];
    if($type_of_form=='Other'){
      $type_of_form = $_POST['type_of_form_other'];
    }
    if($type_of_account=='Other'){
       $type_of_account = $_POST['type_of_account_other'];
    }
    $date_time = date('Y-m-d H:i:s');
    $data ="INSERT INTO mr_download_form(type_of_account,type_of_form,slug,download_file_name,created_on,ordering) VALUES('$type_of_account','$type_of_form','$slug','$image_url','$date_time','$ordering')";
    $wpdb->query($data);
    echo "<script>location.replace('admin.php?page=list&msg=1');</script>";
  }
  
}

if(isset($_GET['action']) && $_GET['action']=="new" || $_GET['action']=="update"){
  $sql = "select type_of_account from mr_download_form group by type_of_account order by type_of_account";
  $results = $wpdb->get_results($sql);
  foreach ($results as $value) {
    $result[] = $value->type_of_account;
  }

  $sql_1 = "select type_of_form from mr_download_form group by type_of_form order by type_of_form";
  $results_1 = $wpdb->get_results($sql_1);
  foreach ($results_1 as $value) {
    $result_1[] = $value->type_of_form;
  }
}


if ($_GET['action']=="delete" && isset($_GET['del'])) {
    $del_id = $_GET['del'];
    $wpdb->query("DELETE FROM mr_download_form WHERE id='$del_id'");
    echo "<script>location.replace('admin.php?page=list');</script>";
}

if ($_GET['action']=="status" && isset($_GET['upt'])) {
    $upt = $_GET['upt'];
    $status = $_GET['status'];
    $wpdb->query("update mr_download_form set status ='$status'  WHERE id='$upt'");
    echo "<script>location.replace('admin.php?page=list&msg=2');</script>";
}

if(isset($_POST['but_submit']) && $_POST['but_submit'] == 'Update'){
    $id = $_POST['id'];
    $type_of_account = $_POST['type_of_account'];
    $type_of_form = $_POST['type_of_form'];
    $slug = $_POST['slug'];
    $ordering = $_POST['ordering'];
    $imageurl = upload_file($_FILES);
    if($imageurl["status"]){
      $image_url =$imageurl['url']; 
    }else{
      $image_url = $_POST['image_url'];
    }
    $update_query = "update mr_download_form set type_of_account ='$type_of_account',type_of_form ='$type_of_form',slug= '$slug',download_file_name ='$image_url',ordering = '$ordering' WHERE id=".$id;  
    $wpdb->query($update_query);

    echo "<script>location.replace('admin.php?page=list&msg=1');</script>";
}

function msg_print($msg){
  $array = array(1=>"Record Updated",2=>"Record Added",3=>"Record Added");
  return $array[$msg];
}
if(isset($_GET['msg'])){
  echo msg_print($_GET['msg']);  
} 

//$result = array('Resident Individual' ,'NRI' ,'HUF' ,'Trust' ,'Corporate' ,'LLP' ,'Resident but Foreign National' ,'Partnership');
//$results_1 = array('Acount opening','Kotak Closure','Part Redemption ','KYC Change ','Kotak Add Nominee');
?>


<!-- Form -->
<?php if(isset($_GET['action']) && $_GET['action']=="new"){?>
<h1 class="wp-heading-inline">Add Forms</h1>
<table class="form-table">      
  <form method='post' action='' name='myform' enctype='multipart/form-data'>
    <tr class="form-field term-name-wrap">
      <th scope="row"><label for="name">Type of Form</label></th>
      <td>
        <select name="type_of_form" id="type_of_form" class="postform required">
              <option value="">Select Type of Form</option>
                  <?php
                  foreach( $result_1 as $value ) { ?>
                    <option value="<?php echo $value; ?>"><?php echo $value; ?></option>
                  <?php
                  }
                ?>
               <option value="Other">Other</option> 
         </select>
         <div id="type_of_form_div">
            <input name="type_of_form_other" id="type_of_form_other" type="text" value="" size="40" placeholder="Please enter other value">
         <div>
      </td>
    </tr>
    <tr class="form-field term-name-wrap">
      <th scope="row"><label for="name">Select Type of Account</label></th>
      <td>
          <select name="type_of_account" id="type_of_account" class="postform required">
              <option value="">Select Type of Account</option>
                  <?php
                  foreach( $result as $value ) { ?>
                    <option value="<?php echo $value; ?>"><?php echo $value; ?></option>
                  <?php
                  }
                ?>
                <option value="Other">Other</option>
         </select>
         <div id="type_of_account_div">
            <input name="type_of_account_other" id="type_of_account_other" type="text" value="" size="40" placeholder="Please enter other value">
         <div>
      </td>
    </tr>
    <tr class="form-field term-slug-wrap">
      <th scope="row"><label for="name">Slug (URL Name)</label></th>
      <td>
          <input name="slug" id="tag-slug" type="text" value="" size="20">
      </td>
    </tr>
    <tr class="form-field term-name-wrap">
        <th scope="row"><label for="name">Select File Path</label></th>
        <td><input type="text" name="image_url" id="image_url" value=""></a>
        </td>
    </tr>
     <!-- <tr class="form-field term-name-wrap">
          <th scope="row">Or</td>
      </tr>
      <tr class="form-field term-name-wrap">
        <th scope="row"><label for="name">Upload file</label> <input type="button" class="upload_image_button" name="Select Image" value="Select Image">
        </th>
        <td><input type='file' name='file'  class="upload_image_button"></td>
      </tr>
    <tr> -->
          <th scope="row"><label for="name">Ordering</label></th>
          <td>
              <input name="ordering" id="ordering" type="number" max="100" min="0" size="10" value="<?php echo $ordering?>">
          </td>
    </tr>
    <tr class="form-field term-name-wrap">
      <td>&nbsp;</td>
      <td><input type='submit' class='button button-primary' name='but_submit' value='Submit'></td>
    </tr>
 
</form>
</table>
<?php } elseif(isset($_GET['action']) && $_GET['action']=="update"){ 
        $upt_id = $_GET['upt'];
        $new_result = $wpdb->get_results("SELECT * FROM mr_download_form WHERE id='$upt_id'");
        foreach($new_result as $print) {
          $id = $print->id;
          $type_of_form = $print->type_of_form;
          $type_of_account = $print->type_of_account;
          $download_file_name = $print->download_file_name;
          $slug = $print->slug;
          $ordering = $print->ordering;
        }
  ?>
<table class="form-table"> 
  <form method='post' action='' name='myform' enctype='multipart/form-data'>
    <input type="hidden" name="id" id="id" value="<?php echo $id?>">
    <input type="hidden" name="action" id="action" value="update">
      <tr class="form-field term-name-wrap">
        <th scope="row"><label for="name">Type of Form</label></th>
        <td>
          <select name="type_of_form" id="type_of_form" required>
                <option value="">Select Type of Form</option>
                    <?php
                    foreach($result_1 as $value ) { ?>
                      <option value="<?php echo $value; ?>" <?php if($type_of_form == $value){?>selected="selected"<?php } ?> ><?php echo $value; ?></option>
                    <?php
                    }
                  ?>
           </select>
        </td>
      </tr>
      <tr class="form-field term-name-wrap">
        <th scope="row"><label for="name">Select Type of Account</label></th>
        <td>
            <select name="type_of_account" id="type_of_account" required>
                <option value="">Select Type of Account</option>
                    <?php
                    foreach( $result as $value ) { ?>
                      <option value="<?php echo $value; ?>" <?php if($type_of_account == $value){?>selected="selected"<?php } ?>><?php echo $value; ?></option>
                    <?php
                    }
                  ?>
           </select>
        </td>
      </tr>
      <tr class="form-field term-slug-wrap">
          <th scope="row"><label for="name">Slug (URL Name)</label></th>
          <td>
              <input name="slug" id="tag-slug" type="text" value="<?php echo $slug?>" size="40">
          </td>
      </tr>
     <tr class="form-field term-name-wrap">
        <th scope="row"><label for="name">Select File Path</label></th>
        <td><input type="text" name="image_url" id="image_url" value="<?php echo $download_file_name?>"></a>
        </td>
      </tr>
      <!--<tr class="form-field term-name-wrap">
          <th scope="row">Or</td>
        </tr> 
        <tr class="form-field term-name-wrap">
          <th scope="row"><label for="name">Upload file</label>
          </th>
          <td><input type='file' name='file'value=""><a href="<?php echo $download_file_name; ?>">Upload File</a>
          </td>
        </tr>
      -->

      <tr>
          <th scope="row"><label for="name">Ordering</label></th>
          <td>
              <input name="ordering" id="ordering" type="number" max="100" min="0" size="10" value="<?php echo $ordering?>">
          </td>
      </tr>

      
      <tr>
        <td>&nbsp;</td>
        <td><input type='submit' class='button button-primary' name='but_submit' value='Update'></td>
      </tr>
  </form>
</table>
<?php  } elseif(isset($_GET['action']) && $_GET['action']=="view"){ 
        $upt_id = $_GET['upt'];
        $new_result = $wpdb->get_results("SELECT * FROM mr_download_form WHERE id='$upt_id'");
        foreach($new_result as $print) {
          $id = $print->id;
          $type_of_form = $print->type_of_form;
          $type_of_account = $print->type_of_account;
          $download_file_name = $print->download_file_name;
          $slug = $print->slug;
          $ordering = $print->ordering;
       }   ?>
<h1 class="wp-heading-inline">View Forms Details</h1>
<div class="wrap">

  <a href='admin.php?page=list' class="page-title-action">Form List</a>       
  <table class="form-table"> 
        <tr class="form-field term-name-wrap">
          <th scope="row"><label for="name">Type of Form</label></th>
          <td><?php echo $type_of_form; ?></td>
        </tr>
        <tr class="form-field term-name-wrap">
          <th scope="row"><label for="name">Select Type of Account</label></th>
          <td><?php echo $type_of_account; ?></td>
        </tr>
        <tr class="form-field term-slug-wrap">
            <th scope="row"><label for="name">Slug (URL Name)</label></th>
            <td><?php echo $slug; ?></td>
        </tr>
        <tr class="form-field term-name-wrap">
          <th scope="row"><label for="name">Select File Path</label></th>
          <td><a href="<?php echo $download_file_name; ?>">Download File</a></td>
        </tr>
        <tr>
            <th scope="row"><label for="name">Ordering</label></th>
            <td><?php echo $ordering?></td>
        </tr>
  </table>
</div>

<?php  }else{
    require_once('listing.php' );
  ?>
      
<?php } ?>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>  
<script type="text/javascript">
  $("#type_of_form_div").hide();
  $("#type_of_account_other").hide();

  $("#type_of_form").change(function(){
    $("#type_of_form_div").hide();
    if($(this).val()=='Other'){
      $("#type_of_form_div").show();
    }
  });
  $("#type_of_account").change(function(){
    $("#type_of_account_other").hide();
    if($(this).val()=='Other'){
      $("#type_of_account_other").show();
    }
  });

  $('.upload_image_button').click(function() {
    var send_attachment_bkp = wp.media.editor.send.attachment;
    var button = $(this);
    wp.media.editor.send.attachment = function(props, attachment) {
        $(button).parent().prev().attr('src', attachment.url);
        $(button).prev().val(attachment.id);
        wp.media.editor.send.attachment = send_attachment_bkp;
    }
    wp.media.editor.open(button);
    return false;
 });   

</script>