<?php 
header("Access-Control-Allow-Origin: *");
//////////// Login Api /////////////
add_action( 'rest_api_init', 'register_api_hooks' );

function register_api_hooks() {
  register_rest_route(
    'recite', '/login/',
    array(
      'methods'  => 'POST',
      'callback' => 'login',
    )
  );
}

function login($request){
    $creds = array();
    $creds['user_login'] = $request["username"];
    $creds['user_password'] =  $request["password"];
    $creds['remember'] = true;
    $user = wp_signon( $creds, false );

    if ( is_wp_error($user) )
	{
       $return = array(
    	'message' => __( 'Email & Password Not Matched', 'textdomain' )
		 );
 
       wp_send_json_error( $return );
	}
	else
	{
	    $user_meta=get_userdata($user->ID);
			$return = array(
			'ID'      => $user->ID,
			'username'      => $user->user_login,
			'email'      => $user->user_email,
			'role'      => $user_meta->roles[0]
		);
		wp_send_json_success( $return );
	}
}


/////////////////// Register Api /////////////

add_action('rest_api_init', 'wp_rest_user_endpoints');
/**
 * Register a new user
 *
 * @param  WP_REST_Request $request Full details about the request.
 * @return array $args.
 **/
function wp_rest_user_endpoints($request) {
  /**
   * Handle Register User request.
   */
  register_rest_route('wp/v2', 'users/register', array(
    'methods' => 'POST',
    'callback' => 'wc_rest_user_endpoint_handler',
  ));
}
function wc_rest_user_endpoint_handler($request = null) {
  $response = array();
  $parameters = $request->get_json_params();
  $username = sanitize_text_field($parameters['username']);
  $first_name = sanitize_text_field($parameters['first_name']);
  $last_name = sanitize_text_field($parameters['last_name']);
  $email = sanitize_text_field($parameters['email']);
  $phone = sanitize_text_field($parameters['phone']);
  $dob = sanitize_text_field($parameters['dob']);
  $password = sanitize_text_field($parameters['password']);
  // $role = sanitize_text_field($parameters['role']);
  $error = new WP_Error();
  if (empty($username)) {
    $error->add(400, __("Username field 'username' is required.", 'wp-rest-user'), array('status' => 400));
    return $error;
  }
  if (empty($first_name)) {
    $error->add(400, __("First Name field 'first_name' is required.", 'wp-rest-user'), array('status' => 400));
    return $error;
  }
  if (empty($last_name)) {
    $error->add(400, __("Last Name field 'last_name' is required.", 'wp-rest-user'), array('status' => 400));
    return $error;
  }
  if (empty($email)) {
    $error->add(401, __("Email field 'email' is required.", 'wp-rest-user'), array('status' => 400));
    return $error;
  }
  if (empty($phone)) {
    $error->add(401, __("Phone field 'phone' is required.", 'wp-rest-user'), array('status' => 400));
    return $error;
  }
  if (empty($dob)) {
    $error->add(401, __("Date Of Birth field 'dob' is required.", 'wp-rest-user'), array('status' => 400));
    return $error;
  }
  if (empty($password)) {
    $error->add(404, __("Password field 'password' is required.", 'wp-rest-user'), array('status' => 400));
    return $error;
  }
  // if (empty($role)) {
  //  $role = 'subscriber';
  // } else {
  //     if ($GLOBALS['wp_roles']->is_role($role)) {
  //      // Silence is gold
  //     } else {
  //    $error->add(405, __("Role field 'role' is not a valid. Check your User Roles from Dashboard.", 'wp_rest_user'), array('status' => 400));
  //    return $error;
  //     }
  // }
  $user_id = username_exists($username);
  if (!$user_id && email_exists($email) == false) {
    $user_id = wp_create_user($username, $password, $email);
    if (!is_wp_error($user_id)) {
      // Ger User Meta Data (Sensitive, Password included. DO NOT pass to front end.)
      $user = get_user_by('id', $user_id);
      // $user->set_role($role);
      $user->set_role('author');
      update_user_meta( $user_id, 'first_name', $first_name );
      update_user_meta( $user_id, 'last_name', $last_name );
      update_user_meta( $user_id, 'phone', $phone );
      update_user_meta( $user_id, 'dob', $dob );
      // WooCommerce specific code
      if (class_exists('WooCommerce')) {
        $user->set_role('customer');
      }
      // Ger User Data (Non-Sensitive, Pass to front end.)
      $response['code'] = 200;
      $response['message'] = __("User '" . $username . "' Registration was Successful", "wp-rest-user");
    } else {
      return $user_id;
    }
  } else {
    $error->add(406, __("Email already exists, please try 'Reset Password'", 'wp-rest-user'), array('status' => 400));
    return $error;
  }
  return new WP_REST_Response($response, 123);
}



