<?php
/**
 * Plugin Name: ID Visual Editor
 * Plugin URI:  https://insightdezign.com/plugin/id-visual-editor
 * Description: A lightweight visual row/column/block builder that produces clean HTML and CSS with zero frontend JavaScript dependencies.
 * Version:     1.1.0
 * Author:      Insight Dezign
 * Author URI:  https://insightdezign.com
 * License:     GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: insight-dezign-visual-editor
 * Requires at least: 5.8
 * Requires PHP: 7.4
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

define( 'IDVE_VERSION', '1.1.0' );
define( 'IDVE_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'IDVE_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'IDVE_PLUGIN_FILE', __FILE__ );

/* ------------------------------------------------------------------ */
/*  Freemius SDK integration                                           */
/* ------------------------------------------------------------------ */
if ( ! function_exists( 'idve_fs' ) ) {
    function idve_fs() {
        global $idve_fs;

        if ( ! isset( $idve_fs ) ) {
            require_once dirname( __FILE__ ) . '/vendor/freemius/wordpress-sdk/start.php';

            $idve_fs = fs_dynamic_init( array(
                'id'                  => '24568',
                'slug'                => 'id-visual-editor',
                'type'                => 'plugin',
                'public_key'          => 'pk_d9c775c723024c709ecccad746ad1',
                'is_premium'          => false,
                'has_addons'          => false,
                'has_paid_plans'      => true,
                'is_org_compliant'    => true,
                'menu'                => array(
                    'slug'           => 'idve-settings',
                    'first-path'     => 'options-general.php?page=idve-settings',
                    'account'        => false,
                    'contact'        => false,
                    'support'        => false,
                    'parent'         => array(
                        'slug' => 'options-general.php',
                    ),
                ),
            ) );
        }

        return $idve_fs;
    }

    // Init Freemius.
    idve_fs();
    // Signal that SDK was initiated.
    do_action( 'idve_fs_loaded' );

    // Uninstall cleanup.
    idve_fs()->add_action( 'after_uninstall', 'idve_fs_uninstall_cleanup' );
}

/**
 * Freemius uninstall cleanup.
 */
function idve_fs_uninstall_cleanup() {
    global $wpdb;

    // Delete plugin options.
    delete_option( 'idve_settings' );
    delete_option( 'idve_ai_settings' );
    delete_option( 'idve_global_styles' );

    // Delete post meta.
    $meta_keys = array( '_idve_data', '_idve_css', '_idve_active', '_idve_autosave', '_idve_content_hash' );
    foreach ( $meta_keys as $key ) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.SlowDBQuery.slow_db_query_meta_key
        $wpdb->delete( $wpdb->postmeta, array( 'meta_key' => $key ) );
    }

    // Remove mu-plugin.
    $mu_file = WPMU_PLUGIN_DIR . '/idve-frontend-persist.php';
    if ( file_exists( $mu_file ) ) {
        wp_delete_file( $mu_file );
    }

    // Remove global styles file.
    $upload_dir = wp_upload_dir();
    $styles_file = $upload_dir['basedir'] . '/idve-global-styles.css';
    if ( file_exists( $styles_file ) ) {
        wp_delete_file( $styles_file );
    }
}

/**
 * Check if Pro license is active.
 *
 * @return bool
 */
function idve_is_pro() {
    if ( function_exists( 'idve_fs' ) && idve_fs()->can_use_premium_code() ) {
        return true;
    }
    return false;
}

require_once IDVE_PLUGIN_DIR . 'includes/class-idve-core.php';
require_once IDVE_PLUGIN_DIR . 'api/idve-block-api.php';

register_activation_hook( __FILE__, 'idve_activate' );
register_deactivation_hook( __FILE__, 'idve_deactivate' );

function idve_activate() {
    $defaults = get_option( 'idve_settings', array() );
    if ( empty( $defaults ) ) {
        update_option( 'idve_settings', array(
            'post_types' => array( 'post', 'page' ),
        ) );
    }

    // Create mu-plugin for FontAwesome + global styles persistence.
    $mu_dir = WPMU_PLUGIN_DIR;
    if ( ! is_dir( $mu_dir ) ) {
        wp_mkdir_p( $mu_dir );
    }
    $mu_file = $mu_dir . '/idve-frontend-persist.php';
    $content = "<?php\n"
        . "/* Plugin Name: IDVE Frontend Persistence */\n"
        . "add_action('wp_enqueue_scripts', function() {\n"
        . "    wp_enqueue_style('idve-fontawesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css', array(), '6.7.2');\n"
        . "    \$upload_dir = wp_upload_dir();\n"
        . "    \$grid = \$upload_dir['basedir'] . '/idve-grid.css';\n"
        . "    if (file_exists(\$grid)) {\n"
        . "        wp_enqueue_style('idve-grid', \$upload_dir['baseurl'] . '/idve-grid.css', array(), filemtime(\$grid));\n"
        . "    }\n"
        . "    \$global = \$upload_dir['basedir'] . '/idve-global-styles.css';\n"
        . "    if (file_exists(\$global)) {\n"
        . "        wp_enqueue_style('idve-global-styles', \$upload_dir['baseurl'] . '/idve-global-styles.css', array(), filemtime(\$global));\n"
        . "    }\n"
        . "});\n";
    file_put_contents( $mu_file, $content );

    // Remove old mu-plugin if upgrading from 0.1.20-beta.
    $old_mu = $mu_dir . '/idve-fontawesome.php';
    if ( file_exists( $old_mu ) ) {
        wp_delete_file( $old_mu );
    }
}

function idve_deactivate() {
    // Copy the grid stylesheet to the uploads directory so it persists
    // after the plugin folder is deleted.
    $upload_dir = wp_upload_dir();
    $src        = IDVE_PLUGIN_DIR . 'frontend/css/idve-grid.css';
    $dest       = trailingslashit( $upload_dir['basedir'] ) . 'idve-grid.css';
    if ( file_exists( $src ) ) {
        copy( $src, $dest );
    }
}

/**
 * Show a confirmation dialog when deactivating the plugin from the
 * plugins page, warning the user to copy the grid CSS to their theme.
 */
function idve_deactivation_warning() {
    $plugin_file = plugin_basename( IDVE_PLUGIN_FILE );
    ?>
    <script>
    (function(){
        var row = document.querySelector('tr[data-plugin="<?php echo esc_js( $plugin_file ); ?>"]');
        if (!row) return;
        var link = row.querySelector('.deactivate a');
        if (!link) return;
        link.addEventListener('click', function(e) {
            if (!confirm(
                'Your page layouts, global styles, and FontAwesome icons will continue working via a must-use plugin (mu-plugins/idve-frontend-persist.php).\n\n' +
                'Delete that file if you no longer need them.\n\n' +
                'Proceed with deactivation?'
            )) {
                e.preventDefault();
            }
        });
    })();
    </script>
    <?php
}
add_action( 'admin_footer-plugins.php', 'idve_deactivation_warning' );

add_action( 'plugins_loaded', array( 'IDVE_Core', 'instance' ) );
