<?php
/**
 * Plugin Name: Magecomp AI Description Generator for WooCommerce
 * Description: Magecomp AI Description Generator for WooCommerce is a WordPress plugin that leverages advanced AI to automatically generate SEO-friendly product, category, tag and brand descriptions for WooCommerce stores. Boost your store’s engagement and efficiency with AI-powered content.
 * Version: 1.0.1
 * Author: Magecomp
 * Author URI: https://magecomp.com/
 * Requires Plugins: woocommerce
 * License: GPLv2 or later
 *
 * @package Magecomp AI Description Generator for WooCommerce
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: magecomp-ai-description-generator-for-woocommerce
 * Domain Path: /languages
 */

// Prevent direct access for security.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Define plugin constants.
define( 'MCADGW_DESC_GEN_CHTGPT', '1.0.0' );
define( 'MCADGW_DESC_GEN_CHTGPT_DIR', plugin_dir_path( __FILE__ ) );
define( 'MCADGW_DESC_GEN_CHTGPT_URL', plugin_dir_url( __FILE__ ) );
define( 'MCADGW_DESC_GEN_CHTGPT_FILE', __FILE__ );
define( 'MCADGW_DESC_GEN_CHTGPT_TEXT_DOMAIN', 'magecomp-ai-description-generator-for-woocommerce' );

require_once MCADGW_DESC_GEN_CHTGPT_DIR . 'admin/admin-functions.php';

/**
 * WooCommerce active?
 *
 * @return bool
 */
// ========================= WooCommerce Dependency Check ========================= //
add_action( 'plugins_loaded', 'descgpt_check_woocommerce_dependency' );

if ( ! function_exists( 'descgpt_check_woocommerce_dependency' ) ) {
	/**
	 * Check for WooCommerce dependency.
	 *
	 * This function verifies if WooCommerce is active. If not, it adds an admin notice
	 * and deactivates the Magecomp AI Description Generator for WooCommerce plugin.
	 *
	 * @package Magecomp AI Description Generator for WooCommerce
	 * @since 1.0.0
	 * @return void
	 */
	function descgpt_check_woocommerce_dependency() {
		if ( ! class_exists( 'WooCommerce' ) ) {

			add_action( 'admin_notices', 'descgpt_wc_missing_notice' );

			deactivate_plugins( plugin_basename( __FILE__ ) );
		}
	}
}

if ( ! function_exists( 'descgpt_wc_missing_notice' ) ) {
	/**
	 * Display WooCommerce missing notice in admin.
	 *
	 * This function outputs an admin notice informing the user that
	 * WooCommerce is required for the plugin to function, and that the plugin
	 * has been deactivated.
	 *
	 * @package Magecomp AI Description Generator for WooCommerce
	 * @since 1.0.0
	 * @return void Outputs the admin notice HTML directly.
	 */
	function descgpt_wc_missing_notice() {
		?>
		<div class="notice notice-error is-dismissible">
			<p>
				<?php esc_html_e( 'Magecomp AI Description Generator for WooCommerce plugin requires WooCommerce to be installed and active. The plugin has been deactivated.', 'magecomp-ai-description-generator-for-woocommerce' ); ?>
			</p>
		</div>
		<?php
	}
}

/**
 * Register the plugin admin menu and submenus.
 *
 * This function adds the top-level menu and all its
 * submenus in the WordPress admin dashboard. Each submenu links to the
 * corresponding plugin admin page:
 * 1. General Settings
 * 2. AI Description Generator
 * 3. Documentation
 *
 * @since 1.0.0
 * @return void Outputs the admin menu and submenus directly.
 */