////////////////// Book API ////////////////

add_action( 'rest_api_init', 'my_booklists' );

function my_booklists() {
    register_rest_route( 'books', 'list', array(
                    'methods' => 'GET',
                    'callback' => 'custom_phrase',
                )
            );
}

function custom_phrase() {
    $posts_list = get_posts( array( 'post_type' => 'book','numberposts'=>-1 ) );
    $post_data = array();

    foreach( $posts_list as $posts) {
        $post_id = $posts->ID;
        $post_author = $posts->post_author;
        $recent_author = get_user_by( 'ID', $post_author );
        $post_title = $posts->post_title;
        $post_content = $posts->post_content;
        $post_excerpt = wp_trim_words( $posts->post_content, 20, '...' );
        $post_image = wp_get_attachment_image_src( get_post_thumbnail_id($post_id), 'full') ;

        /*$post_data[ $post_id ][ 'authorID' ] = $post_author;
        $post_data[ $post_id ][ 'bookID' ] = $post_id;
        $post_data[ $post_id ][ 'authorName' ] = $recent_author->display_name;;
        $post_data[ $post_id ][ 'title' ] = $post_title;
        $post_data[ $post_id ][ 'content' ] = $post_content;
        $post_data[ $post_id ][ 'excerpt' ] = $post_excerpt;
        $post_data[ $post_id ][ 'image' ] = $post_image[0];
        $post_data[ $post_id ][ 'audioURL' ] = get_post_meta($post_id,'bookaudio',true);
        $post_data[ $post_id ][ 'publication' ] = get_post_meta($post_id,'publication',true);*/
		
		$post_data[] = array(
                   'authorID' => $post_author,
                   'bookID' => $post_id,
			       'authorName' => $recent_author->display_name,
			       'title' => $post_title,
			       'content' => $post_content,
			       'excerpt' => $post_excerpt,
			       'image' => $post_image[0],
			       'audioURL' => get_post_meta($post_id,'bookaudio',true),
			       'publication' => get_post_meta($post_id,'publication',true)
			
         );

    }

    wp_reset_postdata();
    return rest_ensure_response( $post_data );
}

///////////// Get Book Through ID ///////////////////////

add_action( 'rest_api_init', 'my_booklistsbyid' );

function my_booklistsbyid() {
    register_rest_route( 'book', 'lists/(?P<id>\d+)', array(
                    'methods' => 'GET',
                    'callback' => 'custom_phrasebyid',
                )
            );
}

function custom_phrasebyid($data) {

    $id = $data['id'];
    $posts_list = get_posts( array( 'post_type' => 'book','p' => $id ) );
    $post_data = array();

    foreach( $posts_list as $posts) {
        $post_id = $posts->ID;
        $post_author = $posts->post_author;
        $recent_author = get_user_by( 'ID', $post_author );
        $post_title = $posts->post_title;
        $post_content = $posts->post_content;
        $post_excerpt = wp_trim_words( $posts->post_content, 20, '...' );
        $post_image = wp_get_attachment_image_src( get_post_thumbnail_id($post_id), 'full') ;

        /*$post_data[ $post_id ][ 'authorID' ] = $post_author;
        $post_data[ $post_id ][ 'bookID' ] = $post_id;
        $post_data[ $post_id ][ 'authorName' ] = $recent_author->display_name;;
        $post_data[ $post_id ][ 'title' ] = $post_title;
        $post_data[ $post_id ][ 'content' ] = $post_content;
        $post_data[ $post_id ][ 'excerpt' ] = $post_excerpt;
        $post_data[ $post_id ][ 'image' ] = $post_image[0];
        $post_data[ $post_id ][ 'audioURL' ] = get_post_meta($post_id,'bookaudio',true);
        $post_data[ $post_id ][ 'publication' ] = get_post_meta($post_id,'publication',true);*/
		
		$post_data[] = array(
                   'authorID' => $post_author,
                   'bookID' => $post_id,
			       'authorName' => $recent_author->display_name,
			       'title' => $post_title,
			       'content' => $post_content,
			       'excerpt' => $post_excerpt,
			       'image' => $post_image[0],
			       'audioURL' => get_post_meta($post_id,'bookaudio',true),
			       'publication' => get_post_meta($post_id,'publication',true)
			
         );

    }

    wp_reset_postdata();
    return rest_ensure_response( $post_data );
}



