<?php

/**
 * Plugin Name: Giraforms
 * Description: A powerful form builder plugin for Gutenberg. Create forms easily with custom blocks.
 * Version: 1.6.3
 * Author: Mickaël Larguier
 * Author URI: https://mickaellarguier.com
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: giraforms
 * Domain Path: /languages
 * Requires at least: 6.2
 * Tested up to: 7.0
 * Requires PHP: 7.4
 *
 * @package Giraforms
 */
// Exit if accessed directly.
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * Freemius auto-deactivation mechanism.
 */
if ( function_exists( 'giraforms__fs' ) ) {
    giraforms__fs()->set_basename( false, __FILE__ );
} else {
    if ( !function_exists( 'giraforms__fs' ) ) {
        // Create a helper function for easy SDK access.
        function giraforms__fs() {
            global $giraforms__fs;
            if ( !isset( $giraforms__fs ) ) {
                // Include Freemius SDK.
                require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';
                $giraforms__fs = fs_dynamic_init( array(
                    'id'               => '23061',
                    'slug'             => 'giraforms',
                    'premium_slug'     => 'giraforms-pro',
                    'type'             => 'plugin',
                    'public_key'       => 'pk_a12afffdbf0d9135a11f415c8f23a',
                    'is_premium'       => false,
                    'premium_suffix'   => 'Pro',
                    'has_addons'       => false,
                    'has_paid_plans'   => true,
                    'is_org_compliant' => true,
                    'menu'             => array(
                        'slug'    => 'giraforms',
                        'support' => false,
                    ),
                    'is_live'          => true,
                ) );
            }
            return $giraforms__fs;
        }

        // Init Freemius.
        giraforms__fs();
        // Signal that SDK was initiated.
        do_action( 'giraforms__fs_loaded' );
    }
    // Define plugin constants.
    define( 'GIRAFORMS_VERSION', '1.6.3' );
    define( 'GIRAFORMS_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
    define( 'GIRAFORMS_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
    define( 'GIRAFORMS_PLUGIN_FILE', __FILE__ );
    define( 'GIRAFORMS_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
    /**
     * Main GiraForms Class
     */
    final class GiraForms {
        /**
         * Plugin instance.
         *
         * @var GiraForms
         */
        private static $instance = null;

        /**
         * Get plugin instance.
         *
         * @return GiraForms
         */
        public static function instance() {
            if ( is_null( self::$instance ) ) {
                self::$instance = new self();
            }
            return self::$instance;
        }

        /**
         * Constructor.
         */
        private function __construct() {
            $this->init_hooks();
            $this->includes();
        }

        /**
         * Initialize hooks.
         */
        private function init_hooks() {
            add_action( 'plugins_loaded', array($this, 'init') );
            add_action( 'plugins_loaded', array($this, 'maybe_upgrade_db'), 5 );
            register_activation_hook( GIRAFORMS_PLUGIN_FILE, array($this, 'activate') );
            register_deactivation_hook( GIRAFORMS_PLUGIN_FILE, array($this, 'deactivate') );
        }

        /**
         * Include required files.
         */
        private function includes() {
            // Encryption helpers (must be loaded first).
            require_once GIRAFORMS_PLUGIN_DIR . 'includes/class-encryption.php';
            // Core classes
            require_once GIRAFORMS_PLUGIN_DIR . 'includes/class-database.php';
            require_once GIRAFORMS_PLUGIN_DIR . 'includes/class-blocks-manager.php';
            require_once GIRAFORMS_PLUGIN_DIR . 'includes/class-form-handler.php';
            require_once GIRAFORMS_PLUGIN_DIR . 'includes/class-email-notifications.php';
            require_once GIRAFORMS_PLUGIN_DIR . 'includes/class-validation.php';
            require_once GIRAFORMS_PLUGIN_DIR . 'includes/class-submissions.php';
            require_once GIRAFORMS_PLUGIN_DIR . 'includes/class-export.php';
            // Admin classes
            if ( is_admin() ) {
                require_once GIRAFORMS_PLUGIN_DIR . 'includes/admin/class-admin-menu.php';
                require_once GIRAFORMS_PLUGIN_DIR . 'includes/admin/class-submissions-list.php';
                require_once GIRAFORMS_PLUGIN_DIR . 'includes/admin/class-settings.php';
                require_once GIRAFORMS_PLUGIN_DIR . 'includes/admin/class-integrations.php';
            }
        }

        /**
         * Initialize plugin.
         */
        public function init() {
            // Load translations before class initialization.
            $this->load_translations();
            // Initialize core functionality
            GiraForms_Database::instance();
            GiraForms_Blocks_Manager::instance();
            GiraForms_Form_Handler::instance();
            GiraForms_Email_Notifications::instance();
            if ( is_admin() ) {
                GiraForms_Admin_Menu::instance();
                GiraForms_Settings::instance();
                GiraForms_Integrations::instance();
            }
            do_action( 'giraforms_init' );
        }

        /**
         * Load plugin translations.
         */
        private function load_translations() {
            $locale = ( function_exists( 'determine_locale' ) ? determine_locale() : get_locale() );
            $locale = apply_filters( 'plugin_locale', $locale, 'giraforms' );
            $this->load_wp_translations( $locale );
        }

        /**
         * Load translations using standard WordPress naming.
         *
         * @param string $locale Current locale.
         */
        private function load_wp_translations( $locale ) {
            $mofile = 'giraforms-' . $locale . '.mo';
            $paths = array(WP_LANG_DIR . '/plugins/' . $mofile, GIRAFORMS_PLUGIN_DIR . 'languages/' . $mofile);
            foreach ( $paths as $path ) {
                if ( file_exists( $path ) ) {
                    load_textdomain( 'giraforms', $path, $locale );
                    return;
                }
            }
        }

        /**
         * Plugin activation.
         */
        public function activate() {
            GiraForms_Database::instance()->create_tables();
            flush_rewrite_rules();
        }

        /**
         * Run DB upgrades when the plugin is updated.
         */
        public function maybe_upgrade_db() {
            $installed = get_option( 'giraforms_db_version', '0' );
            if ( version_compare( $installed, GIRAFORMS_VERSION, '<' ) ) {
                GiraForms_Database::instance()->create_tables();
            }
        }

        /**
         * Plugin deactivation.
         */
        public function deactivate() {
            wp_clear_scheduled_hook( 'giraforms_stats_cleanup' );
            flush_rewrite_rules();
        }

    }

    /**
     * Cleanup function for uninstall via Freemius.
     * This function is called after Freemius tracks the uninstall event.
     */
    function giraforms__fs_uninstall_cleanup() {
        global $wpdb;
        /**
         * Get plugin settings to check if user wants to delete data
         */
        $settings = get_option( 'giraforms_settings', array() );
        // Only delete data if the user has opted in via settings
        if ( !isset( $settings['delete_data_on_uninstall'] ) || $settings['delete_data_on_uninstall'] !== '1' ) {
            // User doesn't want to delete data, exit early
            return;
        }
        /**
         * User has opted to delete all data
         * Proceed with cleanup
         */
        // 1. Delete all submissions and meta tables
        $submissions_table = $wpdb->prefix . 'giraforms_submissions';
        $submission_meta_table = $wpdb->prefix . 'giraforms_submission_meta';
        // Drop submissions table
        if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $submissions_table ) ) === $submissions_table ) {
            $wpdb->query( "DROP TABLE IF EXISTS {$submissions_table}" );
        }
        // Drop submission meta table
        if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $submission_meta_table ) ) === $submission_meta_table ) {
            $wpdb->query( "DROP TABLE IF EXISTS {$submission_meta_table}" );
        }
        // Drop form stats table
        $form_stats_table = $wpdb->prefix . 'giraforms_form_stats';
        $wpdb->query( "DROP TABLE IF EXISTS {$form_stats_table}" );
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        // 2. Delete all plugin options
        delete_option( 'giraforms_settings' );
        delete_option( 'giraforms_version' );
        delete_option( 'giraforms_db_version' );
        // 3. Delete transients
        delete_transient( 'giraforms_stats' );
        delete_transient( 'giraforms_update_check' );
        // 4. Delete any other stored options (search for giraforms_ prefix)
        $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", 'giraforms_%' ) );
        $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", '_transient_giraforms_%' ) );
        $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", '_transient_timeout_giraforms_%' ) );
        // 5. For multisite, delete from all sites
        if ( is_multisite() ) {
            // Get all blogs
            $blog_ids = $wpdb->get_col( "SELECT blog_id FROM {$wpdb->blogs}" );
            foreach ( $blog_ids as $blog_id ) {
                switch_to_blog( $blog_id );
                // Delete submissions tables for this site
                $submissions_table = $wpdb->prefix . 'giraforms_submissions';
                $submission_meta_table = $wpdb->prefix . 'giraforms_submission_meta';
                if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $submissions_table ) ) === $submissions_table ) {
                    $wpdb->query( "DROP TABLE IF EXISTS {$submissions_table}" );
                }
                if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $submission_meta_table ) ) === $submission_meta_table ) {
                    $wpdb->query( "DROP TABLE IF EXISTS {$submission_meta_table}" );
                }
                // Delete options for this site
                delete_option( 'giraforms_settings' );
                delete_option( 'giraforms_version' );
                delete_option( 'giraforms_db_version' );
                delete_transient( 'giraforms_stats' );
                delete_transient( 'giraforms_update_check' );
                $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", 'giraforms_%' ) );
                $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", '_transient_giraforms_%' ) );
                $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", '_transient_timeout_giraforms_%' ) );
                restore_current_blog();
            }
            // Delete network-wide options
            delete_site_option( 'giraforms_settings' );
            delete_site_option( 'giraforms_version' );
        }
        // 6. Clear any cached data
        wp_cache_flush();
    }

    // Hook into Freemius uninstall action.
    giraforms__fs()->add_action( 'after_uninstall', 'giraforms__fs_uninstall_cleanup' );
    /**
     * Returns the main instance of GiraForms.
     *
     * @return GiraForms
     */
    function giraforms() {
        return GiraForms::instance();
    }

    // Initialize the plugin.
    giraforms();
}