<?php
/**
 * Plugin Name: TNC FlipBook 3D Lite
 * Plugin URI:  https://tncflipbook.com
 * Description: Turn PDFs and images into interactive 3D page-flip books, with WebGL page-turning, dark and light themes, PDF text search, and clickable links.
 * Version:     1.0.0
 * Author:      ThemeNcode LLC
 * Author URI:  https://themencode.com
 * License:     GPL-2.0-or-later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: tnc-flipbook-3d-lite
 * Domain Path: /languages
 */

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

// ── Plugins-screen assets (enqueued, not inline) ─────────────────────────────
// Registered before the activation guard so it also covers the dual-activation
// notice. Loads only on the Plugins screen; the script no-ops when its target
// elements aren't present.
if ( ! function_exists( 'tncfb3d_lite_enqueue_plugins_assets' ) ) {
    function tncfb3d_lite_enqueue_plugins_assets( $hook ) {
        if ( 'plugins.php' !== $hook ) {
            return;
        }
        $ver = defined( 'TNC_FLIPBOOK_3D_VERSION' ) ? TNC_FLIPBOOK_3D_VERSION : '1.0.0';
        wp_enqueue_script(
            'tncfb3d-lite-plugins',
            plugins_url( 'admin/js/tncfb3d-lite-plugins.js', __FILE__ ),
            array(),
            $ver,
            true
        );
        wp_localize_script( 'tncfb3d-lite-plugins', 'tncfb3dLitePlugins', array(
            'ajaxUrl'         => admin_url( 'admin-ajax.php' ),
            'pluginFile'      => plugin_basename( __FILE__ ),
            'site'            => home_url(),
            'version'         => $ver,
            'deactivateNonce' => wp_create_nonce( 'tncfb3d_deactivate_lite' ),
            'feedbackNonce'   => wp_create_nonce( 'tncfb3d_deactivate_feedback' ),
            'i18n'            => array(
                'deactivating'     => __( 'Deactivating…', 'tnc-flipbook-3d-lite' ),
                'deactivateError'  => __( 'Error - deactivate manually', 'tnc-flipbook-3d-lite' ),
                'submitting'       => __( 'Submitting...', 'tnc-flipbook-3d-lite' ),
            ),
        ) );
    }
    add_action( 'admin_enqueue_scripts', 'tncfb3d_lite_enqueue_plugins_assets' );
}

// ── Guard against simultaneous Lite + Pro activation ────────────────────────
if ( defined( 'TNC_FLIPBOOK_3D_VERSION' ) ) {
    // AJAX handler to deactivate Lite via one click.
    add_action( 'wp_ajax_tncfb3d_deactivate_lite', function () {
        check_ajax_referer( 'tncfb3d_deactivate_lite' );
        if ( ! current_user_can( 'activate_plugins' ) ) {
            wp_send_json_error();
        }
        deactivate_plugins( plugin_basename( __FILE__ ) );
        wp_send_json_success();
    } );

    add_action( 'admin_notices', function () {
        // Behaviour handled by the enqueued tncfb3d-lite-plugins script.
        echo '<div class="notice notice-warning" id="tncfb-dual-notice"><p>';
        echo '<strong>TNC FlipBook 3D:</strong> ';
        esc_html_e( 'Both Lite and Pro versions are active. The Pro version is running.', 'tnc-flipbook-3d-lite' );
        echo ' <a href="#" id="tncfb-deactivate-lite" class="button button-small" style="margin-left:8px;">';
        esc_html_e( 'Deactivate Lite', 'tnc-flipbook-3d-lite' );
        echo '</a></p></div>';
    } );
    return;
}

// ── Pro flag (false in Lite, true in Pro) ───────────────────────────────────
if ( ! defined( 'TNC_FLIPBOOK_3D_PRO' ) ) {
    define( 'TNC_FLIPBOOK_3D_PRO', false );
}