function descgpt_admin_menu() {
	// Top-level menu page.
	$icon_svg = 'data:image/svg+xml;base64,PHN2ZyB2ZXJzaW9uPSIxLjIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDE5IDE5IiB3aWR0aD0iMTkiIGhlaWdodD0iMTkiPjxkZWZzPjxpbWFnZSAgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiBpZD0iaW1nMSIgaHJlZj0iZGF0YTppbWFnZS9wbmc7YmFzZTY0LGlWQk9SdzBLR2dvQUFBQU5TVWhFVWdBQUFCUUFBQUFVQ0FNQUFBQzZWKzAvQUFBQUFYTlNSMElCMmNrc2Z3QUFBVTFRVEZSRi8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vL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UVCaXJ6NXI3dlpoWEI0RjhuSEdKLzVUWUlYR0xNdkVnSFl4VGtJT1h4QmdkdHovbHdFQXhHcE01c0JQTnRNQUFBQUFTVVZPUks1Q1lJST0iLz48L2RlZnM+PHN0eWxlPjwvc3R5bGU+PHVzZSAgaHJlZj0iI2ltZzEiIHg9Ii0xIiB5PSItMSIvPjwvc3ZnPg==';
	add_menu_page(
		esc_html__( 'Description Generator', 'magecomp-ai-description-generator-for-woocommerce' ),
		esc_html__( 'Description Generator', 'magecomp-ai-description-generator-for-woocommerce' ),
		'manage_options',
		'descgpt-general-settings',
		'descgpt_render_general_settings',
		$icon_svg,
		56
	);

	// General Settings submenu.
	add_submenu_page(
		'descgpt-general-settings',
		esc_html__( 'General Settings', 'magecomp-ai-description-generator-for-woocommerce' ),
		esc_html__( 'General Settings', 'magecomp-ai-description-generator-for-woocommerce' ),
		'manage_options',
		'descgpt-general-settings',
		'descgpt_render_general_settings'
	);

	// AI Description Generator submenu.
	add_submenu_page(
		'descgpt-general-settings',
		esc_html__( 'AI Description Generator', 'magecomp-ai-description-generator-for-woocommerce' ),
		esc_html__( 'Description Generator', 'magecomp-ai-description-generator-for-woocommerce' ),
		'manage_options',
		'descgpt-description-generator',
		'descgpt_render_description_generator'
	);

	do_action( 'descgpt_pro_load' );

	// Documentation submenu.
	add_submenu_page(
		'descgpt-general-settings',
		esc_html__( 'Documentation', 'magecomp-ai-description-generator-for-woocommerce' ),
		esc_html__( 'Documentation', 'magecomp-ai-description-generator-for-woocommerce' ),
		'manage_options',
		'descgpt-documentation',
		'descgpt_render_documentation'
	);
}
add_action( 'admin_menu', 'descgpt_admin_menu' );

/**
 * Admin page loaders for Magecomp AI Description Generator for WooCommerce.
 *
 * These functions load the corresponding PHP files for each admin page
 * and call the UI-rendering functions. They ensure that the UI is
 * encapsulated and loaded only when needed.
 *
 * @package Magecomp AI Description Generator for WooCommerce
 * @since 1.0.0
 */

/**
 * Render the General Settings admin page.
 *
 * Loads the general settings UI file and calls the UI rendering function.
 *
 * @since 1.0.0
 * @return void
 */
function descgpt_render_general_settings() {
	$file = MCADGW_DESC_GEN_CHTGPT_DIR . 'admin/descgpt-general-settings.php';

	if ( ! file_exists( $file ) ) {
		wp_die( 'Settings file missing: ' . esc_html( $file ) );
	}

	require_once $file;
	descgpt_render_general_settings_ui();
}

/**
 * Render the Description Generator admin page.
 *
 * Loads the description generator UI file and calls the UI rendering function.
 *
 * @since 1.0.0
 * @return void
 */
function descgpt_render_description_generator() {
	require_once MCADGW_DESC_GEN_CHTGPT_DIR . 'admin/descgpt-description-generator.php';
	descgpt_render_description_generation_settings();
}

/**
 * Render the Documentation admin page.
 *
 * Loads the documentation UI file and calls the UI rendering function.
 *
 * @since 1.0.0
 * @return void
 */
