<?php

/**
 * Freemius SDK bootstrap for 3D Product Customizer.
 *
 *
 * @package ProductCustomizer
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
if ( !function_exists( 'dprcu_fs' ) ) {
    /**
     * Returns the Freemius singleton for this plugin, or null if the SDK is not installed.
     *
     * @return Freemius|null
     */
    function dprcu_fs() {
        global $dprcu_fs;
        if ( isset( $dprcu_fs ) ) {
            return $dprcu_fs;
        }
        $root = plugin_dir_path( dirname( __FILE__ ) );
        $autoload = $root . 'vendor/autoload.php';
        $sdk = $root . 'vendor/freemius/wordpress-sdk/start.php';
        // Skip init when Composer dependencies are not installed yet.
        if ( !file_exists( $autoload ) || !file_exists( $sdk ) ) {
            $dprcu_fs = null;
            return null;
        }
        require_once $autoload;
        require_once $sdk;
        $dprcu_fs = fs_dynamic_init( array(
            'id'                    => '26799',
            'slug'                  => '3d-product-customizer',
            'premium_slug'          => '3d-customizer-premium',
            'plugin_main_file_path' => dirname( dirname( __FILE__ ) ) . '/product-customizer.php',
            'type'                  => 'plugin',
            'public_key'            => 'pk_dba046c8a58bfafc6268115946a43',
            'is_premium'            => false,
            'has_addons'            => false,
            'has_paid_plans'        => true,
            'is_org_compliant'      => true,
            'menu'                  => array(
                'slug'       => 'dprcu-settings',
                'first-path' => 'admin.php?page=dprcu-settings',
                'account'    => true,
                'support'    => false,
            ),
            'is_live'               => true,
        ) );
        return $dprcu_fs;
    }

    // Initialise early so Freemius hooks register in time.
    dprcu_fs();
    do_action( 'dprcu_fs_loaded' );
}
/**
 * Returns the URL to the in-dashboard pricing / plan selection page.
 *
 * Uses the Freemius SDK when available; falls back to the hosted
 * checkout page so the link never leads to a dead admin page.
 *
 * @return string
 */
function dprcu_upgrade_url() {
    $fs = dprcu_fs();
    if ( $fs ) {
        return $fs->get_upgrade_url();
    }
    return 'https://checkout.freemius.com/mode/dialog/plugin/26799/';
}

/**
 * Returns the checkout URL for purchasing a license.
 *
 * Uses the Freemius SDK when available; falls back to the hosted
 * checkout page so the link never leads to a dead admin page.
 *
 * @return string
 */
function dprcu_checkout_url() {
    $fs = dprcu_fs();
    if ( $fs ) {
        return $fs->checkout_url();
    }
    return 'https://checkout.freemius.com/mode/dialog/plugin/26799/';
}

/**
 * Returns true when the current site does NOT have an active paid license.
 *
 * Useful for showing marketing sections even on the premium codebase when a
 * license has expired (Freemius calls these "non-paying" users).
 *
 * @return bool
 */
function dprcu_is_not_paying() {
    if ( defined( 'PSC_FORCE_PREMIUM' ) && PSC_FORCE_PREMIUM ) {
        return false;
    }
    $dprcu_fs = dprcu_fs();
    return !$dprcu_fs || $dprcu_fs->is_not_paying();
}

/**
 * Outputs a reusable admin upgrade notice comparing free vs premium features.
 *
 * CSS is inlined once per page load via a static flag so the function can be
 * called multiple times without duplicating styles.
 *
 * @param array $args {
 *     @type string   $title            Heading text for the notice.
 *     @type string[] $free_features    List of features the free tier includes.
 *     @type string[] $premium_features List of features unlocked by premium.
 * }
 */