// ── Constants ────────────────────────────────────────────────────────────────
if ( ! defined( 'TNC_FLIPBOOK_3D_VERSION' ) ) {
    define( 'TNC_FLIPBOOK_3D_VERSION', '1.0.0' );
}
if ( ! defined( 'TNC_FLIPBOOK_3D_FILE' ) ) {
    define( 'TNC_FLIPBOOK_3D_FILE',     __FILE__ );
}
if ( ! defined( 'TNC_FLIPBOOK_3D_DIR' ) ) {
    define( 'TNC_FLIPBOOK_3D_DIR',      plugin_dir_path( __FILE__ ) );
}
if ( ! defined( 'TNC_FLIPBOOK_3D_URL' ) ) {
    define( 'TNC_FLIPBOOK_3D_URL',      plugin_dir_url( __FILE__ ) );
}
if ( ! defined( 'TNC_FLIPBOOK_3D_CPT' ) ) {
    define( 'TNC_FLIPBOOK_3D_CPT', 'tnc_flipbook' );
}
if ( ! defined( 'TNC_FLIPBOOK_3D_OPTION' ) ) {
    define( 'TNC_FLIPBOOK_3D_OPTION',   'tnc_flipbook_3d_settings' );
}
if ( ! defined( 'TNC_FLIPBOOK_3D_PREFIX' ) ) {
    define( 'TNC_FLIPBOOK_3D_PREFIX',   '_tncfb3d_' );
}

if ( ! function_exists( 'tnc_flipbook_3d_is_pro' ) ) {
    /**
     * Check if this is the Pro version.
     *
     * @return bool
     */
    function tnc_flipbook_3d_is_pro() {
        return defined( 'TNC_FLIPBOOK_3D_PRO' ) && TNC_FLIPBOOK_3D_PRO;
    }
}

// ── Autoload includes ────────────────────────────────────────────────────────
require_once TNC_FLIPBOOK_3D_DIR . 'includes/tncfb3d-utm.php';
$tncfb3d_includes = array(
    'class-tnc-flipbook-3d-helpers',
    'class-tnc-flipbook-3d-meta-schema',
    'class-tnc-flipbook-3d-cpt',
    'class-tnc-flipbook-3d-admin',
    'class-tnc-flipbook-3d-settings',
    'class-tnc-flipbook-3d-config-builder',
    'class-tnc-flipbook-3d-frontend',
    'class-tnc-flipbook-3d-rest-proxy',
    'class-tnc-flipbook-3d-blocks',
    'class-tnc-flipbook-3d-seo',
    'class-tnc-flipbook-3d-text-extract',
    'class-tnc-flipbook-3d-tooltips',
);

foreach ( $tncfb3d_includes as $tncfb3d_file ) {
    require_once TNC_FLIPBOOK_3D_DIR . 'includes/' . $tncfb3d_file . '.php';
}

// ── Bootstrap ────────────────────────────────────────────────────────────────
if ( ! function_exists( 'tnc_flipbook_3d_init' ) ) {
    function tnc_flipbook_3d_init() {
        // Translations are served automatically by WordPress.org (since WP 4.6),
        // so no manual textdomain loading is needed here.

        TNC_Flipbook_3D_CPT::init();
        TNC_Flipbook_3D_Admin::init();
        TNC_Flipbook_3D_Settings::init();
        TNC_Flipbook_3D_Frontend::init();
        TNC_Flipbook_3D_REST_Proxy::init();
        TNC_Flipbook_3D_Blocks::init();
        TNC_Flipbook_3D_SEO::init();
        TNC_Flipbook_3D_Text_Extract::init();
    }
}
add_action( 'plugins_loaded', 'tnc_flipbook_3d_init' );

// ── Lite-only: Pro teaser styles (separate file so CSS sync from Pro doesn't wipe it) ──
add_action( 'admin_enqueue_scripts', function ( $hook ) {
    if ( false === strpos( $hook, 'flipbook' ) && 'post.php' !== $hook && 'post-new.php' !== $hook ) {
        return;
    }
    wp_enqueue_style(
        'tncfb3d-pro-teaser',
        TNC_FLIPBOOK_3D_URL . 'admin/css/tnc-flipbook-3d-pro-teaser.css',
        array( 'tncfb3d-admin' ),
        TNC_FLIPBOOK_3D_VERSION
    );
}, 20 );

