<?php
/**
 * Plugin Name: Trifuxion Tools - Repeater
 * Description: A powerful Elementor tool that makes ACF repeater managing easy!
 * Author: Carl Emmanuel Bagno Basquial
 * Author URI: https://plugins.carl-basquial.com
 * Version: 1.0.0
 * Text Domain: trifuxion-tools-repeater
 * Domain Path: /languages
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 *
 * Requires Plugins: elementor
 * Elementor tested up to: 3.25.0
 * Elementor Pro tested up to: 3.25.0
 */

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if ( ! defined( 'ABSPATH' ) ) exit;

require_once __DIR__ . '/vendor/autoload.php';

if ( ! function_exists( 'tlr_fs' ) ) {
    // Create a helper function for easy SDK access.
    function tlr_fs() {
        global $tlr_fs;

        if ( ! isset( $tlr_fs ) ) {
            // Include Freemius SDK.
            // SDK is auto-loaded through composer
            $tlr_fs = fs_dynamic_init( array(
                'id'                  => '19480',
                'slug'                => 'trifuxion-labs-repeater',
                'type'                => 'plugin',
                'public_key'          => 'pk_aa9d8269df407d44a11381c53dae1',
                'is_premium'          => true,
                'premium_suffix'      => 'Premium',
                // If your plugin is a serviceware, set this option to false.
                'has_premium_version' => true,
                'has_addons'          => false,
                'has_paid_plans'      => true,
                'menu'                => array(
                    'first-path'     => 'plugins.php',
                    'support'        => false,
                ),
            ) );
        }

        return $tlr_fs;
    }

    // Init Freemius.
    tlr_fs();
    // Signal that SDK was initiated.
    do_action( 'tlr_fs_loaded' );
}

define('TRFX_TOOLS_SWIPER_DIR', plugin_dir_path(__FILE__));
define('TRFX_TOOLS_SWIPER_URL', plugin_dir_url(__FILE__));
require_once TRFX_TOOLS_SWIPER_DIR . 'admin/index.php';

add_action('elementor/widgets/register', function($widgets_manager) {
    require_once TRFX_TOOLS_SWIPER_DIR . 'widgets/trfx-repeater.php';
    $widgets_manager->register( new \Trfx_Repeater_Widget() );
});

add_action('wp_enqueue_scripts', function() {
});

add_action('elementor/init', function () {
    \Elementor\Plugin::instance()->elements_manager->add_category(
        'trfx-tools',
        [
            'title' => esc_html__('Trfx Toolkit', 'trfx-tools-repeater'),
            'icon'  => 'fa fa-plug',
        ]
    );
});

add_action('elementor/editor/after_enqueue_scripts', function () {
    wp_enqueue_script(
        'trfx-repeater-editor',
        plugin_dir_url(__FILE__) . 'assets/js/trfx-repeater-editor.js',
        ['jquery'], // <-- IMPORTANT: this ensures jQuery is loaded
        '1.0',
        true
    );

    // Provide ajaxurl to JS
    wp_localize_script('trfx-repeater-editor', 'trfxRepeaterAjax', [
        'ajaxurl' => admin_url('admin-ajax.php')
    ]);
});

