<?php

namespace Miruni\Elementor;
if (!defined('ABSPATH'))
    exit; // Exit if accessed directly

class Miruni_Elementor_Service
{
    /**
     * returns the _elementor_data post meta for a given post
     * @param int $post_id
     * @return mixed
     */
    public static function get_page_data(int $post_id)
    {
        $data = get_post_meta($post_id, '_elementor_data', true);
        return $data;
    }

    /**
     * updates the _elementor_data post meta for a given post
     * Always saves in JSON format
     * @param int $post_id
     * @param string|array $modified_data JSON string or PHP array
     * @return bool True on success, false on failure
     * @phpstan-ignore missingType.iterableValue
     */
    public static function update_page_data(int $post_id, string|array $modified_data): bool
    {
        try {
            error_log("update_page_data called type: " . gettype($modified_data));
            // Accept either a valid JSON string or a PHP array
            if (is_array($modified_data)) {
                $json_to_save = json_encode($modified_data, JSON_UNESCAPED_UNICODE);
                if ($json_to_save === false || json_last_error() !== JSON_ERROR_NONE) {
                    error_log("JSON encoding error: " . json_last_error_msg());
                    return false;
                }
                // @phpstan-ignore function.alreadyNarrowedType
            } elseif (is_string($modified_data)) {
                // Validate string is valid JSON
                json_decode($modified_data);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    error_log("Invalid JSON string provided: " . json_last_error_msg());
                    return false;
                }
                $json_to_save = $modified_data;
            } else {
                error_log("update_page_data called with invalid data type: " . gettype($modified_data));
                return false;
            }

            error_log("update_page_data json_to_save type " . gettype($json_to_save));
            if (class_exists('Elementor\Plugin')) {
                // @phpstan-ignore class.notFound
                $document = \Elementor\Plugin::$instance->documents->get($post_id);
                // Directly decode and update meta only once
                $decoded = json_decode($json_to_save, true);
                if ($decoded === null && $json_to_save !== 'null') {
                    error_log("Failed to decode JSON for Elementor meta update");
                    return false;
                }
                $document->update_json_meta("_elementor_data", $decoded);
            } else {
                $update_result = update_post_meta($post_id, '_elementor_data', $json_to_save);
                if ($update_result === false) {
                    return false;
                }
            }
            self::delete_element_cache($post_id);
            return true;
        } catch (\Exception $e) {
            do_action('miruni_plugin_error', $e, [
                'context' => 'Miruni_Elementor_Service.update_page_data',
                'operation' => "Updating post meta for post_id: $post_id",
                'user_id' => get_current_user_id()
            ]);
            return false;
        }
    }

    public static function delete_element_cache(int $post_id): void
    {
        try {
            delete_post_meta($post_id, '_elementor_element_cache');
            delete_post_meta($post_id, '_elementor_page_assets');
            delete_post_meta($post_id, '_elementor_css');
        } catch (\Exception $e) {
            do_action('miruni_plugin_error', $e, [
                'context' => 'Miruni_Elementor_Service.delete_element_cache',
                'operation' => "Deleting post meta for post_id: $post_id",
                'user_id' => get_current_user_id() // Optional: add user context
            ]);
        }
    }

    /**
     * Checks if the site uses the Elementor builder by verifying the active theme.
     * @return bool True if the active theme uses Elementor, false otherwise.
     */
    public static function is_current_page_elementor(int $post_id): bool
    {
        if (!class_exists('Elementor\Plugin')) {
            return false;
        }


        try {
            // @phpstan-ignore class.notFound
            return \Elementor\Plugin::$instance->documents->get($post_id)->is_built_with_elementor();
        } catch (\Exception $e) {
            do_action('miruni_plugin_error', $e, [
                'context' => 'Miruni_Elementor_Service.is_current_page_elementor',
                'operation' => "Checking if post_id: $post_id is built with Elementor",
                'user_id' => get_current_user_id()
            ]);
            return false;
        }
    }
}