// ── Attribution badge (opt-in) ───────────────────────────────────────────────
// WordPress.org build: the "Powered by" badge is OFF by default and only renders
// when the user explicitly enables it under Settings > Advanced. No forced links.
add_action( 'tncfb3d_viewer_body_end', function ( $post_id, $payload ) {
    $tncfb3d_attr_opts = get_option( TNC_FLIPBOOK_3D_OPTION, array() );
    if ( empty( $tncfb3d_attr_opts['show_attribution'] ) ) {
        return;
    }
    ?>
    <div id="tncfb-branding">
        <a href="<?php echo esc_url( tncfb3d_utm( 'https://tncflipbook.com/', 'attribution', 'viewer-branding', 'viewer' ) ); ?>" target="_blank" rel="noopener noreferrer">
            Powered by <strong>TNC FlipBook 3D</strong>
        </a>
    </div>
    <?php
}, 99, 2 );

// ── Activation / Deactivation ────────────────────────────────────────────────
register_activation_hook( __FILE__, 'tnc_flipbook_3d_activate' );
if ( ! function_exists( 'tnc_flipbook_3d_activate' ) ) {
    function tnc_flipbook_3d_activate() {
        TNC_Flipbook_3D_CPT::register();
        flush_rewrite_rules();
    }
}


register_deactivation_hook( __FILE__, 'tnc_flipbook_3d_deactivate' );
if ( ! function_exists( 'tnc_flipbook_3d_deactivate' ) ) {
    function tnc_flipbook_3d_deactivate() {
        flush_rewrite_rules();
    }
}

// ── Pro upgrade URL & promo ──────────────────────────────────────────────────
if ( ! defined( 'TNC_FLIPBOOK_PRO_URL' ) ) {
    define( 'TNC_FLIPBOOK_PRO_URL', 'https://tncflipbook.com/pricing/' );
}
if ( ! defined( 'TNC_FLIPBOOK_PROMO_CODE' ) ) {
    define( 'TNC_FLIPBOOK_PROMO_CODE', 'FLIPITUP' );
}
if ( ! defined( 'TNC_FLIPBOOK_PROMO_DISCOUNT' ) ) {
    define( 'TNC_FLIPBOOK_PROMO_DISCOUNT', '20%' );
}

// ── Public API for addons ───────────────────────────────────────────────────

if ( ! function_exists( 'tnc_flipbook_3d_get_cover_url' ) ) {
/**
 * Get the cover/thumbnail URL for a flipbook.
 */
function tnc_flipbook_3d_get_cover_url( $flipbook_id, $size = 'large' ) {
    $flipbook_id = absint( $flipbook_id );
    if ( ! $flipbook_id ) {
        return '';
    }

    $post = get_post( $flipbook_id );
    if ( ! $post || TNC_FLIPBOOK_3D_CPT !== $post->post_type ) {
        return '';
    }

    $p = TNC_FLIPBOOK_3D_PREFIX;

    // 1. Featured Image
    $thumb_url = get_the_post_thumbnail_url( $flipbook_id, $size );
    if ( $thumb_url ) {
        return $thumb_url;
    }

    $source_type = get_post_meta( $flipbook_id, $p . 'source_type', true );

    // 2. Image-based flipbook - first image
    if ( 'images' === $source_type ) {
        $image_ids = get_post_meta( $flipbook_id, $p . 'image_ids', true );
        if ( is_array( $image_ids ) && ! empty( $image_ids ) ) {
            $first_id = absint( reset( $image_ids ) );
            if ( $first_id ) {
                $url = wp_get_attachment_image_url( $first_id, $size );
                if ( $url ) {
                    return $url;
                }
            }
        }
    }

    // 3. Single PDF - WP-generated first-page thumbnail
    if ( 'pdf' === $source_type || '' === $source_type ) {
        $pdf_id = absint( get_post_meta( $flipbook_id, $p . 'pdf_id', true ) );
        if ( $pdf_id ) {
            $url = wp_get_attachment_image_url( $pdf_id, $size );
            if ( $url ) {
                return $url;
            }
        }
    }

    return '';
}
} // end function_exists tnc_flipbook_3d_get_cover_url

