<?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://webequipe.com/webequipe-spin-win-wheel
 * @since             1.0.0
 * @package           Webequipe_Spin_Win_Wheel
 *
 * @wordpress-plugin
 * Plugin Name:       WebEquipe Spin & Win Wheel
 * Plugin URI:        https://webequipe.com/webequipe-spin-win-wheel
 * Description:       Boost engagement with a fun spin-to-win prize wheel! Customize rewards, collect emails, and display as a popup or sidebar. Perfect for giveaways, discounts, and lead generation.
 * Version:           1.1.1
 * Requires at least: 5.4
 * Tested up to:      7.0
 * Requires PHP:      7.4
 * Author:            Webequipe
 * Author URI:        https://webequipe.com/
 * License:           GPLv2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       webequipe-spin-win-wheel
 * Domain Path:       /languages
 * Contributors:      webequipe
 * Tags:              spin wheel, lucky draw, giveaway, coupon, lead generation
 * Stable tag:        1.1.1
 */




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

// Define the assets URL constant for use throughout the plugin
if (!defined('WEBEQUIPE_SPIN_WIN_WHEEL_ASSETS')) {
	define('WEBEQUIPE_SPIN_WIN_WHEEL_ASSETS', plugin_dir_url(__FILE__) . 'assets');
}
if (!defined('WEBEQUIPE_SPIN_WIN_WHEEL_PATH')) {
	define('WEBEQUIPE_SPIN_WIN_WHEEL_PATH', plugin_dir_path(__FILE__));
}

/**
 * Currently plugin version.
 * Start at version 1.0.0 and use SemVer - https://semver.org
 * Rename this for your plugin and update it as you release new versions.
 */
define('WEBEQUIPE_SPIN_WIN_WHEEL_VERSION', '1.1.1');

/**
 * The code that runs during plugin activation.
 * This action is documented in includes/class-webequipe-spin-win-wheel-activator.php
 */
function webequipe_sww_activate()
{
	require_once plugin_dir_path(__FILE__) . 'includes/class-webequipe-spin-win-wheel-activator.php';
	Webequipe_Spin_Win_Wheel_Activator::activate();
}

/**
 * The code that runs during plugin deactivation.
 * This action is documented in includes/class-webequipe-spin-win-wheel-deactivator.php
 */
function webequipe_sww_deactivate()
{
	require_once plugin_dir_path(__FILE__) . 'includes/class-webequipe-spin-win-wheel-deactivator.php';
	Webequipe_Spin_Win_Wheel_Deactivator::deactivate();
}

/**
 * The code that runs during plugin uninstall.
 * This action is documented in uninstall.php
 * 
 * @link https://developer.wordpress.org/reference/functions/register_uninstall_hook/
 */
function webequipe_sww_uninstall()
{
	if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
		return;
	}

	if ( ! current_user_can( 'activate_plugins' ) ) {
		return;
	}

	global $wpdb;

	// Remove plugin options.
	delete_option( 'wsww_plugin_version' );
	delete_option( 'wsww_settings' );
	delete_option( 'wsww_db_version' );

	if ( is_multisite() ) {
		delete_site_option( 'wsww_plugin_version' );
		delete_site_option( 'wsww_settings' );
	}

	/**
	 * Drop plugin tables securely.
	 *
	 * Direct schema queries are necessary here.
	 * Table names are fully sanitized and not user-controlled.
	 */
	$webequipe_sww_allowed_tables = array(
		$wpdb->prefix . 'spin_emails',
		$wpdb->prefix . 'spin_posts',
	);

	foreach ( $webequipe_sww_allowed_tables as $webequipe_sww_table_name ) {
		$webequipe_sww_table_name = webequipe_sww_sanitize_table_name( $webequipe_sww_table_name );
		if ( '' === $webequipe_sww_table_name ) {
			continue;
		}

		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Uninstall cleanup; table name sanitized above.
		$wpdb->query( 'DROP TABLE IF EXISTS `' . $webequipe_sww_table_name . '`' );
	}
}

/**
 * Sanitize SQL table identifier to alphanumerics and underscore.
 *
 * @param string $table_name Raw table name.
 * @return string
 */
function webequipe_sww_sanitize_table_name( $table_name ) {
	return (string) preg_replace( '/[^a-zA-Z0-9_]/', '', (string) $table_name );
}

/**
 * Check whether a column exists in a custom plugin table.
 *
 * @param string $table_name  Sanitized table name.
 * @param string $column_name Column name to check.
 * @return bool
 */
function webequipe_sww_table_has_column( $table_name, $column_name ) {
	global $wpdb;

	$table_name  = webequipe_sww_sanitize_table_name( $table_name );
	$column_name = webequipe_sww_sanitize_table_name( $column_name );

	if ( '' === $table_name || '' === $column_name ) {
		return false;
	}

	// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Metadata query for schema migration.
	$column_count = (int) $wpdb->get_var(
		$wpdb->prepare(
			'SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s AND COLUMN_NAME = %s',
			$table_name,
			$column_name
		)
	);

	return $column_count > 0;
}

register_activation_hook(__FILE__, 'webequipe_sww_activate');
register_deactivation_hook(__FILE__, 'webequipe_sww_deactivate');
register_uninstall_hook(__FILE__, 'webequipe_sww_uninstall');

/**
 * 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-webequipe-spin-win-wheel.php';

/**
 * Mailchimp integration helper.
 */
require_once plugin_dir_path(__FILE__) . 'includes/class-webequipe-spin-win-wheel-mailchimp.php';

/**
 * Manually include and instantiate the AJAX handler
 */
