<?php

/**
 * The plugin bootstrap file
 *
 * This file is read by WordPress to generate the plugin information in the plugin
 * admin area. This file also includes all of the dependencies used by the plugin,
 * registers the activation and deactivation functions, and defines a function
 * that starts the plugin.
 *
 * @link              https://mediahubster.in
 * @since             1.0.0
 * @package           Subs_Sys
 *
 * @wordpress-plugin
 * Plugin Name:       Subscription System
 * Plugin URI:        https://mediahubster.in/subscription-system
 * Description:       A comprehensive subscription management system for WordPress.
 * Version:           1.0.18
 * Author:            Joe Youngblood
 * Author URI:        https://mediahubster.in
 * License:           GPL-2.0+
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
 * Text Domain:       subscription-system
 * Domain Path:       /languages
 * Requires at least: 5.8
 * Requires PHP:      8.0
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

// Check minimum PHP version requirement
if ( version_compare( PHP_VERSION, '8.0', '<' ) ) {
	add_action( 'admin_notices', function() {
		echo '<div class="error"><p>';
		printf(
			/* translators: 1: Current PHP version, 2: Required PHP version */
			esc_html__( 'Subscription System requires PHP version %2$s or higher. You are currently running PHP version %1$s. Please upgrade PHP to activate this plugin.', 'subscription-system' ),
			esc_html( PHP_VERSION ),
			'8.0'
		);
		echo '</p></div>';
	});
	return;
}

// Check WordPress version compatibility
global $wp_version;
if ( version_compare( $wp_version, '5.8', '<' ) ) {
	add_action( 'admin_notices', function() {
		echo '<div class="error"><p>';
		printf(
			/* translators: 1: Current WordPress version, 2: Required WordPress version */
			esc_html__( 'Subscription System requires WordPress version %2$s or higher. You are currently running WordPress version %1$s. Please upgrade WordPress to use this plugin.', 'subscription-system' ),
			esc_html( $GLOBALS['wp_version'] ),
			'5.8'
		);
		echo '</p></div>';
	});
	return;
}

/**
 * WordPress 7.0 Compatibility Check
 * Ensures the plugin works seamlessly with WordPress 7.0 and its new features
 */
function subs_sys_check_wp7_compatibility() {
	global $wp_version;
	
	// If running WordPress 7.0 or higher, ensure compatibility with new features
	if ( version_compare( $wp_version, '7.0', '>=' ) ) {
		// WordPress 7.0 introduces built-in AI Client - ensure no conflicts
		if ( function_exists( 'wp_ai_client' ) ) {
			// Future-proofing: Add filter to allow integration with WP AI features
			add_filter( 'subs_sys_ai_integration_enabled', '__return_true' );
		}
		
		// Ensure compatibility with WordPress 7.0 REST API changes
		add_filter( 'rest_authentication_errors', 'subs_sys_wp7_rest_auth_compatibility', 10, 1 );
	}
}
add_action( 'plugins_loaded', 'subs_sys_check_wp7_compatibility' );

/**
 * REST API Authentication compatibility for WordPress 7.0+
 */
function subs_sys_wp7_rest_auth_compatibility( $result ) {
	// Ensure our REST API endpoints remain compatible with WP 7.0 changes
	if ( ! empty( $result ) ) {
		return $result;
	}
	return $result;
}

