<?php
/**
 * Utilidades HTTP y URLs.
 */

/**
 * URL pública de la app (auto-detecta en HTTP; en CLI usa config).
 *
 * @return string
 */
function jb_planeacion_resolve_app_url() {
	static $cache = null;
	if ( null !== $cache ) {
		return $cache;
	}

	$configured = rtrim( (string) JB_App::config( 'app_url', '' ), '/' );
	$auto       = JB_App::config( 'app_url_auto', true );
	$is_cli     = ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' );
	$has_http   = ! empty( $_SERVER['HTTP_HOST'] );

	if ( ( ! $auto || ! $has_http || $is_cli ) && '' !== $configured ) {
		$cache = $configured;
		return $cache;
	}

	if ( $has_http && ! $is_cli ) {
		$scheme = is_ssl() ? 'https' : 'http';
		$host   = (string) $_SERVER['HTTP_HOST'];
		$script = (string) ( $_SERVER['SCRIPT_NAME'] ?? '/index.php' );
		$public = str_replace( '\\', '/', dirname( $script ) );
		if ( in_array( $public, array( '.', '/', '\\' ), true ) ) {
			$public = '';
		}
		$cache = $scheme . '://' . $host . $public;
		return $cache;
	}

	$cache = $configured;
	return $cache;
}

function home_url( $path = '', $scheme = null ) {
	$base = jb_planeacion_resolve_app_url();
	if ( $path ) {
		$base .= '/' . ltrim( $path, '/' );
	}
	return $base;
}

function admin_url( $path = '', $scheme = 'admin' ) {
	$base = jb_planeacion_resolve_app_url();
	if ( 'admin-ajax.php' === $path || str_starts_with( $path, 'admin-ajax.php' ) ) {
		return $base . '/ajax.php';
	}
	if ( 'admin-post.php' === $path || str_starts_with( $path, 'admin-post.php' ) ) {
		return $base . '/post.php';
	}

	$query = '';
	if ( str_starts_with( $path, 'admin.php' ) ) {
		$query = (string) parse_url( $path, PHP_URL_QUERY );
	} elseif ( '' !== $path ) {
		$query = ltrim( $path, '?' );
	}

	if ( defined( 'LOGISTICA_STANDALONE' ) && LOGISTICA_STANDALONE && '' !== $query && preg_match( '/(?:^|&)page=([^&]+)/', $query, $page_match ) ) {
		$page = sanitize_key( $page_match[1] );
		if ( 'logistica' === $page || str_starts_with( $page, 'logistica-' ) ) {
			$url = add_query_arg( 'config', '1', home_url( '/' ) );
			if ( preg_match( '/(?:^|&)tab=([^&]+)/', $query, $tab_match ) ) {
				$url = add_query_arg( 'tab', sanitize_key( $tab_match[1] ), $url );
			} elseif ( str_starts_with( $page, 'logistica-' ) ) {
				$url = add_query_arg( 'tab', $page, $url );
			}
			return $url;
		}
	}

	if ( str_starts_with( $path, 'admin.php' ) ) {
		return $base . '/admin.php' . ( $query ? '?' . $query : '' );
	}
	return $base . '/admin.php' . ( $path ? '?' . ltrim( $path, '?' ) : '' );
}

function site_url( $path = '', $scheme = null ) {
	return home_url( $path, $scheme );
}

function plugin_dir_path( $file ) {
	return rtrim( dirname( $file ), '/\\' ) . '/';
}

function plugin_dir_url( $file ) {
	return jb_planeacion_resolve_app_url() . '/';
}

function wp_safe_redirect( $location, $status = 302 ) {
	$location = trim( (string) $location );
	if ( '' === $location ) {
		$location = home_url( '/' );
	}
	// No usar FILTER_SANITIZE_URL aquí: en algunos PHP vacía URLs con query string.
	if ( function_exists( 'wp_validate_redirect' ) ) {
		$validated = wp_validate_redirect( $location, '' );
		if ( '' !== $validated ) {
			$location = $validated;
		}
	}
	if ( ! headers_sent() ) {
		header( 'Location: ' . $location, true, (int) $status );
	}
	exit;
}

