<?php
/**
 * Compatibilidad con funciones WordPress restantes.
 */

function is_admin() {
	return JB_App::is_admin();
}

function is_singular( $type = '' ) {
	return JB_App::current_post() !== null;
}

function get_post( $post = null ) {
	if ( null === $post ) {
		return JB_App::current_post();
	}
	if ( is_numeric( $post ) ) {
		return JB_App::current_post();
	}
	return $post;
}

function have_posts() {
	if ( ! isset( $GLOBALS['jb_the_query'] ) ) {
		$GLOBALS['jb_the_query'] = array(
			'current' => -1,
			'count'   => JB_App::current_post() ? 1 : 0,
		);
	}
	$q = &$GLOBALS['jb_the_query'];
	return ( $q['current'] + 1 ) < $q['count'];
}

function the_post() {
	if ( isset( $GLOBALS['jb_the_query'] ) ) {
		$GLOBALS['jb_the_query']['current']++;
	}
}

function wp_reset_postdata() {
	unset( $GLOBALS['jb_the_query'] );
}

function get_queried_object_id() {
	$post = JB_App::current_post();
	return $post ? (int) $post->ID : 0;
}

function get_header( $name = null ) {
	// El layout standalone maneja el header.
}

function get_footer( $name = null ) {
	// El layout standalone maneja el footer.
}

function body_class( $class = '' ) {
	$classes = apply_filters( 'body_class', array() );
	if ( $class ) {
		$classes[] = $class;
	}
	echo 'class="' . esc_attr( implode( ' ', $classes ) ) . '"';
}

function add_shortcode( $tag, $callback ) {
	JB_App::add_shortcode( $tag, $callback );
}

function has_shortcode( $content, $tag ) {
	return str_contains( (string) $content, '[' . $tag );
}

function esc_html_e( $text, $domain = 'default' ) {
	echo esc_html( $text );
}

function esc_attr_e( $text, $domain = 'default' ) {
	echo esc_attr( $text );
}

function __( $text, $domain = 'default' ) {
	return $text;
}

function _e( $text, $domain = 'default' ) {
	echo esc_html( $text );
}

function esc_html__( $text, $domain = 'default' ) {
	return esc_html( $text );
}

function esc_attr__( $text, $domain = 'default' ) {
	return esc_attr( $text );
}

function _n( $single, $plural, $number, $domain = 'default' ) {
	return (int) $number === 1 ? $single : $plural;
}

function get_transient( $transient ) {
	$value = get_option( '_transient_' . $transient, false );
	if ( false === $value ) {
		return false;
	}
	$timeout = get_option( '_transient_timeout_' . $transient, 0 );
	if ( $timeout && time() > (int) $timeout ) {
		delete_option( '_transient_' . $transient );
		delete_option( '_transient_timeout_' . $transient );
		return false;
	}
	return $value;
}

function set_transient( $transient, $value, $expiration = 0 ) {
	update_option( '_transient_' . $transient, $value );
	if ( $expiration ) {
		update_option( '_transient_timeout_' . $transient, time() + (int) $expiration );
	}
	return true;
}

function delete_transient( $transient ) {
	delete_option( '_transient_' . $transient );
	delete_option( '_transient_timeout_' . $transient );
}

function wp_timezone() {
	return new DateTimeZone( JB_App::config( 'timezone', 'America/Bogota' ) );
}

function wp_date( $format, $timestamp = null, $timezone = null ) {
	$tz  = $timezone ?: wp_timezone();
	$dt  = new DateTime( '@' . ( $timestamp ?? time() ) );
	$dt->setTimezone( $tz );
	return $dt->format( $format );
}

function date_i18n( $format, $timestamp = false, $gmt = false ) {
	if ( false === $timestamp ) {
		$timestamp = current_time( 'timestamp', $gmt );
	}
	return wp_date( $format, (int) $timestamp, $gmt ? new DateTimeZone( 'UTC' ) : null );
}

function current_time( $type, $gmt = false ) {
	$tz = wp_timezone();
	$dt = new DateTime( 'now', $tz );
	if ( 'mysql' === $type ) {
		return $dt->format( 'Y-m-d H:i:s' );
	}
	if ( 'timestamp' === $type ) {
		return $dt->getTimestamp();
	}
	return $dt->format( $type );
}

function get_page_by_path( $page_path, $output = OBJECT, $post_type = 'page' ) {
	$slug = sanitize_title( $page_path );
	$stored = get_option( 'jb_pages', array() );
	if ( isset( $stored[ $slug ] ) ) {
		$page = (object) $stored[ $slug ];
		return $page;
	}
	return null;
}

