<?php
defined( 'ABSPATH' ) or die( 'Direct access is not permitted' );
global $wpdb;
$table_name = $wpdb->prefix."custody_icici_forms";
// 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["status"] = true;
    } else {
       $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"];
  }
  $check_data = check_empty_file($_POST);
  
  if($check_data["status"] || !$imageurl["status"]){
    echo "<script>location.replace('admin.php?page=custodylist&error=1');</script>";
  }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 $table_name (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=custodylist&msg=1');</script>";
  }
  
}

if(isset($_GET['action']) && $_GET['action']=="new" || $_GET['action']=="update" || $_GET['action']=="ETOF" || $_GET['action']=="ETOA"){
  $sql = "select type_of_account from $table_name 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 $table_name 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 $table_name WHERE id='$del_id'");
    echo "<script>location.replace('admin.php?page=custodylist');</script>";
}

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

if(isset($_POST['but_submit']) && $_POST['but_submit'] == 'Update' && isset($_POST['action'])){

    if($_POST['action'] == 'update_main'){
      $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 $table_name 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=custodylist&msg=1');</script>";
    }elseif($_POST['action'] == 'update_tof'){
       if($_POST['type_of_form'] && trim($_POST['type_of_form_other'])){
         $type_of_form_other = trim($_POST['type_of_form_other']);
         $type_of_form =$_POST['type_of_form'];
         $wpdb->query("update $table_name set type_of_form ='$type_of_form_other'  WHERE type_of_form='$type_of_form'");
         echo "<script>location.replace('admin.php?page=custodylist&msg=4');</script>";
        }
    }elseif($_POST['action'] == 'update_toa'){
       if($_POST['type_of_account'] && trim($_POST['type_of_account_other'])){
         $type_of_account_other = trim($_POST['type_of_account_other']);
         $type_of_account =$_POST['type_of_account'];
         $wpdb->query("update $table_name set type_of_account ='$type_of_account_other'  WHERE type_of_account='$type_of_account'");
         echo "<script>location.replace('admin.php?page=custodylist&msg=4');</script>";
        }
    }
}

function msg_print($msg){
  $array = array(1=>"Record Updated",2=>"Record Updated",3=>"Record Added",4=>"Updated Type for Form Details",5=>"Record Updated");
  return $array[$msg];
}
if(isset($_GET['msg'])){
  echo msg_print($_GET['msg']);  
} 
?>
<!-- Form -->
<?php if(isset($_GET['action']) && $_GET['action']=="new"){
  include_once('add.php' );
} elseif(isset($_GET['action']) && $_GET['action']=="update"){ 
        $upt_id = $_GET['upt'];
        $query ="SELECT * FROM $table_name WHERE id='$upt_id'";
        $new_result = $wpdb->get_results($query);
        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_main">
      <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>
          <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 $table_name 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;
       }
  include_once('view.php');
}elseif(isset($_GET['action']) && $_GET['action']=="ETOF"){ 
   include_once('type_of_form.php');     
  
}elseif(isset($_GET['action']) && $_GET['action']=="ETOA"){ 
   include_once('type_of_account.php');    
}else{
  require_once('listing.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>