<?php
define("API_URL", "api-tbc/v1");

function create_custom_post_tbc() { 
  $args = array(
        'label'             => 'tbc',
        'taxonomies'            => array( 'category', 'post_tag' ),
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array( 'slug' => 'tbc' ),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => null,
        'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ),
    );
  register_post_type( 'tbc', $args );
}
add_action( 'init', 'create_custom_post_tbc' );

// Get list tbc
//https://tbc.herramientatradecolsubsidio.com/tbc/wp/wp-json/api-tbc/v1/tbc/list
function getListTbc($request){
    $args = [
        'posts_per_page'    => $request['limit'],
        'paged' => $request['page'],
        'sort_order'  => 'desc',
        'post_type'   => 'tbc',
        'post_status' => 'publish',
    ];

    // use WP_Query to get the results with pagination
    $query = new WP_Query( $args ); 

    // if no posts found return 
    if( empty($query->posts) ){
        return new WP_Error( 'no_posts', __('No post found'), array( 'status' => 404 ) );
    }
     
    // set max number of pages and total num of posts
    $max_pages = $query->max_num_pages;
    $total = $query->found_posts;

    $posts = $query->posts;

    // prepare data for output
    $controller = new WP_REST_Posts_Controller('post');

    $index = 0;
    $data=[];
    foreach ( $posts as $post ) {
        $response = $controller->prepare_item_for_response( $post, $request );

        $data["data"][$index]  = $controller->prepare_response_for_collection( $response );
        $data["data"][$index]["custom_fields"] = get_fields($response->ID);
        $index+=1;
    }

    $data['total'] = $total;
    $data['totalPages'] = $max_pages;

    return $data;

}
function limpiarCadena($text){
    $cadena = trim(preg_replace('/[^A-Za-z0-9-\*\.]+/', '', $text));
    return $cadena ;
}
//https://tbc.herramientatradecolsubsidio.com/tbc/wp/wp-json/api-tbc/v1/usuario/autenticar
function usuarioAutenticar($req) { 
    
    global $wpdb;
    $wpdb_prefix = $wpdb->prefix;
    $wpdb_tablename = $wpdb_prefix.'users';
    $login = limpiarCadena($req['login']);
    $password = limpiarCadena($req['password']);
    $sqlQ="SELECT ID FROM ".$wpdb_tablename." WHERE user_login = '".$login."' and user_pass = '".$password."'";
    $result = $wpdb->get_results($sqlQ); 
    $retorno = 1;
    if ($result == false){
        $retorno = 0;
    }       

    $res = new WP_REST_Response($retorno);
    $res->set_status(200);

    return ['result' => $res];
}

//https://tbc.herramientatradecolsubsidio.com/tbc/wp/wp-json/api-tbc/v1/usuario/crear
function usuarioCrear($req) { 
    global $wpdb;
    $wpdb_prefix = $wpdb->prefix;
    $wpdb_tablename = $wpdb_prefix.'usuario';
    $sql = "INSERT INTO ".$wpdb_tablename."(`nombres`, `apellidos`, `tipo_documento`, `num_documento`, `email`, `celular`, `telefono`, `extension_telefono`, `nombre_empresa`, `nit`, `digito_verificacion`, `cargo`, `area`, `uuid`, `activo`, `habeas_data`) values ('".$req['nombres']."', '".$req['apellidos']."', '".$req['tipo_documento']."', '".$req['num_documento']."', '".$req['email']."', '".$req['celular']."', '".$req['telefono']."', '".$req['extension_telefono']."', '".$req['nombre_empresa']."', '".$req['nit']."', '".$req['digito_verificacion']."', '".$req['cargo']."', '".$req['area']."', '".$req['uuid']."', '".$req['activo']."', '".$req['habeas_data']."')";
    return $wpdb->query($sql);
    
}
//https://tbc.herramientatradecolsubsidio.com/tbc/wp/wp-json/api-tbc/v1/usuario/modificar
function usuarioModificar($req) { 
    global $wpdb;
    $wpdb_prefix = $wpdb->prefix;
    $wpdb_tablename = $wpdb_prefix.'usuario';
    $sql = "UPDATE ".$wpdb_tablename." SET `nombres`= '".$req['nombres']."', `apellidos` = '".$req['apellidos']."', `tipo_documento` = '".$req['tipo_documento']."', `num_documento` = '".$req['num_documento']."', `email` = '".$req['email']."', `celular` = '".$req['celular']."', `telefono` = '".$req['telefono']."', `extension_telefono` = '".$req['extension_telefono']."', `nombre_empresa` = '".$req['nombre_empresa']."', `nit` = '".$req['nit']."', `digito_verificacion` = '".$req['digito_verificacion']."', `cargo` = '".$req['cargo']."', `area` = '".$req['area']."', `uuid` = '".$req['uuid']."', `activo` = '".$req['activo']."', `habeas_data` = '".$req['habeas_data']."' where `id` = '".$req['id']."'";
    return $wpdb->query($sql);
}
//https://tbc.herramientatradecolsubsidio.com/tbc/wp/wp-json/api-tbc/v1/usuario/eliminar
function usuarioEliminar($req) { 
    global $wpdb;
    $wpdb_prefix = $wpdb->prefix;
    $wpdb_tablename = $wpdb_prefix.'usuario';
    return $wpdb->delete( $wpdb_tablename, array( 'id' => $req['id'] ) );
}