// Define plugin constants
define('SUBS_SYS_VERSION', '1.0.18');
define('SUBS_SYS_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('SUBS_SYS_PLUGIN_URL', plugin_dir_url(__FILE__));
define('SUBS_SYS_PLUGIN_BASENAME', plugin_basename(__FILE__));

/**
 * Shared helper: enqueue interest-subscribe modal assets + localize script vars.
 * Called by both the shortcode handler and the floating-button/auto-open renderer
 * so the JS object is always fully populated regardless of which trigger is used.
 *
 * @param string $plugin_name Plugin slug.
 * @param string $version     Plugin version string.
 */
function subs_sys_enqueue_interest_modal_assets( $plugin_name, $version ) {
    static $done = false;
    if ( $done ) {
        return;
    }
    $done = true;

    wp_enqueue_style(
        $plugin_name . '-interest-subscribe',
        SUBS_SYS_PLUGIN_URL . 'public/css/interest-subscribe.css',
        array(),
        $version
    );

    wp_enqueue_script(
        $plugin_name . '-interest-subscribe',
        SUBS_SYS_PLUGIN_URL . 'public/js/interest-subscribe.js',
        array( 'jquery' ),
        $version,
        true
    );

    $current_user = wp_get_current_user();
    $is_logged_in = $current_user->exists();

    wp_localize_script(
        $plugin_name . '-interest-subscribe',
        'ssInterestVars',
        array(
            'ajax_url'              => admin_url( 'admin-ajax.php' ),
            'nonce'                 => wp_create_nonce( 'interest_subscription_nonce' ),
            'auto_open'             => (int) get_option( 'subs_modal_auto_open', 0 ),
            'auto_open_delay'       => absint( get_option( 'subs_modal_auto_open_delay', 3 ) ),
            'hide_fields_logged_in' => (int) get_option( 'subs_modal_hide_fields_logged_in', 1 ),
            'is_logged_in'          => $is_logged_in ? 1 : 0,
            'i18n'                  => array(
                'processing'  => __( 'Processing...', 'subscription-system' ),
                'submit'      => __( 'Subscribe', 'subscription-system' ),
                'error'       => __( 'Something went wrong. Please try again.', 'subscription-system' ),
                'select_plan' => __( 'Please select a subscription plan.', 'subscription-system' ),
            ),
        )
    );
}

// Load Composer autoloader if it exists
$autoloader = __DIR__ . '/vendor/autoload.php';
if (file_exists($autoloader)) {
    require_once $autoloader;
}

/**
 * The core plugin class that is used to define internationalization,
 * admin-specific hooks, and public-facing site hooks.
 */
require plugin_dir_path( __FILE__ ) . 'includes/class-subs-sys.php';

/**
 * Begins execution of the plugin.
 *
 * Since everything within the plugin is registered via hooks,
 * then kicking off the plugin from this point in the file does
 * not affect the page life cycle.
 *
 * @since    1.0.0
 */
function subs_sys_mh_run_plugin() {
	$plugin = new Subs_Sys();
	$plugin->run();
}

/**
 * Create required database tables on plugin activation
 */
function subs_sys_mh_activate_plugin() {
    global $wpdb;
    $charset_collate = $wpdb->get_charset_collate();
    
    // Create subscriptions table
    $subscriptions_table = $wpdb->prefix . 'subscriptions';
    $sql_subscriptions = "CREATE TABLE IF NOT EXISTS $subscriptions_table (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        user_id bigint(20) NOT NULL,
        plan_id mediumint(9) NOT NULL,
        customer_email varchar(100) NOT NULL,
        customer_name varchar(100) NOT NULL,
        payment_id varchar(100) NOT NULL,
        amount decimal(10,2) NOT NULL,
        status varchar(20) NOT NULL,
        start_date datetime NOT NULL,
        end_date datetime NOT NULL,
        stripe_customer_id varchar(100) DEFAULT NULL,
        stripe_subscription_id varchar(100) DEFAULT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id),
        KEY user_id (user_id),
        KEY payment_id (payment_id)
    ) $charset_collate;";
    
    // Create subscription orders table
    $orders_table = $wpdb->prefix . 'subscription_orders';
    $sql_orders = "CREATE TABLE IF NOT EXISTS $orders_table (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        user_id bigint(20) NOT NULL,
        subscription_id mediumint(9) NOT NULL,
        order_number varchar(50) NOT NULL,
        payment_id varchar(100) NOT NULL,
        amount decimal(10,2) NOT NULL,
        status varchar(20) NOT NULL,
        payment_method varchar(50) NOT NULL,
        billing_name varchar(100) NOT NULL,
        billing_email varchar(100) NOT NULL,
        transaction_date datetime NOT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id),
        KEY user_id (user_id),
        KEY subscription_id (subscription_id)
    ) $charset_collate;";
    
    // Create subscription plans table with status column
    $plans_table = $wpdb->prefix . 'subscription_plans';
    $sql_plans = "CREATE TABLE IF NOT EXISTS $plans_table (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        category_id mediumint(9) DEFAULT NULL,
        plan_name varchar(100) NOT NULL,
        description text NOT NULL,
        price decimal(10,2) NOT NULL,
        duration int(11) NOT NULL,
        duration_unit varchar(20) NOT NULL DEFAULT 'days',
        status varchar(20) NOT NULL DEFAULT 'active',
        stripe_product_id varchar(100) DEFAULT NULL,
        stripe_price_id varchar(100) DEFAULT NULL,
        features text,
        created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate;";

    // Create subscription plan categories table
    $categories_table = $wpdb->prefix . 'subscription_plan_categories';
    $sql_categories = "CREATE TABLE IF NOT EXISTS $categories_table (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        name varchar(100) NOT NULL,
        category_name varchar(100) NOT NULL,
        description text,
        category_description text,
        created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate;";

    // Create channels table
    $channels_table = $wpdb->prefix . 'subscription_channels';
    $sql_channels = "CREATE TABLE IF NOT EXISTS $channels_table (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        name varchar(255) NOT NULL,
        description text NOT NULL,
        status varchar(50) NOT NULL DEFAULT 'active',
        created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate;";

    // Create work items table
    $work_items_table = $wpdb->prefix . 'subscription_work_items';
    $sql_work_items = "CREATE TABLE IF NOT EXISTS $work_items_table (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        name varchar(255) NOT NULL,
        description text NOT NULL,
        status varchar(50) NOT NULL DEFAULT 'active',
        channel_id mediumint(9) DEFAULT 0,
        created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id),
        KEY channel_id (channel_id)
    ) $charset_collate;";

    // Create work logs table
    $work_logs_table = $wpdb->prefix . 'subscription_work_logs';
    $sql_work_logs = "CREATE TABLE IF NOT EXISTS $work_logs_table (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        user_id bigint(20) NOT NULL,
        channel_id mediumint(9) DEFAULT 0,
        work_item_id mediumint(9) DEFAULT 0,
        importance varchar(255) NOT NULL,
        notes longtext NOT NULL,
        performed_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id),
        KEY user_id (user_id),
        KEY channel_id (channel_id),
        KEY work_item_id (work_item_id)
    ) $charset_collate;";
    
    // Create content subscription plans table
    $content_plans_table = $wpdb->prefix . 'subscription_content_plans';
    $sql_content_plans = "CREATE TABLE IF NOT EXISTS $content_plans_table (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        plan_name varchar(255) NOT NULL,
        description text,
        price decimal(10,2) NOT NULL DEFAULT 0.00,
        duration int(11) NOT NULL DEFAULT 30,
        duration_unit varchar(20) NOT NULL DEFAULT 'days',
        content_type varchar(50) NOT NULL DEFAULT 'category',
        content_ids text NOT NULL,
        notification_frequency varchar(50) NOT NULL DEFAULT 'immediate',
        status varchar(20) NOT NULL DEFAULT 'active',
        stripe_product_id varchar(100) DEFAULT NULL,
        stripe_price_id varchar(100) DEFAULT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id),
        KEY content_type (content_type),
        KEY status (status)
    ) $charset_collate;";
    
    // Create content subscriptions table
    $content_subscriptions_table = $wpdb->prefix . 'subscription_content_subscriptions';
    $sql_content_subscriptions = "CREATE TABLE IF NOT EXISTS $content_subscriptions_table (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        user_id bigint(20) NOT NULL,
        content_plan_id mediumint(9) NOT NULL,
        subscription_id mediumint(9) DEFAULT NULL,
        status varchar(20) NOT NULL DEFAULT 'active',
        start_date datetime NOT NULL,
        end_date datetime NOT NULL,
        last_notification datetime DEFAULT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id),
        KEY user_id (user_id),
        KEY content_plan_id (content_plan_id),
        KEY subscription_id (subscription_id),
        KEY status (status),
        UNIQUE KEY user_content_plan (user_id, content_plan_id)
    ) $charset_collate;";
    
    // Create content notifications table
    $content_notifications_table = $wpdb->prefix . 'subscription_content_notifications';
    $sql_content_notifications = "CREATE TABLE IF NOT EXISTS $content_notifications_table (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        user_id bigint(20) NOT NULL,
        content_plan_id mediumint(9) NOT NULL,
        post_id bigint(20) NOT NULL,
        notification_type varchar(50) NOT NULL DEFAULT 'new_content',
        sent_at datetime DEFAULT NULL,
        read_at datetime DEFAULT NULL,
        status varchar(20) NOT NULL DEFAULT 'pending',
        created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id),
        KEY user_id (user_id),
        KEY content_plan_id (content_plan_id),
        KEY post_id (post_id),
        KEY status (status)
    ) $charset_collate;";

    // Create interest subscriptions table
    $interest_table = $wpdb->prefix . 'subscription_interest_subscriptions';
    $sql_interest = "CREATE TABLE IF NOT EXISTS $interest_table (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        user_id bigint(20) DEFAULT NULL,
        plan_id mediumint(9) DEFAULT NULL,
        subscriber_name varchar(100) NOT NULL,
        subscriber_email varchar(100) NOT NULL,
        category_ids text NOT NULL,
        tag_ids text NOT NULL,
        plan_type varchar(20) NOT NULL DEFAULT 'free',
        status varchar(20) NOT NULL DEFAULT 'active',
        payment_id varchar(100) DEFAULT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id),
        KEY user_id (user_id),
        KEY plan_id (plan_id),
        KEY subscriber_email (subscriber_email),
        KEY status (status),
        KEY plan_type (plan_type)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql_subscriptions);
    dbDelta($sql_orders);
    dbDelta($sql_plans);
    dbDelta($sql_categories);
    dbDelta($sql_channels);
    dbDelta($sql_work_items);
    dbDelta($sql_work_logs);
    dbDelta($sql_content_plans);
    dbDelta($sql_content_subscriptions);
    dbDelta($sql_content_notifications);
    dbDelta($sql_interest);
    
    // Add version to options
    add_option('subs_sys_db_version', '1.0');
    
    // Run the original activator
    require_once plugin_dir_path( __FILE__ ) . 'includes/class-subs-sys-activator.php';
    Subs_Sys_Activator::activate();
}