add_action('elementor/editor/after_enqueue_scripts', function () {
    ?>
    <script>
        function updateTrfxTargets() {
            jQuery(function ($) {
                $('[trfx-target]').each(function () {
                    const $label = $(this);
                    const targetKey = $label.attr('trfx-target');
                    const $input = $(`input[data-setting="${targetKey}"]`);
                    if ($input.length) {
                        $label.text($input.val());
                    }
                });
            });
        }
        (function () {
            // function waitForjQuery(callback) {
            //     if (typeof jQuery === 'undefined') {
            //         return setTimeout(() => waitForjQuery(callback), 100);
            //     }
            //     callback(jQuery);
            // }

            // function waitForElementor($) {
            //     if (typeof elementor === 'undefined' || typeof elementor.hooks === 'undefined') {
            //         return setTimeout(() => waitForElementor($), 100);
            //     }

            //     elementor.hooks.addAction('panel/open_editor/widget', function(panel, model, view) {
            //         if (model.get('widgetType') !== 'trfx_repeater') return;
            //         if (typeof updateTrfxTargets === 'function') {
            //             updateTrfxTargets();
            //         }
            //     });
                
            //     elementor.hooks.addAction( 'panel/open_editor/widget/slider', function( panel, model, view ) {
            //         setTimeout(() => {
            //             updateTrfxTargets();
            //         }, 10);
            //     });
            // }
            
            function runWhenReady() {
                if (typeof jQuery === 'undefined' || typeof elementor === 'undefined') {
                    return setTimeout(runWhenReady, 100);
                }

                jQuery(function ($) {
                    if ($('#trfx-loader').length === 0) {
                        $('body').append(`
                            <div id="trfx-loader">
                                <div class="trfx-spinner" style="
                                    border: 6px solid #f3f3f3;
                                    border-top: 6px solid #3498db;
                                    border-radius: 50%;
                                    width: 50px;
                                    height: 50px;
                                    animation: trfx-spin 1s linear infinite;
                                    margin-bottom: 15px;
                                "></div>
                                <div style="
                                    color: white;
                                    font-size: 20px;
                                    font-family: Arial, sans-serif;
                                ">Loading...</div>
                            </div>

                            <style>
                                @keyframes trfx-spin {
                                    0% { transform: rotate(0deg); }
                                    100% { transform: rotate(360deg); }
                                }
                                #trfx-loader {
                                    display: none !important;
                                    opacity: 0;
                                    position: fixed;
                                    top: 0; left: 0;
                                    width: 100%; height: 100%;
                                    background: rgba(0,0,0,0.4);
                                    z-index: 10000;
                                    justify-content: center;
                                    align-items: center;
                                    flex-direction: column;
                                    transition: opacity 0.15s ease-in-out;
                                }
                                #trfx-loader.show {
                                    display: flex !important;
                                    opacity: 1;
                                }
                            </style>
                        `);
                    }

                    if ($('#trfx-layout-modal').length === 0) {
                        $('body').append(`
                            <div id="trfx-layout-modal" style="display:none;position:fixed;top:0;left:0;
                                width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:9999;">
                                <div id="trfx-modal-content" style="
                                    position: fixed !important;
                                    transform: translate(-50%, -50%);
                                    left: 50%;
                                    top: 50%;
                                    background: #212121;
                                    padding: 20px;
                                    width: 520px;
                                    margin: auto auto;">
                                </div>
                            </div>
                        `);
                    }

                    $(document).on('click', '#close-layout-modal', function () {
                        $('#trfx-layout-modal').fadeOut(200);
                    });

                    $(document).on('click', '[trfx-data-link]', function () {

                        const model = elementor.getPanelView().getCurrentPageView().model;
                        const $el = $(this);
                        const method = $el.attr('trfx-data-link');
                        if (!method) return;

                        const hook = $el.attr('trfx-hook');
                        let extraData = {};

                        if (hook) {
                            const panelView = elementor.getPanelView();
                            const model = panelView?.getCurrentPageView?.()?.model;
                            if (model) {
                                const hookValue = model.getSetting(hook) || 0;
                                extraData.old_value = typeof hookValue === 'object' ? JSON.stringify(hookValue) : hookValue;
                                extraData.hook = hook; // 👈 Add this line
                            }
                        }

                        $('#trfx-loader').addClass('show');

                        $.post(ajaxurl, {
                            action: 'trfx_dynamic_modal_action',
                            method: method,
                            ...extraData
                        }).done(function (response) {
                            if (response.success) {
                                const $modal = $('#trfx-layout-modal');
                                const $content = $('#trfx-modal-content');

                                if ($modal.length && $content.length) {
                                    $content.html(
                                        '<span id="close-layout-modal" style="position:absolute;right:10px;top:10px;cursor:pointer;">&times;</span>' + 
                                        response.data);
                                    $modal.fadeIn(200);

                                    $content.find('script').each(function () {
                                        $.globalEval(this.text || this.textContent || this.innerHTML || '');
                                    });
                                } else {
                                    alert('Modal wrapper missing.');
                                }
                            } else {
                                alert(response.data || 'Modal handler failed.');
                            }
                        }).fail(function(jqXHR, textStatus, errorThrown) {
                            alert('AJAX request failed: ' + textStatus + ', ' + errorThrown);
                            console.error('Response text:', jqXHR.responseText);
                        }).always(function () {
                            $('#trfx-loader').removeClass('show');
                        });
                    });
                });
            }

            // waitForjQuery(waitForElementor);
            runWhenReady();
        })();

    </script>
    <?php
});