//https://tbc.herramientatradecolsubsidio.com/tbc/wp/wp-json/api-tbc/v1/usuario/consultar
function usuarioConsultar($req) { 
    global $wpdb;
    $wpdb_prefix = $wpdb->prefix;
    $wpdb_tablename = $wpdb_prefix.'usuario';
    $sqlQ="SELECT * FROM ".$wpdb_tablename." WHERE email = '".$req['email']."' LIMIT 1" ;
    $result = $wpdb->get_results($sqlQ); 
    
    $res = new WP_REST_Response($response);
    $res->set_status(200);

    return ['result' => $result];
}

// Get Custom Type TBC

//https://tbc.herramientatradecolsubsidio.com/tbc/wp/wp-json/api-tbc/v1/tbc/per_page
function blog_get_TBC_per_page($request){
    $args = [
        'posts_per_page'    => $request['limit'],
        'paged' => $request['page'],
        'sort_order'  => 'desc',
        'post_type'   => 'tbc',
        'post_status' => 'publish',
    ];

    // use WP_Query to get the results with pagination
    $query = new WP_Query( $args ); 

    // if no posts found return 
    if( empty($query->posts) ){
        return new WP_Error( 'no_posts', __('No post found'), array( 'status' => 404 ) );
    }
     
    // set max number of pages and total num of posts
    $max_pages = $query->max_num_pages;
    $total = $query->found_posts;

    $posts = $query->posts;

    // prepare data for output
    $controller = new WP_REST_Posts_Controller('post');

    $index = 0;
    $data=[];
    foreach ( $posts as $post ) {
        $response = $controller->prepare_item_for_response( $post, $request );

        $data["data"][$index]  = $controller->prepare_response_for_collection( $response );
        $data["data"][$index]["custom_fields"] = get_fields($response->ID);
        $index+=1;
    }

    $data['total'] = $total;
    $data['totalPages'] = $max_pages;

    return $data;

}

// Get Custom Type TBC by Id
//https://tbc.herramientatradecolsubsidio.com/tbc/wp/wp-json/api-tbc/v1/tbc/by_id/(?P<id>\w+)
function blog_get_TBC_id(WP_REST_Request $request){
    $param = $request->get_url_params();

    $args = [
        'p'           => $param['id'],
        'post_type'   => 'tbc',
        'post_status' => 'publish',
    ];

    $pages = get_posts($args);
    foreach ($pages as $page) {
        $data["ID"]          = $page->ID;
        $data['post_status'] = $page->post_status;
        $data['post_author'] = $page->post_author;
        $data['post_type']   = $page->post_type;
        // $data['post_title']  = $page->post_title;
        $data['categories']  = $page->categories;

        // get custom fields
        $data['custom_fields'] = get_fields($page->ID);

    }

    return $data;
}
//https://tbc.herramientatradecolsubsidio.com/tbc/wp/wp-json/api-tbc/v1/tbc/by_slug/(?P<id>[a-zA-Z0-9-]+)
function blog_get_TBC_id_by_slug ( WP_REST_Request $request) {
    $param = $request->get_url_params();

    $args = [
        'name'           => $param['id'],
        'post_type'   => 'tbc',
        'post_status' => 'publish',
    ];

    $pages = get_posts($args);
    foreach ($pages as $page) {
        $data["ID"]          = $page->ID;
        $data['post_status'] = $page->post_status;
        $data['post_author'] = $page->post_author;
        $data['post_content'] = $page->post_content;
        $data['post_type']   = $page->post_type;
        // $data['post_title']  = $page->post_title;
        $data['categories']  = get_the_category($page->ID);
        $data['custom_fields'] = get_fields($page->ID);

    }

    return $data;
}
//https://tbc.herramientatradecolsubsidio.com/tbc/wp/wp-json/api-tbc/v1/tbc/by_category_slud
function blog_get_TBC_Slug_by_category ($request) {

    $args = [
        // 'offset' => $request['offset'],
        // 'numberposts' => $request['limit'],
        'category_name' => $request['slug'],
        'posts_per_page'    => $request['limit'],
        'paged' => $request['page'],
        'sort_order'  => 'desc',
        'post_type'   => 'tbc',
        'post_status' => 'publish',
    ];

    // use WP_Query to get the results with pagination
    $query = new WP_Query( $args ); 

    // if no posts found return 
    if( empty($query->posts) ){
        return new WP_Error( 'no_posts', __('No post found'), array( 'status' => 404 ) );
    }
     
    // set max number of pages and total num of posts
    $max_pages = $query->max_num_pages;
    $total = $query->found_posts;

    $posts = $query->posts;

    // prepare data for output
    $controller = new WP_REST_Posts_Controller('post');

    $index = 0;
    $data=[];
    foreach ( $posts as $post ) {
        $response = $controller->prepare_item_for_response( $post, $request );
        
        $data["data"][$index] = $controller->prepare_response_for_collection( $response );  
        $data["data"][$index]["custom_fields"] = get_fields($response->ID);
        $index+=1;
    }

    $data['total'] = $total;
    $data['totalPages'] = $max_pages;

    return $data;
}