function descgpt_render_documentation() {
	require_once MCADGW_DESC_GEN_CHTGPT_DIR . 'admin/descgpt-documentation.php';
	descgpt_render_documentation_page();
}

/**
 * Render the API Usage & Logs admin page.
 *
 * Loads the API logs UI file and calls the UI rendering function.
 *
 * @since 1.0.0
 * @return void
 */

// Enqueue admin scripts and styles.
add_action(
	'admin_enqueue_scripts',
	function ( $hook ) {

		if ( strpos( $hook, 'descgpt-' ) === false ) {
			return;
		}

		$admin_assets_url = MCADGW_DESC_GEN_CHTGPT_URL . 'admin/descgpt-admin-assets/';
		$version          = MCADGW_DESC_GEN_CHTGPT;

		/*
		==========================================================
		LOCAL THIRD-PARTY ASSETS (Tailwind + Flowbite + Animate)
		==========================================================
		*/

		wp_enqueue_style(
			'descgpt-tailwind',
			$admin_assets_url . 'css/tailwind.min.css',
			array(),
			$version
		);

		wp_enqueue_style(
			'descgpt-flowbite',
			$admin_assets_url . 'css/flowbite.min.css',
			array( 'descgpt-tailwind' ),
			$version
		);

		wp_enqueue_style(
			'descgpt-animate',
			$admin_assets_url . 'css/animate.min.css',
			array(),
			$version
		);

		wp_enqueue_style(
			'descgpt-font-awesome',
			$admin_assets_url . 'css/all.min.css',
			array(),
			$version
		);

		wp_enqueue_script(
			'descgpt-flowbite-js',
			$admin_assets_url . 'js/flowbite.min.js',
			array(),
			$version,
			true
		);

		/*
		==========================================================
		CUSTOM PLUGIN STYLES & SCRIPTS
		==========================================================
		*/

		wp_enqueue_style(
			'descgpt-admin-css',
			MCADGW_DESC_GEN_CHTGPT_URL . 'assets/css/admin-styles.css',
			array( 'descgpt-flowbite' ),
			$version
		);

		$localized_scripts = array();

		// General Settings Page.
		if ( strpos( $hook, 'descgpt-general-settings' ) !== false ) {
			wp_enqueue_script(
				'descgpt-general-js',
				MCADGW_DESC_GEN_CHTGPT_URL . 'assets/js/descgpt-general.js',
				array( 'jquery' ),
				$version,
				true
			);
			$localized_scripts[] = 'descgpt-general-js';
		}

		// Description Generator Page.
		if ( strpos( $hook, 'descgpt-description-generator' ) !== false ) {
			wp_enqueue_script(
				'descgpt-description-generator-js',
				MCADGW_DESC_GEN_CHTGPT_URL . 'assets/js/descgpt-description-generator.js',
				array( 'jquery' ),
				$version,
				true
			);
		}

		/*
		==========================================================
		LOCALIZATION
		==========================================================
		*/
		if ( in_array( 'descgpt-general-js', $localized_scripts, true ) ) {
			wp_localize_script(
				'descgpt-general-js',
				'descgptwSettings',
				array(
					'ajaxurl'        => admin_url( 'admin-ajax.php' ),
					'verifyNonce'    => wp_create_nonce( 'descgpt_verify_key_nonce' ),
					'modelsNonce'    => wp_create_nonce( 'descgpt_nonce' ),
					'savedModel'     => esc_js( get_option( 'descgpt_model', '' ) ),
					'hasSavedApiKey' => ! empty( get_option( 'descgpt_api_key', '' ) ),
					'strings'        => array(
						'loading_models' => esc_html__( 'Loading models...', 'magecomp-ai-description-generator-for-woocommerce' ),
						'select_model'   => esc_html__( 'Select a model', 'magecomp-ai-description-generator-for-woocommerce' ),
						'no_models'      => esc_html__( 'No models available', 'magecomp-ai-description-generator-for-woocommerce' ),
						'error_models'   => esc_html__( 'Error fetching models', 'magecomp-ai-description-generator-for-woocommerce' ),
						'no_api_key'     => esc_html__( 'Please enter an API key.', 'magecomp-ai-description-generator-for-woocommerce' ),
						'loading'        => esc_html__( 'Loading...', 'magecomp-ai-description-generator-for-woocommerce' ),
						'check'          => esc_html__( 'Check', 'magecomp-ai-description-generator-for-woocommerce' ),
					),
				)
			);
		}

		wp_localize_script(
			'descgpt-description-generator-js',
			'descgptwSettings',
			array(
				'ajaxurl'  => admin_url( 'admin-ajax.php' ),
				'nonce'    => wp_create_nonce( 'descgpt_description_nonce' ),
				'language' => descgpt_get_settings()['language'] ?? 'en',
				'selected' => __( 'Selected', 'magecomp-ai-description-generator-for-woocommerce' ),
			)
		);
	}
);

