<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Niwa_AI_Admin_Autonomy_Temp_Files {

	public static function create( $prefix = '' ) {
		self::ensure_wp_file_api();

		if ( function_exists( 'wp_tempnam' ) ) {
			$tmp = wp_tempnam( $prefix );
			if ( $tmp ) {
				return $tmp;
			}
		}

		$dir = function_exists( 'get_temp_dir' ) ? get_temp_dir() : sys_get_temp_dir();
		if ( ! is_dir( $dir ) || ! is_writable( $dir ) ) {
			$dir = sys_get_temp_dir();
		}

		$safe_prefix = preg_replace( '/[^A-Za-z0-9_.-]/', '_', (string) $prefix );
		$safe_prefix = substr( '' !== $safe_prefix ? $safe_prefix : 'niwa_', 0, 64 );

		return tempnam( $dir, $safe_prefix );
	}

	private static function ensure_wp_file_api() {
		if ( function_exists( 'wp_tempnam' ) || ! defined( 'ABSPATH' ) ) {
			return;
		}

		$file_api = ABSPATH . 'wp-admin/includes/file.php';
		if ( is_readable( $file_api ) ) {
			require_once $file_api;
		}
	}
}
