<?php
/**
 * Functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 */
if ( ! function_exists( 'sas_setup' ) ) {
    function sas_setup() {
		add_theme_support('elementor');

        register_nav_menus([
            'main' => esc_html__('Main', 'sastheme')
        ]);

        /*
		 * Add support for core custom logo.
		 *
		 * @link https://codex.wordpress.org/Theme_Logo
		 */

		add_theme_support(
			'custom-logo',
			array(
				'flex-width'           => true,
				'flex-height'          => true,
				'unlink-homepage-logo' => true,
			)
		);

		add_theme_support('post-thumbnails');
    }
}

add_action( 'after_setup_theme', 'sas_setup' );

function sas_scripts() {
    wp_enqueue_style('sas-style', get_template_directory_uri() . '/style.css', array(), wp_get_theme()->get('Version'));
	wp_enqueue_style('bootstrap-5', 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css');;
	wp_enqueue_script('jquery-min-js', get_template_directory_uri() . '/assets/js/jquery-3.7.0.min.js', array(), '3.7.0');
	wp_enqueue_script('scripts-js', get_template_directory_uri() . '/assets/js/scripts.js');
	wp_enqueue_script('bootstrap-js', 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.min.js', null, null, true);
}

add_action( 'wp_enqueue_scripts', 'sas_scripts' );

require_once dirname( __FILE__ ) . '/inc/class-tgm-plugin-activation.php';

require dirname( __FILE__ ) . '/inc/sas-required-plugins.php';
new Sas_Required_Plugins();

require dirname( __FILE__ ) . '/inc/sas-required-pages.php';
new Sas_Required_Pages();

require dirname( __FILE__ ) . '/inc/sas-theme-navigation.php';
new Sas_Theme_Navigation();

require dirname( __FILE__ ) . '/inc/sas-customizer.php';
new Sas_Customizer();

require dirname( __FILE__ ) . '/inc/sas-subscription.php';
new Sas_Subscription();

// Imports Elementor templates
function import_elementor_templates_parent()
{
    // Checks if the 'elementor_template_imported' theme option is set to true
    $template_imported = get_option('elementor_sas_default_single_template_imported', false);
    $elementor_loaded = get_option('elementor_loaded', false);

    /*
    // If the templates have already been imported, do nothing
    if ($template_imported) {
        return;
    }
    */

    // Checks if Elementor is loaded and if the template manager is available
    if (!class_exists('\Elementor\Plugin') || !\Elementor\Plugin::instance()->templates_manager) {
        return;
    } elseif (!class_exists('Saswp\Api')) {
        return;
    } 

    if (!$elementor_loaded && class_exists('\Elementor\Plugin')) {
        update_option('elementor_loaded', true);
        return;
    } 

    // List of template files to import
    $template_files = [
        "Home - Search and Stay Default Single Property Elementor" => 'home.json',  
        "Banner - Search and Stay Default Single Property Elementor" => 'banner.json'
    ];

    $generated_template_part = [];

    // Loop through each template file
    foreach ($template_files as $template_name => $template_file_name) {

        // Checks if template part is alredy created
        // Searches for the template by section name
        $template_part = get_posts(array(
            'post_type' => 'elementor_library',
            's' => $template_name,
        ));

        if(empty($template_part)) {

            // Path to the template JSON file
            $template_file = get_stylesheet_directory() . '/elementor-templates/' . $template_file_name;

            // Checks if the template JSON file exists
            if (file_exists($template_file)) {
                // Gets the content of the JSON file
                $template_content = file_get_contents($template_file);

                // Decode the JSON to an array to validate it's a correct JSON format
                $decoded_content = json_decode($template_content, true);

                // Checks if JSON decoding was successful
                if (json_last_error() !== JSON_ERROR_NONE) {
                    // Returns an error message if JSON is invalid
                    return 'Invalid JSON format in ' . $template_file_name;
                }

                // Imports the template using Elementor API
                $import_result = \Elementor\Plugin::instance()->templates_manager->import_template([
                    'fileData' => base64_encode($template_content), // Importing entire JSON file content
                    'fileName' => $template_file_name,
                ]);

                // Checks if the import was successful
                if (is_array($import_result) && is_array($import_result[0]) && isset($import_result[0]['template_id'])) {
                    // Perform any other necessary actions after successful import
                    //update_post_meta($import_result[0]['template_id'], '_elementor_location', 'myCustomLocation');
                    update_post_meta($import_result[0]['template_id'], '_elementor_conditions', ['include/general']);

                    $generated_template_part[] = $template_name;

                } else {
                    // Returns an error message if import failed
                    return 'Error importing Elementor template: ' . $template_file_name;
                }
            } else {
                // Returns an error message if the template file does not exist
                return 'Template JSON file not found: ' . $template_file_name;
            }

        }

        if(count($generated_template_part) > 0) {
            $transient_data = [
                'message' => wp_get_theme()->get('Name') ." theme generated an elementor template part successfully:<br/><b>" . implode("<br />", $generated_template_part) . "</b>",
                'type' => 'warning'
            ];
            set_transient( 'sas_theme_template_message', $transient_data, 60);
        }

    }


    // Sets the 'elementor_template_imported' theme option to true to indicate that the templates have been imported
    update_option('elementor_sas_default_single_template_imported', true);

    // Returns a success message
    return 'Templates imported successfully!';
}

function sas_theme_template_message() {

    if ( $notice_data = get_transient( 'sas_theme_template_message' ) ) {
        // Check if the retrieved data is an array before using it in a way that might cause the error
        if ( is_array( $notice_data ) && isset( $notice_data['message'], $notice_data['type'] ) ) {
            printf(
                '<div class="notice notice-%s is-dismissible" style="padding: 1rem">%s</div>',
                esc_attr( $notice_data['type'] ),
                $notice_data['message']
            );
            delete_transient( 'sas_theme_template_message' );
        }
    }
}
add_action( 'admin_notices', 'sas_theme_template_message' );

// Calls the import function on 'init' hook
add_action('init', 'import_elementor_templates_parent');