<?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' );
    }

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

        if(isset($options['page_php_code_text']) && ! empty($options['page_php_code_text']))
        {
            $code = $options['page_php_code_text'];
            $code = trim($code);
            if(! preg_match("/^\<\?php/msi", $code)){
                $code = '<?php '.$code;
            }
            if(! preg_match("/\?\>$/ms", $code)){
                $code .= ' ?>';
            }
            // Add comment
            $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;

            $code = preg_replace('/^\<\?php/msi', $comment, $code);

            // Create the tmp file
            $fname = md5($code).'.php';
            $upload_dir = wp_upload_dir();
            $filePath = $upload_dir['basedir'].'/'.$fname;
            if(! is_file($filePath)){
                WpkZn::writeFile($filePath, $code);
            }
            // Include the tmp file and execute the php code
            if(is_file($filePath)) {
                include( $filePath );
            }
        }
    }

    /**
     * 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()
    {
        return 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"
                ),
        );
    }
}