///////////// Get Book Through Author ///////////////////////

add_action( 'rest_api_init', 'my_booklistsbyauthorid' );

function my_booklistsbyauthorid() {
    register_rest_route( 'book', 'author/(?P<id>\d+)', array(
                    'methods' => 'GET',
                    'callback' => 'custom_phrasebyauthorid',
                )
            );
}

function custom_phrasebyauthorid($data) {

    
    $id = $data['id'];
    $posts_list = get_posts( array( 'post_type' => 'book','author' => $id,'numberposts'=>-1 ) );
    $post_data = array();

    foreach( $posts_list as $posts) {
        $post_id = $posts->ID;
        $post_author = $posts->post_author;
        $recent_author = get_user_by( 'ID', $post_author );
        $post_title = $posts->post_title;
        $post_content = $posts->post_content;
        $post_excerpt = wp_trim_words( $posts->post_content, 20, '...' );
        $post_image = wp_get_attachment_image_src( get_post_thumbnail_id($post_id), 'full') ;

        /*$post_data[ $post_id ][ 'authorID' ] = $post_author;
        $post_data[ $post_id ][ 'bookID' ] = $post_id;
        $post_data[ $post_id ][ 'authorName' ] = $recent_author->display_name;;
        $post_data[ $post_id ][ 'title' ] = $post_title;
        $post_data[ $post_id ][ 'content' ] = $post_content;
        $post_data[ $post_id ][ 'excerpt' ] = $post_excerpt;
        $post_data[ $post_id ][ 'image' ] = $post_image[0];
        $post_data[ $post_id ][ 'audioURL' ] = get_post_meta($post_id,'bookaudio',true);
        $post_data[ $post_id ][ 'publication' ] = get_post_meta($post_id,'publication',true);*/
		
		$post_data[] = array(
                   'authorID' => $post_author,
                   'bookID' => $post_id,
			       'authorName' => $recent_author->display_name,
			       'title' => $post_title,
			       'content' => $post_content,
			       'excerpt' => $post_excerpt,
			       'image' => $post_image[0],
			       'audioURL' => get_post_meta($post_id,'bookaudio',true),
			       'publication' => get_post_meta($post_id,'publication',true)
			
         );

    }

    wp_reset_postdata();
    return rest_ensure_response( $post_data );
}




///////////// Get Book Through Category ///////////////////////

add_action( 'rest_api_init', 'my_booklistsbycatid' );

function my_booklistsbycatid() {
    register_rest_route( 'book', 'category/(?P<id>\d+)', array(
                    'methods' => 'GET',
                    'callback' => 'custom_phrasebycategoryid',
                )
            );
}

function custom_phrasebycategoryid($data) {

    
    $id = $data['id'];

    $args = array(
        'post_type' => 'book',
        'numberposts'=>-1,
        'tax_query' => array(
            array(
                'taxonomy' => 'book-category',
                'field'    => 'term_id',
                'terms'    => $id
            )
        )
    );
    $posts_list = get_posts( $args );

    
    $post_data = array();

    foreach( $posts_list as $posts) {
        $post_id = $posts->ID;
        $post_author = $posts->post_author;
        $recent_author = get_user_by( 'ID', $post_author );
        $post_title = $posts->post_title;
        $post_content = $posts->post_content;
        $post_excerpt = wp_trim_words( $posts->post_content, 20, '...' );
        $post_image = wp_get_attachment_image_src( get_post_thumbnail_id($post_id), 'full') ;

        /*$post_data[ $post_id ][ 'authorID' ] = $post_author;
        $post_data[ $post_id ][ 'bookID' ] = $post_id;
        $post_data[ $post_id ][ 'authorName' ] = $recent_author->display_name;;
        $post_data[ $post_id ][ 'title' ] = $post_title;
        $post_data[ $post_id ][ 'content' ] = $post_content;
        $post_data[ $post_id ][ 'excerpt' ] = $post_excerpt;
        $post_data[ $post_id ][ 'image' ] = $post_image[0];
        $post_data[ $post_id ][ 'audioURL' ] = get_post_meta($post_id,'bookaudio',true);
        $post_data[ $post_id ][ 'publication' ] = get_post_meta($post_id,'publication',true);*/
		
		$post_data[] = array(
                   'authorID' => $post_author,
                   'bookID' => $post_id,
			       'authorName' => $recent_author->display_name,
			       'title' => $post_title,
			       'content' => $post_content,
			       'excerpt' => $post_excerpt,
			       'image' => $post_image[0],
			       'audioURL' => get_post_meta($post_id,'bookaudio',true),
			       'publication' => get_post_meta($post_id,'publication',true)
			
         );

    }

    wp_reset_postdata();
    return rest_ensure_response( $post_data );
}