function add_query_arg( ...$args ) {
	if ( 1 === count( $args ) && is_array( $args[0] ) ) {
		$key_or_array = $args[0];
		$url = $args[1] ?? null;
	} elseif ( 2 === count( $args ) && is_array( $args[0] ) ) {
		$key_or_array = $args[0];
		$url = $args[1];
	} elseif ( 3 === count( $args ) ) {
		$key_or_array = array( $args[0] => $args[1] );
		$url = $args[2];
	} else {
		return '';
	}

	if ( null === $url ) {
		$url = $_SERVER['REQUEST_URI'] ?? '/';
	}

	$parts = parse_url( $url );
	$query = array();
	if ( ! empty( $parts['query'] ) ) {
		parse_str( $parts['query'], $query );
	}
	$query = array_merge( $query, $key_or_array );
	$scheme = $parts['scheme'] ?? null;
	$host   = $parts['host'] ?? '';
	$port   = isset( $parts['port'] ) ? ':' . $parts['port'] : '';
	$path   = $parts['path'] ?? '';
	$base   = $scheme ? "{$scheme}://{$host}{$port}{$path}" : $path;
	return $base . '?' . http_build_query( $query );
}

function remove_query_arg( $key, $url = null ) {
	$keys = is_array( $key ) ? $key : array( $key );
	if ( null === $url ) {
		$url = $_SERVER['REQUEST_URI'] ?? '/';
	}
	$parts = parse_url( $url );
	$query = array();
	if ( ! empty( $parts['query'] ) ) {
		parse_str( $parts['query'], $query );
	}
	foreach ( (array) $keys as $k ) {
		unset( $query[ $k ] );
	}
	$scheme = $parts['scheme'] ?? null;
	$host   = $parts['host'] ?? '';
	$port   = isset( $parts['port'] ) ? ':' . $parts['port'] : '';
	$path   = $parts['path'] ?? '';
	$base   = $scheme ? "{$scheme}://{$host}{$port}{$path}" : $path;
	$qs = http_build_query( $query );
	return $qs ? $base . '?' . $qs : $base;
}

function wp_send_json_success( $data = null, $status_code = 200 ) {
	wp_send_json( array( 'success' => true, 'data' => $data ), $status_code );
}

function wp_send_json_error( $data = null, $status_code = 200 ) {
	wp_send_json( array( 'success' => false, 'data' => $data ), $status_code );
}

function wp_send_json( $response, $status_code = 200 ) {
	if ( ! headers_sent() ) {
		header( 'Content-Type: application/json; charset=utf-8' );
		http_response_code( $status_code );
	}
	echo wp_json_encode( $response );
	exit;
}

function wp_doing_ajax() {
	return JB_App::is_ajax();
}

function is_ssl() {
	return ( ! empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' )
		|| ( (int) ( $_SERVER['SERVER_PORT'] ?? 80 ) === 443 );
}

function status_header( $code ) {
	http_response_code( $code );
}

function nocache_headers() {
	header( 'Cache-Control: no-cache, no-store, must-revalidate' );
	header( 'Pragma: no-cache' );
	header( 'Expires: 0' );
}

function wp_redirect( $location, $status = 302 ) {
	wp_safe_redirect( $location, $status );
}

function wp_get_referer() {
	return $_SERVER['HTTP_REFERER'] ?? '';
}

function selected( $selected, $current = true, $echo = true ) {
	$result = (string) $selected === (string) $current ? ' selected="selected"' : '';
	if ( $echo ) {
		echo $result;
	}
	return $result;
}

function checked( $checked, $current = true, $echo = true ) {
	$result = (string) $checked === (string) $current ? ' checked="checked"' : '';
	if ( $echo ) {
		echo $result;
	}
	return $result;
}

function disabled( $disabled, $current = true, $echo = true ) {
	$result = (string) $disabled === (string) $current ? ' disabled="disabled"' : '';
	if ( $echo ) {
		echo $result;
	}
	return $result;
}
