<?php 
/**
 * Class ST_Proqyz_Admin_Page_Emails
 */
defined( 'ABSPATH' ) || exit;

/**
 * Class.
 */
class ST_ProQyz_Admin_Page_Emails {

    protected static $_instance = null;

    public static $email_triggers = [];

    /**
     * Main Ielts_Lms Instance.
     *
     * Ensures only one instance of Ielts_Lms_Post_Types is loaded or can be loaded.
     *
     * @since 1.0
     * @static
     * @return Ielts_Lms_Post_Types - Main instance.
     */
    public static function instance() {
        if (is_null(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * Hook in tabs.
     */
    public function __construct() {
        $this->define_constants();
        $this->hooks();
        $this->includes();
        // $this->manage_email();
    }

    public function manage_email() {
        
        add_filter( 'mce_buttons' , [$this, 'proqyz_tinymce_tools'] );
        add_filter( 'mce_external_plugins', [$this,'proqyz_tinymce_plugin'] );
    }

    /**
     * Register hooks
     */
    public function define_constants() {
        global $ST_EMAILS;
        self::$email_triggers = (array) $ST_EMAILS;
    }

    public function hooks() {
        if (count(self::$email_triggers) > 0) {
            foreach (self::$email_triggers as $ekey => $etrigger) {
                $post = $this->check_or_create((object) [
                    'post_type' => 'proqyz-email',
                    'post_status' => 'publish',
                    'post_title' => $etrigger->post_title,
                    'post_name' => $etrigger->post_name,
                    'post_content' => $etrigger->post_content,
                    'meta_input' => $etrigger->post_meta
                ]);
                if ($post) {
                    self::$email_triggers[$ekey]->post_meta['_proqyz__email-notification-enabled'] = $post['post_meta']['_proqyz__email-notification-enabled'];
                    self::$email_triggers[$ekey]->post_meta['_proqyz__email-recipient'] = $post['post_meta']['_proqyz__email-recipient'];
                    self::$email_triggers[$ekey]->post_meta['_proqyz__email-subject'] = $post['post_meta']['_proqyz__email-subject'];
                    self::$email_triggers[$ekey]->post_meta['_proqyz__email-content'] = $post['post_meta']['_proqyz__email-content'];
                    self::$email_triggers[$ekey]->ID = $post['ID'];
                }
            }
        }
    }

    /**
     * Includes
     */
    public function includes() {
        // Include additional files if needed.
    }

    /**
     * Initialize TinyMCE
     */
    public function proqyz_tinymce_plugin() {
        $plugin_dir = plugin_dir_url(ST_PROQYZ_PLUGIN_FILE);
        $plugins['proqyz_email_templates_tinymce'] = $plugin_dir . '/includes/admin/dist/js/tinymce-email-templates-plugin.js';
        return $plugins;
    
    }

    public function proqyz_tinymce_tools($buttons) {
        array_push($buttons, 'proqyz_email_templates_tinymce');
        return $buttons;
        
    }

    /**
     * Check if post exists or create a new one and return post ID and metadata.
     *
     * @param array $atts Attributes for the post.
     * @return array Post ID and metadata.
     */
    public function check_or_create($atts = []) {
        $atts = (object)$atts;

        $args = [
            'name' => $atts->post_name,
            'post_type' => $atts->post_type,
            'post_status' => $atts->post_status,
            'posts_per_page' => 1,
        ];

        $posts = get_posts($args);
        if (!empty($posts)) {
            $post_id = $posts[0]->ID;
        } else {
            $post_id = wp_insert_post((array) $atts);
        }


        $email_notification_enabled = get_post_meta($post_id,'_proqyz__email-notification-enabled',true);
        $email_recipient            = get_post_meta($post_id,'_proqyz__email-recipient',true);
        $email_subject              = get_post_meta($post_id,'_proqyz__email-subject',true);
        $email_content              = get_post_meta($post_id,'_proqyz__email-content',true);

        $email_notification_enabled = isset($email_notification_enabled)? $email_notification_enabled : $atts->meta_input['_proqyz__email-notification-enabled'];
        $email_recipient            = (isset($email_recipient))? $email_recipient : $atts->meta_input['_proqyz__email-recipient'];
        $email_subject              = (isset($email_subject))? $email_subject : $atts->meta_input['_proqyz__email-subject'];
        $email_content              = (isset($email_content))? $email_content : $atts->meta_input['_proqyz__email-content'];

        return [
            'ID' => $post_id,
            "post_meta"             => (array) [
                "_proqyz__email-notification-enabled"   => $email_notification_enabled,
                "_proqyz__email-recipient"              => $email_recipient,
                "_proqyz__email-subject"                => $email_subject,
                "_proqyz__email-content"                => $email_content
            ]
        ];
    }

    public static function proqyz_edit_post_handler($post_id = null){
        if($post_id !== null){
            if(isset($_POST['proqyz__email-edit']) && !empty($_POST['proqyz__email-edit'])) {
                $email_notification_enabled = isset($_POST['_proqyz__email-notification-enabled'])? $_POST['_proqyz__email-notification-enabled'] : 0;
                $email_recipient            = (isset($_POST['_proqyz__email-recipient']) && !empty($_POST['_proqyz__email-recipient']))? $_POST['_proqyz__email-recipient'] : '';
                $email_subject              = (isset($_POST['_proqyz__email-subject']) && !empty($_POST['_proqyz__email-subject']))? $_POST['_proqyz__email-subject'] : '';
                $email_content              = (isset($_POST['_proqyz__email-content']) && !empty($_POST['_proqyz__email-content']))? $_POST['_proqyz__email-content'] : '';

                # filter string for content
                $email_content              = wp_unslash($email_content); // Remove slashes added by WordPress
                $email_content              = wp_kses_post($email_content); // Sanitize the content for allowed HTML tags

                // Handle recipients: convert comma-separated string to array
                

                # check if post exists by given post id
                $post = get_post($post_id);
                if ($post && $post->post_type === 'proqyz-email') {
                    
                    # update the post by given post id
                    update_post_meta($post_id, '_proqyz__email-notification-enabled', $email_notification_enabled);
                    update_post_meta($post_id, '_proqyz__email-recipient', []);
                    
                    update_post_meta($post_id, '_proqyz__email-subject', $email_subject);
                    update_post_meta($post_id, '_proqyz__email-content', $email_content);

                    return '<div class="updated">
                        <p>Changes saved successfully. </p>
                    </div>';

                } else {
                    return '<div class="notice notice-error">
                        <p>Post not found, please reload this page.</p>
                    </div>';
                }
            }
        }

        return null;
    }

    /**
     * Get page layout.
     */
    public static function get_page_layout() {
        require_once ST_PROQYZ_ABSPATH . "/includes/templates/admin/emails/emails.php"; // checked
    }

    /**
     * Get posts by post type.
     *
     * @param string $post_type The post type to retrieve.
     * @param int $number_of_posts The number of posts to retrieve. Default is -1 (all posts).
     * @return array An array of WP_Post objects.
     */
    public static function get_posts_by_post_type($post_type, $number_of_posts = -1) {
        $args = [
            'post_type' => $post_type,
            'post_status' => 'publish', // Only retrieve published posts
            'posts_per_page' => $number_of_posts,
        ];

        $posts = get_posts($args);

        return $posts;
    }

    /**
     * Find and return the first match of the given key in the email triggers array.
     *
     * @param string $key The key to search for.
     * @return object|null The matching email trigger object or null if not found.
     */
    public static function find_email_trigger_by_key($key) {
        foreach (self::$email_triggers as $trigger) {
            if ($trigger->post_name === $key) {
                return $trigger;
            }
        }
        return null;
    }

}



return ST_ProQyz_Admin_Page_Emails::instance();