add_action('wp_ajax_trfx_dynamic_modal_action', function () {
    $method = sanitize_key($_POST['method'] ?? '');

    if (!$method) {
        wp_send_json_error('No method specified.');
    }

    do_action('trfx_register_modal_handlers');

    $oldValue = json_decode(stripslashes($_POST['old_value']), true);
    $hook = $_POST['hook'] ?? '';

    $userClasses = array_filter(get_declared_classes(), function ($class) {
        $reflect = new ReflectionClass($class);
        return !$reflect->isInternal();
    });

    foreach ($userClasses as $class) {
        if (method_exists($class, $method)) {
            try {
                $instance = new $class;
                $reflection = new ReflectionMethod($instance, $method);

                ob_start();
                if ($reflection->getNumberOfParameters() === 2) {
                    $instance->$method($oldValue, $hook);
                } elseif ($reflection->getNumberOfParameters() === 1) {
                    $instance->$method($oldValue);
                } else {
                    $instance->$method();
                }

                $output = ob_get_clean();

                wp_send_json_success($output);
            } catch (Throwable $e) {
                wp_send_json_error('Modal handler error: ' . $e->getMessage());
            }
        }
    }

    wp_send_json_error("Handler for method '{$method}' not found.");
});

function trfx_load_modal_files() {
    $modals_dir = plugin_dir_path(__FILE__) . 'modals';

    if (is_dir($modals_dir)) {
        foreach (glob($modals_dir . '/*.php') as $file) {
            include_once $file;
        }
    }
}
add_action('plugins_loaded', 'trfx_load_modal_files');


add_action('wp_ajax_get_acf_repeater_preview', function() {
    $post_id = absint($_POST['post_id'] ?? 0);
    $acf_key = sanitize_text_field($_POST['acf_key'] ?? '');
    $fields = array_map('sanitize_text_field', $_POST['fields'] ?? []);

    if (!$post_id || !$acf_key || empty($fields)) {
        wp_send_json_error('Invalid request');
    }

    $data = get_field($acf_key, $post_id);
    if (!is_array($data)) {
        wp_send_json_error('No data');
    }

    $result = array_map(function($row) use ($fields) {
        $out = [];
        foreach ($fields as $field) {
            $out[$field] = $row[$field] ?? '';
        }
        return $out;
    }, $data);

    wp_send_json_success($result);
});


// add_action( 'elementor/element/heading/section_title/after_section_end', function( $element, $args ) {

//     $repeater_fields = get_acf_repeater_fields();

//     $element->start_controls_section(
//         'custom_section_content',
//         [
//             'label' => __( 'ACF Repeater sub-field', 'trfx-tools-repeater' ),
//             'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
//         ]
//     );

//     // 1st dropdown - Select repeater field
//     $element->add_control(
//         'acf_repeater_field',
//         [
//             'label' => __('Select ACF Repeater Field', 'trfx-tools-repeater'),
//             'type' => \Elementor\Controls_Manager::SELECT,
//             'options' => $repeater_fields,
//             'default' => '',
//         ]
//     );

//     $element->add_control(
//         'acf_repeater_subfield',
//         [
//             'label' => __('Repeater Sub Field', 'trfx-tools-repeater'),
//             'type' => \Elementor\Controls_Manager::TEXT,
//             'default' => '',
//             'condition' => [
//                 'acf_repeater_field!' => '',
//             ],
//             'input_attrs' => [
//                 'readonly' => 'readonly',
//                 'placeholder' => __('No subfield selected', 'trfx-tools-repeater'),
//                 'style' => 'background:#f9f9f9; cursor: default;',
//             ],
//         ]
//     );

//     $element->end_controls_section();


// }, 10, 2 );

