<?php
/**
 * Plugin Name: Kwiro — AI Sales Agent & Chatbot for WooCommerce
 * Description: The AI sales agent for WooCommerce — not another support chatbot. Learns your catalog, recommends products, answers buying questions, and closes sales 24/7. One click connects your store to the Kwiro dashboard.
 * Version:     1.2.18
 * Requires at least: 5.8
 * Tested up to: 7.0
 * Requires PHP: 7.4
 * Requires Plugins: woocommerce
 * WC requires at least: 7.0
 * WC tested up to: 9.5
 * Author:      Kwiro
 * Author URI:  https://kwiro.ai
 * Text Domain: kwiro-ai-sales-agent
 * License:     GPL-2.0-or-later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 *
 * @package KwiroAISalesAgent
 */

defined( 'ABSPATH' ) || exit;

/**
 * Plugin constants. The internal prefix was migrated AISALES_* → KWIRO_*
 * in v1.2.0 alongside the wordpress.org submission slug rename. Existing
 * v1.1.x installs are migrated automatically by Kwiro_Activator on their
 * first v1.2 activation — see run_migrations() for the option renames.
 */
define( 'KWIRO_VERSION', '1.2.18' );
define( 'KWIRO_PLUGIN_FILE', __FILE__ );
define( 'KWIRO_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'KWIRO_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'KWIRO_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );

/**
 * Check if WooCommerce is active.
 *
 * @return bool
 */
function kwiro_is_woocommerce_active() {
	// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- `active_plugins` is a core WP filter we apply (never fire), not a custom hook of ours.
	$active = in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ), true );
	if ( ! $active && is_multisite() ) {
		$network_plugins = get_site_option( 'active_sitewide_plugins', array() );
		$active          = isset( $network_plugins['woocommerce/woocommerce.php'] );
	}
	return $active;
}

/**
 * Display admin notice if WooCommerce is not active.
 */
function kwiro_woocommerce_missing_notice() {
	?>
	<div class="notice notice-error">
		<p>
			<?php
			echo esc_html__(
				'Kwiro requires WooCommerce to be installed and active.',
				'kwiro-ai-sales-agent'
			);
			?>
		</p>
	</div>
	<?php
}

/**
 * Add a "Settings" link + "Connect to Kwiro" link on the Plugins list row.
 * The settings deep-link saves a click when users land on the plugins page
 * after activation; the Kwiro dashboard link gives them an escape hatch.
 *
 * @param array $links Existing action links from `plugin_action_links_*`.
 * @return array Updated action links with our two entries prepended.
 */
function kwiro_plugin_action_links( $links ) {
	$settings_url  = admin_url( 'admin.php?page=kwiro-settings' );
	$dashboard_url = defined( 'KWIRO_DASHBOARD_URL' ) ? KWIRO_DASHBOARD_URL : 'https://app.kwiro.ai';
	$row           = array(
		'settings'  => '<a href="' . esc_url( $settings_url ) . '">' . esc_html__( 'Settings', 'kwiro-ai-sales-agent' ) . '</a>',
		'dashboard' => '<a href="' . esc_url( $dashboard_url ) . '" target="_blank" rel="noopener"><strong style="color:#d97757;">' . esc_html__( 'Open Kwiro →', 'kwiro-ai-sales-agent' ) . '</strong></a>',
	);
	return array_merge( $row, $links );
}
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), 'kwiro_plugin_action_links' );

/**
 * Add a "Docs" link under the plugin description on the Plugins list.
 *
 * @param array  $links Existing row-meta links from `plugin_row_meta`.
 * @param string $file  The plugin file path WordPress is iterating on.
 * @return array Row-meta links — original list, plus our Docs + Support links if this is the kwiro row.
 */
function kwiro_plugin_row_meta( $links, $file ) {
	if ( plugin_basename( __FILE__ ) !== $file ) {
		return $links;
	}
	$links[] = '<a href="https://kwiro.ai/docs" target="_blank" rel="noopener">' . esc_html__( 'Docs', 'kwiro-ai-sales-agent' ) . '</a>';
	$links[] = '<a href="https://kwiro.ai/support" target="_blank" rel="noopener">' . esc_html__( 'Support', 'kwiro-ai-sales-agent' ) . '</a>';
	return $links;
}
add_filter( 'plugin_row_meta', 'kwiro_plugin_row_meta', 10, 2 );

/**
 * Activation hook.
 */
function kwiro_activate() {
	require_once KWIRO_PLUGIN_DIR . 'includes/class-activator.php';
	Kwiro_Activator::activate();
}

/**
 * Deactivation hook.
 */
function kwiro_deactivate() {
	require_once KWIRO_PLUGIN_DIR . 'includes/class-deactivator.php';
	Kwiro_Deactivator::deactivate();
}

register_activation_hook( __FILE__, 'kwiro_activate' );
register_deactivation_hook( __FILE__, 'kwiro_deactivate' );

/**
 * Declare WooCommerce feature compatibility.
 *
 * - `custom_order_tables` (HPOS): plugin only touches orders via the WC CRUD
 *   API (`wc_get_order`, `$order->get_meta`, `$order->update_meta_data`,
 *   `$order->save`, status hooks) — zero direct `wp_postmeta`/`shop_order`
 *   queries — so it's already HPOS-safe; this just tells WC so the
 *   "incompatible plugins" notice stops firing on stores that have HPOS on.
 * - `cart_checkout_blocks`: attribution writes use the Store API hook
 *   `woocommerce_store_api_checkout_order_processed` for the Block Checkout
 *   path (alongside `woocommerce_checkout_update_order_meta` for classic),
 *   so the block-checkout flow is fully supported.
 */
add_action(
	'before_woocommerce_init',
	function () {
		if ( class_exists( '\\Automattic\\WooCommerce\\Utilities\\FeaturesUtil' ) ) {
			\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
			\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', __FILE__, true );
		}
	}
);

/**
 * Register custom CRON schedule intervals.
 * WordPress core only defines hourly, twicedaily, daily.
 *
 * @param array $schedules Existing schedules.
 * @return array
 */
function kwiro_cron_schedules( $schedules ) {
	$schedules['weekly'] = array(
		'interval' => 604800,
		'display'  => esc_html__( 'Once Weekly', 'kwiro-ai-sales-agent' ),
	);
	return $schedules;
}
add_filter( 'cron_schedules', 'kwiro_cron_schedules' );

/**
 * Initialize the plugin.
 */
function kwiro_init() {
	if ( ! kwiro_is_woocommerce_active() ) {
		add_action( 'admin_notices', 'kwiro_woocommerce_missing_notice' );
		return;
	}

	require_once KWIRO_PLUGIN_DIR . 'includes/class-plugin.php';
	Kwiro_Plugin::instance();
}
add_action( 'plugins_loaded', 'kwiro_init' );
