<?php
   /*
   Plugin Name: Raumgleiter Knowledge Base
   Plugin URI: http://raumgleiter.com
   description: >-
  a plugin that simplifies adjusting and extending wedocs
   Version: 0.1
   Author: Raumgleiter AG
   Author URI: http://raumgleiter.com
   License: All rights reserved
   */

   include "functions.php";

   class RG_Knowledge_Base{
     public function __construct() {
         add_action( 'wp_ajax_add_tutorial', array( $this, 'add_tutorial') );
         add_action( 'wp_ajax_nopriv_add_tutorial', array( $this, 'add_tutorial' ) );

         add_action( 'wp_enqueue_scripts', array( $this, 'rg_enqueue') );

         add_action( 'wp_enqueue_scripts', [ $this, 'register_scripts' ], 9 );
     }

	   public function register_scripts() {
		   // All styles goes here
		   wp_register_style( 'rg-knowledge-base', plugins_url( 'rg-knowledge-base/css/frontend.css' ) );
		   wp_enqueue_style( 'rg-knowledge-base' );
	   }

     public function rg_enqueue() {
         wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js',
          __FILE__ ), array('jquery') );
         wp_localize_script( 'ajax-script', 'rg_client',
         array('ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
     }

     public function add_tutorial() {

  		 $title  = isset( $_POST['title'] ) ? sanitize_text_field( $_POST['title'] ) : 'New Tutorial';
  		 $status = isset( $_POST['status'] ) ? sanitize_text_field( $_POST['status'] ) : 'draft';
  		 $parent = isset( $_POST['parent'] ) ? absint( $_POST['parent'] ) : 0;
  		 $order  = isset( $_POST['order'] ) ? absint( $_POST['order'] ) : 0;

  		 $status           = 'publish';
  		 $post_type_object = get_post_type_object( 'docs' );

  		 if ( ! current_user_can( $post_type_object->cap->publish_posts ) ) {
  			 $status = 'pending';
  		 }

  		 $post_id = wp_insert_post( [
  			 'post_title'  => $title,
  			 'post_type'   => 'docs',
  			 'post_status' => $status,
  			 'post_parent' => $parent,
  			 'post_author' => get_current_user_id(),
  			 'menu_order'  => $order,
  		 ] );

  		 if(!is_wp_error($post_id)){
  			 //the post is valid
  			 echo get_permalink($post_id);

  //			 wp_send_json_success( [
  //				 'post' => [
  //					 'id'     => $post_id,
  //					 'title'  => stripslashes( $title ),
  //					 'status' => $status,
  //					 'caps'   => [
  //						 'edit'   => current_user_can( $post_type_object->cap->edit_post, $post_id ),
  //						 'delete' => current_user_can( $post_type_object->cap->delete_post, $post_id ),
  //					 ],
  //				 ],
  //				 'child' => [],
  //			 ] );
  		 }else{
  			 //there was an error in the post insertion,
  			 echo $post_id->get_error_message();

  			 wp_send_json_error();
  		 }

       // Don't forget to stop execution afterward.
       wp_die();
     }
   }

   	$plugin = new RG_Knowledge_Base();
?>