if ( ! function_exists( 'tnc_flipbook_3d_get_config' ) ) {
    /**
     * Get the full config + options payload for a flipbook.
     *
     * @param  int   $post_id
     * @return array { config: array, options: array }
     */
    function tnc_flipbook_3d_get_config( $post_id ) {
        return TNC_Flipbook_3D_Config_Builder::build( absint( $post_id ) );
    }
}

if ( ! function_exists( 'tnc_flipbook_3d_get_meta' ) ) {
    /**
     * Get all meta for a flipbook post (keys without prefix).
     *
     * @param  int   $post_id
     * @return array
     */
    function tnc_flipbook_3d_get_meta( $post_id ) {
        return TNC_Flipbook_3D_Admin::get_post_meta( absint( $post_id ) );
    }
}

if ( ! function_exists( 'tnc_flipbook_3d_update_meta' ) ) {
    /**
     * Update a single meta field on a flipbook post.
     *
     * @param  int    $post_id
     * @param  string $key     Meta key without prefix (e.g. 'source_type')
     * @param  mixed  $value
     * @return bool
     */
    function tnc_flipbook_3d_update_meta( $post_id, $key, $value ) {
        return update_post_meta( absint( $post_id ), TNC_FLIPBOOK_3D_PREFIX . sanitize_key( $key ), $value );
    }
}

if ( ! function_exists( 'tnc_flipbook_3d_get_all' ) ) {
    /**
     * Get all flipbook posts.
     *
     * @param  array $args  Optional WP_Query args to merge.
     * @return WP_Post[]
     */
    function tnc_flipbook_3d_get_all( $args = array() ) {
        $defaults = array(
            'post_type'      => TNC_FLIPBOOK_3D_CPT,
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'orderby'        => 'title',
            'order'          => 'ASC',
        );
        return get_posts( array_merge( $defaults, $args ) );
    }
}

if ( ! function_exists( 'tnc_flipbook_3d_get_setting' ) ) {
    /**
     * Get a single global setting value.
     *
     * @param  string $key
     * @param  mixed  $default
     * @return mixed
     */
    function tnc_flipbook_3d_get_setting( $key, $default = null ) {
        return TNC_Flipbook_3D_Settings::get( $key, $default );
    }
}

if ( ! function_exists( 'tnc_flipbook_3d_get_viewer_url' ) ) {
    /**
     * Get the standalone viewer URL for a flipbook.
     *
     * @param  int    $post_id
     * @return string
     */
    function tnc_flipbook_3d_get_viewer_url( $post_id ) {
        return add_query_arg( 'tncfb3d_viewer', absint( $post_id ), home_url( '/' ) );
    }
}

if ( ! function_exists( 'tnc_flipbook_3d_render' ) ) {
    /**
     * Render a flipbook embed (iframe HTML).
     *
     * @param  int   $post_id
     * @param  array $overrides  { width, height, iframe_title, class }
     * @return string
     */
    function tnc_flipbook_3d_render( $post_id, $overrides = array() ) {
        return TNC_Flipbook_3D_Frontend::render( absint( $post_id ), $overrides );
    }
}