function wp_insert_post( $postarr, $wp_error = false ) {
	$slug = sanitize_title( $postarr['post_name'] ?? $postarr['post_title'] ?? 'page' );
	$stored = get_option( 'jb_pages', array() );
	$id = count( $stored ) + 1;
	$page = array(
		'ID'           => $id,
		'post_title'   => $postarr['post_title'] ?? '',
		'post_content' => $postarr['post_content'] ?? '',
		'post_status'  => $postarr['post_status'] ?? 'publish',
		'post_type'    => $postarr['post_type'] ?? 'page',
		'post_name'    => $slug,
	);
	$stored[ $slug ] = $page;
	update_option( 'jb_pages', $stored );
	if ( ! empty( $postarr['meta_input'] ) ) {
		foreach ( $postarr['meta_input'] as $k => $v ) {
			update_post_meta( $id, $k, $v );
		}
	}
	return $id;
}

function get_permalink( $post = 0 ) {
	$post_id = is_object( $post ) ? (int) ( $post->ID ?? 0 ) : (int) $post;

	if ( 2 === $post_id ) {
		return add_query_arg( 'public', '1', home_url( '/' ) );
	}

	if ( is_object( $post ) ) {
		$slug = $post->post_name ?? '';
	} else {
		$stored = get_option( 'jb_pages', array() );
		$slug = '';
		foreach ( $stored as $s => $p ) {
			if ( (int) ( $p['ID'] ?? 0 ) === $post_id ) {
				$slug = $s;
				break;
			}
		}
	}
	if ( 'jb-planeacion-backend' === $slug || '' === $slug || 1 === $post_id ) {
		return home_url( '/' );
	}
	if ( 'latingraf-inventarios' === $slug ) {
		return add_query_arg( 'public', '1', home_url( '/' ) );
	}
	return home_url( '/' . $slug );
}

function get_page_template_slug( $post_id = 0 ) {
	$meta = get_post_meta( $post_id, '_wp_page_template', true );
	return $meta ?: '';
}

function update_post_meta( $post_id, $meta_key, $meta_value ) {
	$all = get_option( 'jb_post_meta', array() );
	if ( ! isset( $all[ $post_id ] ) ) {
		$all[ $post_id ] = array();
	}
	$all[ $post_id ][ $meta_key ] = $meta_value;
	update_option( 'jb_post_meta', $all );
	return true;
}

function get_post_meta( $post_id, $key = '', $single = true ) {
	$all = get_option( 'jb_post_meta', array() );
	$meta = $all[ $post_id ] ?? array();
	if ( '' === $key ) {
		return $meta;
	}
	if ( ! isset( $meta[ $key ] ) ) {
		return $single ? '' : array();
	}
	return $single ? $meta[ $key ] : array( $meta[ $key ] );
}

function wp_upload_dir() {
	$dir = JB_APP_ROOT . 'storage/uploads';
	if ( ! is_dir( $dir ) ) {
		mkdir( $dir, 0755, true );
	}
	$url = home_url( 'uploads' );
	$y   = date( 'Y' );
	$m   = date( 'm' );
	$subdir = "/{$y}/{$m}";
	$pathdir = $dir . $subdir;
	if ( ! is_dir( $pathdir ) ) {
		mkdir( $pathdir, 0755, true );
	}
	return array(
		'path'    => $pathdir,
		'url'     => $url . $subdir,
		'subdir'  => $subdir,
		'basedir' => $dir,
		'baseurl' => $url,
		'error'   => false,
	);
}

function wp_parse_args( $args, $defaults = '' ) {
	if ( is_object( $args ) ) {
		$args = get_object_vars( $args );
	}
	if ( is_array( $defaults ) ) {
		return array_merge( $defaults, $args );
	}
	return $args;
}

function wp_list_pluck( $list, $field, $index_key = null ) {
	$newlist = array();
	if ( ! is_array( $list ) ) {
		return $newlist;
	}
	foreach ( $list as $key => $value ) {
		if ( is_object( $value ) ) {
			$newlist[ $index_key ? $value->$index_key : $key ] = $value->$field;
		} elseif ( is_array( $value ) ) {
			$newlist[ $index_key ? $value[ $index_key ] : $key ] = $value[ $field ];
		}
	}
	return $newlist;
}

function number_format_i18n( $number, $decimals = 0 ) {
	return number_format( (float) $number, $decimals, ',', '.' );
}