require_once plugin_dir_path(__FILE__) . 'includes/class-webequipe-spin-win-wheel-ajax.php';
if (class_exists('Webequipe\SpinWinWheel\Ajax')) {
	new \Webequipe\SpinWinWheel\Ajax();
}

/**
 * Manually include and instantiate the Assets handler
 */
require_once plugin_dir_path(__FILE__) . 'includes/class-webequipe-spin-win-wheel-assets.php';
if (class_exists('Webequipe\SpinWinWheel\Assets')) {
	new \Webequipe\SpinWinWheel\Assets();
}

/**
 * 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
 */
/**
 * Ensure spin_emails table has all expected columns (migration for existing installs).
 */
function webequipe_sww_maybe_add_spin_item_unique_id_column() {
	$db_version = (int) get_option( 'wsww_db_version', 0 );
	global $wpdb;
	$table = webequipe_sww_sanitize_table_name( $wpdb->prefix . 'spin_emails' );

	if ( '' === $table ) {
		return;
	}

	// 1) Ensure spin_item_unique_id column exists.
	if ( $db_version < 1 ) {
		$exists = webequipe_sww_table_has_column( $table, 'spin_item_unique_id' );
		if ( ! $exists ) {
			// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Migration; table name sanitized above.
			$wpdb->query( 'ALTER TABLE `' . $table . '` ADD COLUMN `spin_item_unique_id` varchar(20) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL AFTER `spin_id`' );
		}
		$db_version = 1;
	}

	// 2) Ensure coupon_code column exists.
	if ( $db_version < 2 ) {
		$exists_coupon = webequipe_sww_table_has_column( $table, 'coupon_code' );
		if ( ! $exists_coupon ) {
			// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Migration; table name sanitized above.
			$wpdb->query( 'ALTER TABLE `' . $table . '` ADD COLUMN `coupon_code` varchar(100) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL AFTER `page_url`' );
		}
		$db_version = 2;
	}

	// 3) Ensure coupon_applied column exists.
	if ( $db_version < 3 ) {
		$exists_applied = webequipe_sww_table_has_column( $table, 'coupon_applied' );
		if ( ! $exists_applied ) {
			// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Migration; table name sanitized above.
			$wpdb->query( 'ALTER TABLE `' . $table . '` ADD COLUMN `coupon_applied` varchar(10) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL AFTER `coupon_code`' );
		}
		$db_version = 3;
	}

	// 4) Version bump (legacy: spin_schedule_mode migration removed).
	if ( $db_version < 4 ) {
		$db_version = 4;
	}

	update_option( 'wsww_db_version', $db_version );
}
add_action( 'plugins_loaded', 'webequipe_sww_maybe_add_spin_item_unique_id_column', 5 );

/**
 * Ensure Mailchimp settings keys exist with safe defaults.
 *
 * This update migration keeps existing values intact and only fills missing keys.
 * Consent remains unchecked by default (`consent_enabled` = 0).
 *
 * @return void
 */
function webequipe_sww_maybe_migrate_mailchimp_settings() {
	$defaults = array(
		'enabled'         => 0,
		'api_key'         => '',
		'list_id'         => '',
		'tag'             => 'SpinWheel',
		'consent_enabled' => 0,
		'consent_text'    => __( 'I agree to receive promotional emails.', 'webequipe-spin-win-wheel' ),
		'last_status'     => '',
	);

	$settings = get_option( 'wsww_mailchimp_settings', null );
	if ( ! is_array( $settings ) ) {
		update_option( 'wsww_mailchimp_settings', $defaults );
		return;
	}

	$updated = false;
	foreach ( $defaults as $key => $default_value ) {
		if ( ! array_key_exists( $key, $settings ) ) {
			$settings[ $key ] = $default_value;
			$updated          = true;
		}
	}

	if ( $updated ) {
		update_option( 'wsww_mailchimp_settings', $settings );
	}
}
add_action( 'plugins_loaded', 'webequipe_sww_maybe_migrate_mailchimp_settings', 6 );

function webequipe_sww_run()
{

	if (!is_admin()) {
		require_once plugin_dir_path(__FILE__) . 'includes/class-webequipe-spin-win-wheel-frontend.php';
		new \Webequipe\SpinWinWheel\Frontend();
	}

	$plugin = new Webequipe_Spin_Win_Wheel();
	$plugin->run();

}
webequipe_sww_run();

/**
 * Add suggested privacy policy text.
 */
function webequipe_sww_add_privacy_policy_content() {
	if ( ! function_exists( 'wp_add_privacy_policy_content' ) ) {
		return;
	}

	$content = '<p>' . esc_html__( 'This site uses the WebEquipe Spin & Win Wheel plugin to run a spin-to-win campaign.', 'webequipe-spin-win-wheel' ) . '</p>'
		. '<ul>'
		. '<li>' . esc_html__( 'Data collected: name, email address, phone number, spin result, and page URL.', 'webequipe-spin-win-wheel' ) . '</li>'
		. '<li>' . esc_html__( 'Purpose: to run the spin-to-win campaign, store entries, and send winner/admin notifications if enabled.', 'webequipe-spin-win-wheel' ) . '</li>'
		. '<li>' . esc_html__( 'Storage: data is stored in custom database tables on this site.', 'webequipe-spin-win-wheel' ) . '</li>'
		. '<li>' . esc_html__( 'Retention: data remains until entries are deleted or the plugin is uninstalled.', 'webequipe-spin-win-wheel' ) . '</li>'
		. '</ul>';

	wp_add_privacy_policy_content(
		esc_html__( 'WebEquipe Spin & Win Wheel', 'webequipe-spin-win-wheel' ),
		wp_kses_post( wpautop( $content ) )
	);
}
add_action( 'admin_init', 'webequipe_sww_add_privacy_policy_content' );