add_action(
	'wp_enqueue_scripts',
	function () {
		$frontend_assets_url = MCADGW_DESC_GEN_CHTGPT_URL . 'admin/descgpt-admin-assets/';
		$version             = MCADGW_DESC_GEN_CHTGPT;

		wp_enqueue_style(
			'descgpt-tailwind-frontend',
			$frontend_assets_url . 'css/tailwind.min.css',
			array(),
			$version
		);

		wp_enqueue_style(
			'descgpt-flowbite-frontend',
			$frontend_assets_url . 'css/flowbite.min.css',
			array( 'descgpt-tailwind-frontend' ),
			$version
		);

		wp_enqueue_script(
			'descgpt-flowbite-js-frontend',
			$frontend_assets_url . 'js/flowbite.min.js',
			array(),
			$version,
			true
		);
	}
);

/**
 * Creates the API logs table on plugin activation.
 */
function descgpt_create_api_logs_table() {
	global $wpdb;
	$table_name      = $wpdb->prefix . 'descgpt_api_logs';
	$charset_collate = $wpdb->get_charset_collate();

	$sql = "CREATE TABLE $table_name (
		id bigint(20) NOT NULL AUTO_INCREMENT,
		date datetime NOT NULL,
		endpoint varchar(255) NOT NULL,
		status int(11) NOT NULL,
		status_label varchar(50) DEFAULT NULL,
		response_time float NOT NULL,
		tokens_used int(11) NOT NULL,
		functionality varchar(100) NOT NULL,
		order_id int(11) DEFAULT NULL,
		product_name varchar(255) DEFAULT NULL,
		item_id bigint(20) DEFAULT NULL,
		item_type varchar(50) DEFAULT NULL,
		item_slug varchar(255) DEFAULT NULL,
		model varchar(255) DEFAULT NULL,
		prompt_excerpt text DEFAULT NULL,
		result longtext DEFAULT NULL,
		user_id bigint(20) DEFAULT NULL,
		PRIMARY KEY (id)
	) $charset_collate;";

	require_once ABSPATH . 'wp-admin/includes/upgrade.php';
	dbDelta( $sql );
}
register_activation_hook( MCADGW_DESC_GEN_CHTGPT_FILE, 'descgpt_create_api_logs_table' );

add_filter(
    'plugin_action_links_' . plugin_basename( __FILE__ ),
    'mcadgw_free_add_upgrade_link'
);

function mcadgw_free_add_upgrade_link( $links ) {
    $upgrade_url = esc_url( 'https://magecomp.com/ai-description-generator-with-woocommerce-pro.html' );

    $links[] = '<a href="' . $upgrade_url . '" target="_blank" style="font-weight:bold;color:#d97706;">' 
        . esc_html__( 'Upgrade to PRO', 'magecomp-ai-description-generator-for-woocommerce' ) 
        . '</a>';

    return $links;
}