function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
	// Stub: registrar en log en desarrollo.
	if ( JB_App::is_debug() ) {
		error_log( "wp_mail to={$to} subject={$subject}" );
	}
	return true;
}

function wp_tempnam( $filename = '', $dir = '' ) {
	$dir = $dir ?: sys_get_temp_dir();
	return tempnam( $dir, 'jb_' );
}

function wp_mkdir_p( $target ) {
	return wp_mkdir_p_inner( $target );
}

function wp_mkdir_p_inner( $target ) {
	if ( file_exists( $target ) ) {
		return is_dir( $target );
	}
	return mkdir( $target, 0755, true );
}

function wp_normalize_path( $path ) {
	$path = str_replace( '\\', '/', $path );
	$path = preg_replace( '|/+|', '/', $path );
	return $path;
}

function wp_is_stream( $path ) {
	return false;
}

function wp_basename( $path ) {
	return basename( $path );
}

function wp_unique_filename( $dir, $filename ) {
	$filename = sanitize_file_name( $filename );
	$ext = pathinfo( $filename, PATHINFO_EXTENSION );
	$name = pathinfo( $filename, PATHINFO_FILENAME );
	$i = 1;
	$candidate = $filename;
	while ( file_exists( $dir . '/' . $candidate ) ) {
		$candidate = $name . '-' . $i . ( $ext ? '.' . $ext : '' );
		$i++;
	}
	return $candidate;
}

function wp_generate_password( $length = 12, $special_chars = true ) {
	$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	if ( $special_chars ) {
		$chars .= '!@#$%^&*()';
	}
	$pass = '';
	for ( $i = 0; $i < $length; $i++ ) {
		$pass .= $chars[ random_int( 0, strlen( $chars ) - 1 ) ];
	}
	return $pass;
}

function wp_get_upload_dir() {
	return wp_upload_dir();
}

function content_url( $path = '' ) {
	return home_url( 'uploads' . ( $path ? '/' . ltrim( $path, '/' ) : '' ) );
}

function trailingslashit( $string ) {
	return rtrim( $string, '/\\' ) . '/';
}

function untrailingslashit( $string ) {
	return rtrim( $string, '/\\' );
}

function is_email( $email ) {
	return (bool) filter_var( $email, FILTER_VALIDATE_EMAIL );
}

function wp_cache_get( $key, $group = '' ) {
	return false;
}

function wp_cache_set( $key, $data, $group = '', $expire = 0 ) {
	return true;
}

function wp_cache_delete( $key, $group = '' ) {
	return true;
}

function wp_raise_memory_limit( $context = 'admin' ) {
	@ini_set( 'memory_limit', '256M' );
}

function wp_get_environment_type() {
	return JB_App::config( 'app_env', 'production' );
}

function wp_using_ext_object_cache() {
	return false;
}

function load_textdomain( $domain, $mofile ) {
	return true;
}

function load_plugin_textdomain( $domain, $deprecated = false, $plugin_rel_path = false ) {
	return true;
}

function plugin_basename( $file ) {
	return basename( dirname( $file ) ) . '/' . basename( $file );
}

function wp_nonce_field( $action, $name = '_wpnonce', $referer = true, $echo = true ) {
	$field = '<input type="hidden" name="' . esc_attr( $name ) . '" value="' . esc_attr( wp_create_nonce( $action ) ) . '" />';
	if ( $echo ) {
		echo $field;
	}
	return $field;
}

function wp_nonce_url( $url, $action, $name = '_wpnonce' ) {
	return add_query_arg( $name, wp_create_nonce( $action ), $url );
}


function wp_reset_query() {}

function get_bloginfo( $show = '' ) {
	$map = array(
		'name'    => JB_App::config( 'app_name' ),
		'url'     => home_url(),
		'version' => LOGISTICA_VERSION ?? '1.0.0',
	);
	return $map[ $show ] ?? '';
}

function get_site_url() {
	return home_url();
}

function wp_get_attachment_url( $attachment_id ) {
	return get_option( 'jb_attachment_' . $attachment_id, '' );
}

function attachment_url_to_postid( $url ) {
	return 0;
}

function media_sideload_image( $file, $post_id, $desc = null, $return = 'html' ) {
	return '';
}

function download_url( $url ) {
	$tmp = wp_tempnam( basename( parse_url( $url, PHP_URL_PATH ) ) );
	$data = file_get_contents( $url );
	if ( $data ) {
		file_put_contents( $tmp, $data );
		return $tmp;
	}
	return new WP_Error( 'download_failed', 'No se pudo descargar el archivo.' );
}