/////////////////////// Get categories /////////


add_action( 'rest_api_init', 'gettaxnomie' );

function gettaxnomie() {
    register_rest_route( 'recite', 'category', array(
                    'methods' => 'GET',
                    'callback' => 'getcategories',
     )
    );
}

function getcategories()
{
    $terms = get_terms( array(
        'taxonomy' => 'book-category',
        'hide_empty' => false,
    ) );
    $post_data = array();


    foreach($terms as $term)
    {
       /*$post_data[$term->term_id]['termID'] =  $term->term_id;
       $post_data[$term->term_id]['name'] =  $term->name;
       $post_data[$term->term_id]['description'] =  $term->description;
       $post_data[$term->term_id]['count'] =  $term->count;*/
		
		$post_data[] = array(
		  'termID' => $term->term_id,
		  'name' => $term->name,
		  'description' => $term->description,
		  'count' => $term->count	
		);
		
    }
    return rest_ensure_response( $post_data );
}

////////////////// Get Authors ////////////////////

add_action( 'rest_api_init', 'getauthors' );

function getauthors() {
    register_rest_route( 'recite', 'authors', array(
        'methods' => 'GET',
        'callback' => 'getauthorslist',
     )
    );
}

function getauthorslist()
{
    $blogusers = get_users( array( 'role__in' => array( 'author' ) ) );
    $post_data = array();
    foreach ( $blogusers as $user ) {
        /*$post_data[$user->ID]['userID'] =  $user->ID;
        $post_data[$user->ID]['firstname'] =  $user->first_name;
        $post_data[$user->ID]['lastname'] =  $user->last_name;
        $post_data[$user->ID]['displayname'] =  $user->display_name;
        $post_data[$user->ID]['bio'] =  $user->description;
        $post_data[$user->ID]['email'] =  $user->user_email;
        $post_data[$user->ID]['phone'] =  get_user_meta($user->ID,'phone',true);
        $post_data[$user->ID]['dob'] =  get_user_meta($user->ID,'dob',true);
        $post_data[$user->ID]['image'] =  get_avatar_url( $user->ID,['size' => '300']);*/
		
		$post_data[] = array(
		  'userID' => $user->ID,
		  'firstname' => $user->first_name,
		  'lastname' => $user->last_name,
		  'displayname' => $user->display_name,
		  'bio' => $user->description,
		  'email' => $user->user_email,
		  'phone' => get_user_meta($user->ID,'phone',true),
		  'dob' => get_user_meta($user->ID,'dob',true),
		  'image' => get_avatar_url( $user->ID,['size' => '300'])
		);
    }
    return rest_ensure_response( $post_data );
}

/////////////// Adding Userwise Song /////////////////
add_action('rest_api_init', 'wp_add_lastsong');
function wp_add_lastsong() {
    register_rest_route( 'recite', 'lastsong', array(
        'methods' => 'POST',
        'callback' => 'savelastsong',
    )
    );
  }
  function savelastsong($request )
  {
     $userid = (int)$request['userId'];
     $lastsongid = (int)$request['lastSongId'];
     $playedupto = $request['playedUpto'];
     if(empty($lastsongid))
     {
      $return = array(
        'message' => __( 'Last song ID cannot be blank!', 'textdomain' )
       );
   
         wp_send_json_error( $return );
     }
     elseif(empty($playedupto))
     {
      $return = array(
        'message' => __( 'Upto played cannot be blank!', 'textdomain' )
       );
   
         wp_send_json_error( $return );
     }
     else
     {
     update_user_meta( $userid, 'lastSongId', $lastsongid );
     update_user_meta( $userid, 'playedUpto', $playedupto );

     $return = array(
			'success'      => 1
		);
		wp_send_json_success( $return );
  }
  }


  add_action( 'rest_api_init', 'getsonginfo' );

function getsonginfo() {
    register_rest_route( 'recite', 'songinfo/(?P<id>\d+)', array(
                    'methods' => 'GET',
                    'callback' => 'usersonginfo',
                )
      );    
}
function usersonginfo($request)
{
  $userid = $request['id'];
  $post_data = array();

  $post_data[] = array(
    'lastSongId' => get_user_meta($userid,'lastSongId',true),
    'playedUpto' => get_user_meta($userid,'playedUpto',true)
 );
 return rest_ensure_response( $post_data );
}
?>