/**
 * The code that runs during plugin deactivation.
 */
function subs_sys_mh_deactivate_plugin() {
	require_once plugin_dir_path( __FILE__ ) . 'includes/class-subs-sys-deactivator.php';
	Subs_Sys_Deactivator::deactivate();
}

register_activation_hook( __FILE__, 'subs_sys_mh_activate_plugin' );
register_deactivation_hook( __FILE__, 'subs_sys_mh_deactivate_plugin' );

// Start the plugin
subs_sys_mh_run_plugin();

/**
 * Delete plugin tables and options on plugin uninstall
 */
function subs_sys_mh_uninstall() {
    global $wpdb;
    
    // Drop tables
    $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}subscriptions"); 
    $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}subscription_orders");
    $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}subscription_plans");
    $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}subscription_plan_categories");
    $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}subscription_channels");
    $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}subscription_work_items");
    $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}subscription_work_logs");
    $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}subscription_content_plans");
    $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}subscription_content_subscriptions");
    $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}subscription_content_notifications");
    $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}subscription_interest_subscriptions");

    // Delete options
    delete_option('subs_sys_db_version');
    delete_option('subs_sys_settings');
}

// Register uninstall hook
register_uninstall_hook(__FILE__, 'subs_sys_mh_uninstall');

/**
 * Load the database updater class
 */
require_once plugin_dir_path(__FILE__) . 'includes/class-subs-sys-db-updater.php';

/**
 * Run database updates on activation
 */
function subs_sys_mh_run_db_updates() {
    if (class_exists('Subs_Sys_DB_Updater')) {
        Subs_Sys_DB_Updater::force_update();
    }
}

// Run updates on plugin activation only
register_activation_hook(__FILE__, 'subs_sys_mh_run_db_updates'); 

/**
 * Update the subscription_plans table to add missing columns
 */
function subs_sys_mh_update_plans_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'subscription_plans';
    
    // Check if updated_at column exists
    $column_exists = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} LIKE 'updated_at'");
    
    if (empty($column_exists)) {
        // Add the missing column
        $wpdb->query("ALTER TABLE {$table_name} ADD COLUMN updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL");
    }
}

// Run this function on plugin load (temporarily)
add_action('plugins_loaded', 'subs_sys_mh_update_plans_table');