// ── Upgrade to Pro (WordPress.org build) ─────────────────────────────────────
// A single, clearly-labelled upsell under the FlipBooks menu. The free plugin
// stays fully functional; this only links out to the paid version. No locked or
// disabled controls, no admin-wide notices, no remote requests.
if ( is_admin() ) {

	add_action( 'admin_menu', 'tncfb3d_wporg_upgrade_menu', 99 );
	/**
	 * Register the "Upgrade" submenu under the FlipBooks menu.
	 */
	function tncfb3d_wporg_upgrade_menu() {
		add_submenu_page(
			'edit.php?post_type=' . TNC_FLIPBOOK_3D_CPT,
			__( 'Upgrade to Pro', 'tnc-flipbook-3d-lite' ),
			'<span class="tncfb3d-upgrade-link">' . esc_html__( 'Upgrade', 'tnc-flipbook-3d-lite' ) . '</span>',
			'manage_options',
			'tncfb3d-upgrade',
			'tncfb3d_wporg_upgrade_page'
		);
	}

	add_action( 'admin_enqueue_scripts', 'tncfb3d_wporg_upgrade_style' );
	/**
	 * Highlight the menu item + style the upgrade page (enqueued inline, no
	 * inline <style> block, so Plugin Check stays clean).
	 */
	function tncfb3d_wporg_upgrade_style() {
		wp_register_style( 'tncfb3d-upgrade', false, array(), TNC_FLIPBOOK_3D_VERSION );
		wp_enqueue_style( 'tncfb3d-upgrade' );
		wp_add_inline_style(
			'tncfb3d-upgrade',
			'#adminmenu .tncfb3d-upgrade-link{color:#ffca28;font-weight:600}'
			. '.tncfb3d-upgrade-wrap{max-width:820px}'
			. '.tncfb3d-upgrade-card{background:#fff;border:1px solid #dcdcde;border-radius:8px;padding:24px 28px;margin-top:16px}'
			. '.tncfb3d-upgrade-card h2{margin-top:0}'
			. '.tncfb3d-upgrade-features{display:grid;grid-template-columns:1fr 1fr;gap:10px 24px;margin:18px 0 26px;padding:0;list-style:none}'
			. '.tncfb3d-upgrade-features li{padding-left:24px;position:relative}'
			. '.tncfb3d-upgrade-features li::before{content:"";position:absolute;left:2px;top:7px;width:8px;height:8px;border-radius:50%;background:#2271b1}'
		);
	}

	/**
	 * Render the upgrade page: what Pro adds + a link out to pricing.
	 */
	function tncfb3d_wporg_upgrade_page() {
		// Tag via the shared helper: utm_source=tnc-flipbook-3d-lite (this free
		// plugin), utm_medium=wp-admin, utm_campaign=upgrade, utm_content=upgrade-page.
		$tncfb3d_pro_url = function_exists( 'tncfb3d_utm' )
			? tncfb3d_utm( 'https://tncflipbook.com/pricing/', 'upgrade', 'upgrade-page' )
			: 'https://tncflipbook.com/pricing/';
		$tncfb3d_features = array(
			__( 'More interface languages', 'tnc-flipbook-3d-lite' ),
			__( 'All color schemes plus brand & hardcover colors', 'tnc-flipbook-3d-lite' ),
			__( 'Merge multiple PDFs with named chapters', 'tnc-flipbook-3d-lite' ),
			__( 'Interactive hotspots (links, media, products)', 'tnc-flipbook-3d-lite' ),
			__( 'AI read-aloud with premium voices', 'tnc-flipbook-3d-lite' ),
			__( 'Content protection & watermarks', 'tnc-flipbook-3d-lite' ),
			__( 'WooCommerce page gating', 'tnc-flipbook-3d-lite' ),
			__( 'Google Analytics 4 tracking', 'tnc-flipbook-3d-lite' ),
			__( 'Export & import flipbooks', 'tnc-flipbook-3d-lite' ),
			__( 'Page video overlays', 'tnc-flipbook-3d-lite' ),
			__( 'Priority support', 'tnc-flipbook-3d-lite' ),
		);
		?>
		<div class="wrap tncfb3d-upgrade-wrap">
			<h1><?php esc_html_e( 'Upgrade to TNC FlipBook 3D Pro', 'tnc-flipbook-3d-lite' ); ?></h1>
			<div class="tncfb3d-upgrade-card">
				<h2><?php esc_html_e( 'Everything here keeps working for free', 'tnc-flipbook-3d-lite' ); ?></h2>
				<p><?php esc_html_e( 'You are using the free version. When you need more, Pro adds:', 'tnc-flipbook-3d-lite' ); ?></p>
				<ul class="tncfb3d-upgrade-features">
					<?php foreach ( $tncfb3d_features as $tncfb3d_feature ) : ?>
						<li><?php echo esc_html( $tncfb3d_feature ); ?></li>
					<?php endforeach; ?>
				</ul>
				<a class="button button-primary button-hero" href="<?php echo esc_url( $tncfb3d_pro_url ); ?>" target="_blank" rel="noopener noreferrer">
					<?php esc_html_e( 'See Pro plans', 'tnc-flipbook-3d-lite' ); ?>
				</a>
			</div>
		</div>
		<?php
	}
}
