<?php if(! defined('ABSPATH')){ return; }
/*
 Name: PHP Code
 Description: Create and display a PHP Code element.
 Class: TH_PhpCode
 Category: content
 Level: 3
*/
/**
 * Class TH_PhpCode
 *
 * Create and display a PHP Code element.
 * Executes the provided PHP code in pages this element is included into.
 * Heads up: While this element give you a lot of freedom, please use it responsibly as it can easily break your
 * existent codebase. Also, be aware of the server's limitations: restricted functions or classes.
 *
 * @package  Kallyas
 * @category Page Builder
 * @author   Team Hogash
 * @since    4.0.0
 */
class TH_PhpCode extends ZnElements
{

	public static function getName(){
		return __( "PHP Code", 'zn_framework' );
	}

	private static function _updateEntry( $optName, $value = '' ){
		return update_option($optName, $value);
	}
	private static function _getEntry($optName){
		return get_option($optName);
	}


	/**
	 * This method is used to display the output of the element.
	 * @return void
	 */
	function element()
	{
		$options = $this->data['options'];
		$dbOptName = $this->data['uid'];

		echo '<div class="elm-phpcode '.$dbOptName.' '.zn_get_element_classes($this->data['options']).'">';

		if(isset($options['page_php_code_text']) && ! empty($options['page_php_code_text']))
		{
			$oldFileName = self::_getEntry($dbOptName);

			$code = $options['page_php_code_text'];
			$code = trim($code);

			$startStr = substr($code, 0, 5);

			if( $startStr != '<?php' ){
				$code = '<?php '.$code;
			}

			// Add comment if not there already
			$comment = '<?php /*[Kallyas Theme] This file was automatically generated by the PHP Code element. You should not edit this file unless you know what you\'re doing! */ if(!defined("ABSPATH")){return;}'.PHP_EOL;

			if(false === ($pos = stripos($code, '[Kallyas Theme]'))) {
				$code = preg_replace( '/^\<\?php/msi', $comment, $code );
			}

			// Create the tmp file
			$codeHash = md5($code);

			// Get the uploads dir path
			$upload_dir = wp_upload_dir();
			$uploadPath = $upload_dir['basedir'];

			// Check option
			if(! empty($oldFileName)){
				// Edited code -> Delete old file
				$fp = "{$uploadPath}/{$oldFileName}.php";
				if(is_file($fp)){
					@unlink( $fp );
				}
			}
			// Update db entry
			self::_updateEntry( $dbOptName, $codeHash );

			$fname = $codeHash.'.php';
			$filePath = $upload_dir['basedir'].'/'.$fname;
			if(! is_file($filePath)){
				self::writeFile($filePath, $code);
			}
			// Include the tmp file and execute the php code
			if( is_file($filePath) && is_readable($filePath) ) {
				include( $filePath );
			}
		}
		echo '</div>';
	}

		/**
		 * Write the specified $content to a file $filePath.
		 * @param string $filePath
		 * @param string $content
		 * @param bool   $append
		 * @since 3.8.0
		 * @return int 0 on error, >=1 on success
		 */
		public static function writeFile($filePath, $content, $append = false){

			$fs = ZNHGTFW()->getComponent( 'utility' )->getFileSystem();

			if( ! $append ){
				$fs->delete( $filePath );
			}
			$fs->put_contents( $filePath, $content );
			return 2;
		}

	/**
	 * This method is used to retrieve the configurable options of the element.
	 * @return array The list of options that compose the element and then passed as the argument for the render() function
	 */
	function options()
	{
		$uid = $this->data['uid'];

		$options = array(
			'has_tabs'  => true,
			'general' => array(
				'title' => 'General options',
				'options' => array(
					array (
						"name"        => __( "PHP Code", 'zn_framework' ),
						"description" => __( 'Please enter the PHP code to be executed. You need to be very careful to
												write this code properly because it will be executed as it is and it
												can potentially break your website.', 'zn_framework' ),
						"id"          => "page_php_code_text",
						"std"         => "",
						"type"        => "textarea",
						'class' => 'zn_full'
					),
				),
			),


			'help' => znpb_get_helptab( array(
				'video'   => sprintf( '%s', esc_url('https://my.hogash.com/video_category/kallyas-wordpress-theme/#yh8tyiw8tCc') ),
				'docs'    => sprintf( '%s', esc_url('https://my.hogash.com/documentation/php-code/') ),
				'copy'    => $uid,
				'general' => true,
			)),

		);
		return $options;
	}
}