function wp_handle_sideload( $file, $overrides = array(), $time = null ) {
	return $file;
}

function wp_insert_attachment( $args, $file = false, $parent = 0 ) {
	$id = (int) get_option( 'jb_attachment_counter', 0 ) + 1;
	update_option( 'jb_attachment_counter', $id );
	if ( $file ) {
		update_option( 'jb_attachment_' . $id, $file );
	}
	return $id;
}

function wp_update_attachment_metadata( $attachment_id, $data ) {
	update_option( 'jb_attachment_meta_' . $attachment_id, $data );
	return true;
}

function wp_get_attachment_metadata( $attachment_id ) {
	return get_option( 'jb_attachment_meta_' . $attachment_id, array() );
}

function size_format( $bytes, $decimals = 0 ) {
	$units = array( 'B', 'KB', 'MB', 'GB' );
	$bytes = max( $bytes, 0 );
	$pow   = floor( ( $bytes ? log( $bytes ) : 0 ) / log( 1024 ) );
	$pow   = min( $pow, count( $units ) - 1 );
	$bytes /= ( 1 << ( 10 * $pow ) );
	return round( $bytes, $decimals ) . ' ' . $units[ $pow ];
}

function human_time_diff( $from, $to = 0 ) {
	$to = $to ?: time();
	$diff = abs( $to - $from );
	if ( $diff < MINUTE_IN_SECONDS ) {
		return $diff . ' segundos';
	}
	if ( $diff < HOUR_IN_SECONDS ) {
		return floor( $diff / MINUTE_IN_SECONDS ) . ' minutos';
	}
	if ( $diff < DAY_IN_SECONDS ) {
		return floor( $diff / HOUR_IN_SECONDS ) . ' horas';
	}
	return floor( $diff / DAY_IN_SECONDS ) . ' días';
}

function get_post_status( $post = null ) {
	if ( is_numeric( $post ) ) {
		$stored = get_option( 'jb_pages', array() );
		foreach ( $stored as $p ) {
			if ( (int) ( $p['ID'] ?? 0 ) === (int) $post ) {
				return $p['post_status'] ?? 'publish';
			}
		}
		return false;
	}
	if ( is_object( $post ) ) {
		return $post->post_status ?? 'publish';
	}
	return 'publish';
}

function add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $icon_url = '', $position = null ) {
	return $menu_slug;
}

function add_submenu_page( $parent_slug, $page_title, $menu_title, $capability, $menu_slug, $callback = '' ) {
	return $menu_slug;
}

function get_post_type( $post = null ) {
	$p = get_post( $post );
	return $p ? ( $p->post_type ?? 'page' ) : false;
}

function get_edit_user_link( $user_id, $return_section = 'logistica-config-usuarios' ) {
	if ( defined( 'LOGISTICA_STANDALONE' ) && LOGISTICA_STANDALONE ) {
		$section = function_exists( 'logistica_sanitize_config_section' )
			? logistica_sanitize_config_section( $return_section )
			: 'logistica-config-usuarios';

		return add_query_arg(
			array(
				'user_id'         => (int) $user_id,
				'return_section'  => $section,
			),
			home_url( 'user-edit.php' )
		);
	}

	return add_query_arg( 'config', '1', home_url( '/' ) );
}

function get_avatar_url( $id_or_email, $args = null ) {
	return '';
}

function wp_validate_redirect( $location, $default = '' ) {
	$location = trim( (string) $location );
	if ( '' === $location ) {
		return $default;
	}
	if ( preg_match( '#^(https?://|/)#i', $location ) ) {
		return $location;
	}
	return $default;
}

function wp_parse_url( $url, $component = -1 ) {
	$parts = parse_url( $url );
	if ( -1 === $component ) {
		return $parts;
	}
	if ( false === $parts ) {
		return null;
	}
	$map = array(
		PHP_URL_SCHEME   => 'scheme',
		PHP_URL_HOST     => 'host',
		PHP_URL_PORT     => 'port',
		PHP_URL_USER     => 'user',
		PHP_URL_PASS     => 'pass',
		PHP_URL_PATH     => 'path',
		PHP_URL_QUERY    => 'query',
		PHP_URL_FRAGMENT => 'fragment',
	);
	$key = $map[ $component ] ?? null;
	return $key && isset( $parts[ $key ] ) ? $parts[ $key ] : null;
}