function dprcu_premium_notice(  $args = array()  ) {
    $title = $args['title'] ?? __( 'Upgrade to Premium', '3d-product-customizer' );
    $free_features = $args['free_features'] ?? array();
    $premium_features = $args['premium_features'] ?? array();
    ?>
	<div class="dprcu-upgrade-notice">
		<div class="dprcu-upgrade-header">
			<span class="dashicons dashicons-lock"></span>
			<strong><?php 
    echo esc_html( $title );
    ?></strong>
		</div>
		<div class="dprcu-upgrade-columns">
			<div class="dprcu-upgrade-col dprcu-col-free">
				<div class="dprcu-upgrade-col-label"><?php 
    esc_html_e( 'You have (Free)', '3d-product-customizer' );
    ?></div>
				<ul>
					<?php 
    foreach ( $free_features as $feature ) {
        ?>
						<li><span class="dashicons dashicons-yes-alt"></span><?php 
        echo esc_html( $feature );
        ?></li>
					<?php 
    }
    ?>
				</ul>
			</div>
			<div class="dprcu-upgrade-col dprcu-col-premium">
				<div class="dprcu-upgrade-col-label"><?php 
    esc_html_e( 'Premium', '3d-product-customizer' );
    ?></div>
				<ul>
					<?php 
    foreach ( $premium_features as $feature ) {
        ?>
						<li><span class="dashicons dashicons-star-filled"></span><?php 
        echo esc_html( $feature );
        ?></li>
					<?php 
    }
    ?>
				</ul>
			</div>
		</div>
		<div class="dprcu-upgrade-footer">
			<a href="<?php 
    echo esc_url( dprcu_checkout_url() );
    ?>" class="notice-btn" target="_blank"
				rel="noopener noreferrer">
				<?php 
    esc_html_e( 'Upgrade to Premium', '3d-product-customizer' );
    ?>
			</a>
		</div>
	</div>
	<?php 
}

/**
 * Enqueue styles for premium notice component.
 *
 * Loads premium-notice.css on admin pages where it's needed.
 */
function dprcu_enqueue_premium_notice_styles() {
    wp_enqueue_style(
        'dprcu-premium-notice',
        plugins_url( 'admin/css/premium-notice.css', dirname( __FILE__ ) ),
        array(),
        ( filemtime( plugin_dir_path( dirname( __FILE__ ) ) . 'admin/css/premium-notice.css' ) ?: '1.0' )
    );
}

add_action( 'admin_enqueue_scripts', 'dprcu_enqueue_premium_notice_styles' );
/**
 * Cleanup plugin data when uninstalled via Freemius.
 *
 * Removes all plugin options, post meta, and posts created by 3D Product Customizer.
 * Does NOT delete uploaded media files — those belong to the site owner.
 */
function dprcu_handle_uninstall() {
    // Only wipe data if the user has explicitly opted in via the plugin settings.
    // Defaults to false — this protects data when switching between free and premium.
    $options = get_option( 'dprcu_settings', [] );
    if ( empty( $options['delete_on_uninstall'] ) ) {
        return;
    }
    // Remove global settings option
    delete_option( 'dprcu_settings' );
    // Remove post meta from all products
    // _customizer_config and _3d_model_url may be on any 'product' post.
    delete_post_meta_by_key( '_dprcu_customizer_config' );
    delete_post_meta_by_key( '_dprcu_3d_model_url' );
    delete_post_meta_by_key( '_dprcu_3d_viewer_only' );
    // Remove all dprcu_model_texture posts and their own meta
    $texture_ids = get_posts( array(
        'post_type'      => 'dprcu_model_texture',
        'posts_per_page' => -1,
        'fields'         => 'ids',
        'post_status'    => 'any',
    ) );
    foreach ( $texture_ids as $id ) {
        wp_delete_post( $id, true );
        // true = force-delete, skip trash
    }
    // Clear any cached transients
    delete_transient( 'dprcu_all_textures' );
}

// Register uninstall handler with Freemius
$dprcu_fs = dprcu_fs();
if ( $dprcu_fs ) {
    $dprcu_fs->add_action( 'after_uninstall', 'dprcu_handle_uninstall' );
}