function blog_get_categories()
{
    $args = [
        'orderby' => 'name',
        'order'   => 'ASC',
        'parent' => 0
    ];

    $data = [];
    $index = 0;
    $categories = get_categories($args);
    foreach ($categories as $ca) {
        // $data[$index]['fields'] = $ca;

        $data[$index]['id'] = $ca->cat_ID;
        $data[$index]['name'] = $ca->name;
        $data[$index]['slug'] = $ca->slug;
        $data[$index]['parent'] = $ca->parent; 
        $data[$index]['description'] = $ca->description; 
        $data[$index]["banner_categorias_desktop"] = get_field('banner_categorias_desktop',$ca->taxonomy . '_' . $ca->term_id);
        $data[$index]["banner_categorias_mobile"] = get_field('banner_categorias_mobile',$ca->taxonomy . '_' . $ca->term_id);

        $children = get_categories(['parent'=>$ca->term_id]);

        $i = 0;
        foreach ($children as $item) {
            $data[$index]['child'][$i]['id'] = $item->cat_ID;
            $data[$index]['child'][$i]['name'] = $item->name;
            $data[$index]['child'][$i]['slug'] = $item->slug;
            $data[$index]['child'][$i]['parent'] = $item->parent;
            $data[$index]['child'][$i]['description'] = $item->description; 
            $data[$index]['child'][$i]["banner_categorias_desktop"] = get_field('banner_categorias_desktop',$ca->taxonomy . '_' . $item->term_id);
            $data[$index]['child'][$i]["banner_categorias_mobile"] = get_field('banner_categorias_mobile',$ca->taxonomy . '_' . $item->term_id);
            $i+=1;
        }
        
        $index+=1;
    }

    return $data;
}

add_action('rest_api_init', function () {   

    //inicio del crud
    register_rest_route( API_URL, '/usuario/crear', array(
        'methods' => 'POST',
        'callback' => 'usuarioCrear'
    ));
    register_rest_route( API_URL, '/usuario/modificar', array(
        'methods' => 'POST',
        'callback' => 'usuarioModificar'
    ));
    register_rest_route( API_URL, '/usuario/consultar', array(
        'methods' => 'POST',
        'callback' => 'usuarioConsultar'
    ));
    register_rest_route( API_URL, '/usuario/eliminar', array(
        'methods' => 'POST',
        'callback' => 'usuarioEliminar'
    ));
    //fin del crud

    register_rest_route( API_URL, '/usuario/autenticar', array(
          'methods' => 'POST',
          'callback' => 'usuarioAutenticar'
    ));
    
    register_rest_route(API_URL, '/tbc/list', array(
        'methods'  => 'GET',
        'callback' => 'getListTbc',
    ));    
    
    register_rest_route(API_URL, '/tbc/by_id/(?P<id>\w+)', array(
        'methods'  => 'GET',
        'callback' => 'blog_get_TBC_id',
    ));
      
    register_rest_route(API_URL, '/tbc/by_category_slug', [
        'methods'  => 'GET',
        'callback' => 'blog_get_TBC_Slug_by_category',
    ]);    
      
    register_rest_route(API_URL, '/tbc/by_slug/(?P<id>[a-zA-Z0-9-]+)', [
        'methods'  => 'GET',
        'callback' => 'blog_get_TBC_id_by_slug',
    ]);    
    
    register_rest_route(API_URL, '/tbc/per_page', array(
        'methods'  => 'GET',
        'callback' => 'blog_get_TBC_per_page',
    ));
       
    
    register_rest_route(API_URL, '/tbc/categories', array(
        'methods'  => 'GET',
        'callback' => 'blog_get_categories',
    ));

});

?>