function wp_update_post( $postarr = array(), $wp_error = false ) {
	$id = (int) ( $postarr['ID'] ?? 0 );
	if ( $id <= 0 ) {
		return 0;
	}
	$stored = get_option( 'jb_pages', array() );
	foreach ( $stored as $slug => $page ) {
		if ( (int) ( $page['ID'] ?? 0 ) === $id ) {
			foreach ( $postarr as $k => $v ) {
				if ( 'ID' !== $k ) {
					$stored[ $slug ][ $k ] = $v;
				}
			}
			update_option( 'jb_pages', $stored );
			return $id;
		}
	}
	return $id;
}

function wp_dropdown_pages( $args = '' ) {
	$parsed = wp_parse_args( $args );
	$name     = $parsed['name'] ?? 'page_id';
	$id       = $parsed['id'] ?? $name;
	$selected = (int) ( $parsed['selected'] ?? 0 );
	$show_option_none = $parsed['show_option_none'] ?? '';
	$echo     = $parsed['echo'] ?? true;

	$options = array(
		1 => __( 'Panel de operaciones', 'logistica' ),
		2 => __( 'Panel público (legacy)', 'logistica' ),
	);

	$html = '<select name="' . esc_attr( $name ) . '" id="' . esc_attr( $id ) . '">';
	if ( $show_option_none ) {
		$html .= '<option value="0">' . esc_html( $show_option_none ) . '</option>';
	}
	foreach ( $options as $value => $label ) {
		$html .= '<option value="' . esc_attr( (string) $value ) . '"' . selected( $value, $selected, false ) . '>' . esc_html( $label ) . '</option>';
	}
	$html .= '</select>';
	if ( $echo ) {
		echo $html;
	}
	return $html;
}

function wp_editor( $content, $editor_id, $settings = array() ) {
	$rows = (int) ( $settings['textarea_rows'] ?? 12 );
	$name = $settings['textarea_name'] ?? $editor_id;
	echo '<textarea id="' . esc_attr( $editor_id ) . '" name="' . esc_attr( $name ) . '" rows="' . $rows . '" class="widefat wp-editor-area">' . esc_textarea( $content ) . '</textarea>';
}

function wp_html_excerpt( $str, $count, $more = null ) {
	$str = wp_strip_all_tags( $str );
	if ( strlen( $str ) <= $count ) {
		return $str;
	}
	return substr( $str, 0, $count ) . ( $more ?? '&hellip;' );
}

function wp_trim_words( $text, $num_words = 55, $more = null ) {
	$text = wp_strip_all_tags( $text );
	$words = preg_split( '/\s+/', $text, -1, PREG_SPLIT_NO_EMPTY );
	if ( count( $words ) <= $num_words ) {
		return $text;
	}
	$more = null === $more ? '&hellip;' : $more;
	return implode( ' ', array_slice( $words, 0, $num_words ) ) . $more;
}

function submit_button( $text = null, $type = 'primary', $name = 'submit', $wrap = true, $other_attributes = null ) {
	$text = $text ?: __( 'Guardar cambios' );
	$button = '<button type="submit" name="' . esc_attr( $name ) . '" class="button button-' . esc_attr( $type ) . '">' . esc_html( $text ) . '</button>';
	if ( $wrap ) {
		$button = '<p class="submit">' . $button . '</p>';
	}
	echo $button;
}

function wp_next_scheduled( $hook, $args = array() ) {
	return false;
}

function wp_schedule_event( $timestamp, $recurrence, $hook, $args = array(), $wp_error = false ) {
	return true;
}

function wp_unschedule_event( $timestamp, $hook, $args = array() ) {
	return true;
}

class WP_Post {
	public $ID = 0;
	public $post_title = '';
	public $post_content = '';
	public $post_status = 'publish';
	public $post_type = 'page';
	public $post_name = '';

	public function __construct( $data = array() ) {
		foreach ( $data as $k => $v ) {
			$this->$k = $v;
		}
	}
}

if ( ! defined( 'MINUTE_IN_SECONDS' ) ) {
	define( 'MINUTE_IN_SECONDS', 60 );
}
if ( ! defined( 'HOUR_IN_SECONDS' ) ) {
	define( 'HOUR_IN_SECONDS', 3600 );
}
if ( ! defined( 'DAY_IN_SECONDS' ) ) {
	define( 'DAY_IN_SECONDS', 86400 );
}
if ( ! defined( 'KB_IN_BYTES' ) ) {
	define( 'KB_IN_BYTES', 1024 );
}
