<?php
/**
 * Plugin Name: Goose Commerce
 * Plugin URI: https://wpgoose.com
 * Description: A complete e-commerce solution for WordPress with Elementor & Gutenberg support
 * Version: 1.0.072
 * Requires at least: 6.0
 * Requires PHP: 7.4
 * Author: Goose Commerce - Giles Beckley
 * Author URI: https://wpgoose.com
 * License: As notified on the website
 * License URI: https://wpgoose.com/licence-agreement/
 * Text Domain: goose-commerce
 * Domain Path: /languages
 *
 * @package GGM_Commerce
 */

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

// Plugin Update Checker
$ggmc_puc_file = __DIR__ . '/plugin-update-checker/plugin-update-checker.php';
if ( file_exists( $ggmc_puc_file ) ) {
    require_once $ggmc_puc_file;
    if ( class_exists( 'YahnisElsts\\PluginUpdateChecker\\v5\\PucFactory' ) ) {
        $ggmUpdateChecker = YahnisElsts\PluginUpdateChecker\v5\PucFactory::buildUpdateChecker(
            'https://wpgoose.com/updates/update-check.php',
            __FILE__,
            'goose-commerce'
        );
    }
}

// Database functionality moved to includes/class-database.php

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

// Load database class first (needed for activation hook)
$plugin_path = plugin_dir_path(__FILE__);
if (empty($plugin_path) || !is_string($plugin_path)) {
    return;
}
require_once $plugin_path . 'includes/class-database.php';
require_once $plugin_path . 'includes/class-page-builder.php';
require_once $plugin_path . 'includes/class-roles.php';

// Register hooks to detect Elementor activation/deactivation and convert pages
GGM_Commerce_Page_Builder::register_builder_switch_hooks();

// Register activation hook
register_activation_hook(__FILE__, 'ggm_commerce_activate');

// Register deactivation hook
register_deactivation_hook(__FILE__, 'ggm_commerce_deactivate');

/**
 * Plugin deactivation callback.
 *
 * Cleans up scheduled events. Data cleanup happens on uninstall,
 * not deactivation, to allow reactivation without data loss.
 */
function ggm_commerce_deactivate() {
	// Unschedule cron events (always do this on deactivation).
	wp_clear_scheduled_hook( 'ggmc_daily_cleanup' );
	wp_clear_scheduled_hook( 'ggmc_hourly_tasks' );

	// Unschedule Google Merchant cron if class exists.
	if ( class_exists( 'GGM_Commerce_Google_Merchant_Scheduler' ) ) {
		$scheduler = GGM_Commerce_Google_Merchant_Scheduler::instance();
		$scheduler->unschedule_all();
	}

	// Unschedule Subscription Renewal cron if class exists.
	if ( class_exists( 'GGM_Commerce_Subscription_Renewal' ) ) {
		GGM_Commerce_Subscription_Renewal::instance()->unschedule_all();
	}
}

function ggm_commerce_activate() {
    global $ggm_commerce_database;

    // Create database tables
    $ggm_commerce_database->create_tables();

    // Create default pages with Elementor layouts
    GGM_Commerce_Page_Builder::create_default_pages();

    // Register custom roles (always register on activation to ensure caps are up to date)
    GGM_Commerce_Roles::register_roles();

    // Set default widget controls (only if not already set)
    $widget_controls = get_option('ggm_commerce_widget_controls', array());
    if (!isset($widget_controls['widgets_prioritized'])) {
        $widget_controls['widgets_prioritized'] = '1'; // Enable by default
        update_option('ggm_commerce_widget_controls', $widget_controls);
    }

    // Schedule rewrite rules flush for after init
    // This ensures the product-details page exists before adding rules
    set_transient('ggm_commerce_flush_rewrite_rules', true, 60);
}

// Basic plugin initialization
add_action('init', 'ggm_commerce_init');
add_action('wp_enqueue_scripts', 'ggm_commerce_enqueue_frontend_assets');

function ggm_commerce_init() {
    // Ensure we have a valid plugin path
    $plugin_path = plugin_dir_path(__FILE__);
    if (empty($plugin_path) || !is_string($plugin_path)) {
        return;
    }

    // Load plugin textdomain for translations
    load_plugin_textdomain(
        'ggm-commerce',
        false,
        dirname(plugin_basename(__FILE__)) . '/languages'
    );

    // Auto-create missing database tables when DB version changes.
    // dbDelta is safe to re-run — it only adds missing tables/columns.
    $ggmc_db_version = '2.2'; // Bump this when adding new tables.
    if ( get_option( 'ggmc_db_version' ) !== $ggmc_db_version ) {
        global $ggm_commerce_database;
        $ggm_commerce_database->create_tables();
        update_option( 'ggmc_db_version', $ggmc_db_version );
    }

    // Load modular includes (database class already loaded above)
    require_once $plugin_path . 'includes/class-helpers.php';
    require_once $plugin_path . 'includes/class-taxonomy.php';
    require_once $plugin_path . 'includes/class-barcode.php';
    require_once $plugin_path . 'includes/class-kits.php';
    require_once $plugin_path . 'includes/class-address-manager.php';
    require_once $plugin_path . 'includes/class-reviews.php';
    require_once $plugin_path . 'includes/class-elementor.php';
    require_once $plugin_path . 'includes/class-preview-manager.php';
    require_once $plugin_path . 'includes/class-ajax.php';
    require_once $plugin_path . 'includes/class-admin.php';
    require_once $plugin_path . 'includes/class-license.php';
    require_once $plugin_path . 'includes/class-wishlist.php';
    require_once $plugin_path . 'includes/class-recently-viewed.php';
    require_once $plugin_path . 'includes/class-quick-view.php';
    require_once $plugin_path . 'includes/class-product-comparison.php';
    require_once $plugin_path . 'includes/class-attributes.php';
    require_once $plugin_path . 'includes/class-checkout-fields.php';
    require_once $plugin_path . 'includes/class-tax.php';
    require_once $plugin_path . 'includes/class-shipping.php';
    require_once $plugin_path . 'includes/class-variations.php';
    require_once $plugin_path . 'includes/class-variation-attributes.php';
    require_once $plugin_path . 'includes/class-downloads.php';
    require_once $plugin_path . 'includes/class-virtual-products.php';
    require_once $plugin_path . 'includes/class-order-notes.php';
    require_once $plugin_path . 'includes/class-shipments.php';
    require_once $plugin_path . 'includes/class-opengraph.php';
    require_once $plugin_path . 'includes/class-footer-branding.php';
    require_once $plugin_path . 'includes/emails/class-email-manager.php';
    require_once $plugin_path . 'includes/admin-premium-components-tab.php';
    require_once $plugin_path . 'includes/admin-checkout-fields-tab.php';
    require_once $plugin_path . 'includes/admin-google-merchant-tab.php';
    require_once $plugin_path . 'includes/admin-google-merchant-feed-edit.php';
    require_once $plugin_path . 'includes/settings.php';

    // Load Google Merchant Feed classes
    require_once $plugin_path . 'includes/google-merchant/class-google-merchant-settings.php';
    require_once $plugin_path . 'includes/google-merchant/class-google-merchant-feed-manager.php';
    require_once $plugin_path . 'includes/google-merchant/class-google-merchant-validator.php';
    require_once $plugin_path . 'includes/google-merchant/class-google-merchant-feed.php';
    require_once $plugin_path . 'includes/google-merchant/class-google-merchant-scheduler.php';
    require_once $plugin_path . 'includes/google-merchant/class-google-merchant-rest-api.php';

    // Load payment gateway infrastructure
    require_once $plugin_path . 'includes/gateways/abstract-payment-gateway.php';
    require_once $plugin_path . 'includes/gateways/class-payment-gateway-manager.php';
    require_once $plugin_path . 'includes/gateways/class-gateway-rest-api.php';
    
    // Initialize helper functionality
    GGM_Commerce_Helpers::init();

    // Initialize popup hooks for Elementor Pro (only if Pro is available)
    if ( class_exists( '\ElementorPro\Plugin' ) ) {
        GGM_Commerce_Page_Builder::init_popup_hooks();
    }

    // Check and upgrade page layouts if needed (runs once per version)
    GGM_Commerce_Page_Builder::check_and_upgrade_pages();

    // Load cart functionality only after WordPress is fully loaded
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is a simple existence check for initialization timing, not form processing
    if (!is_admin() || (is_admin() && !isset($_GET['action']))) {
        require_once $plugin_path . 'includes/cart.php';
    }
    
    require_once $plugin_path . 'includes/test-data-generator.php';
    require_once $plugin_path . 'includes/orders.php';
    require_once $plugin_path . 'includes/class-transaction-export.php';
    require_once $plugin_path . 'includes/class-discounts.php';
    require_once $plugin_path . 'includes/class-subscriptions.php';
    require_once $plugin_path . 'includes/class-subscription-renewal.php';
    require_once $plugin_path . 'includes/class-subscription-ajax.php';

    // Initialize classes
    new GGM_Commerce_Test_Data_Generator();

    // Initialize Transaction Export (singleton, registers AJAX handlers)
    GGM_Commerce_Transaction_Export::get_instance();

    // Initialize Checkout Fields (singleton, registers AJAX handlers)
    GGM_Commerce_Checkout_Fields::get_instance();

    // Create single admin instance to avoid duplicates
    global $ggm_commerce_admin;
    $ggm_commerce_admin = new GGM_Commerce_Admin();

    // Initialize email notification system
    ggm_commerce_emails();

    // Load widget loader for script registration
    require_once plugin_dir_path(__FILE__) . 'widgets/widget-loader.php';

    // Initialize Elementor integration
    GGM_Commerce_Elementor::init();

    // Initialize Preview Manager for Elementor editor
    GGM_Commerce_Preview_Manager::init();

    // Initialize Gutenberg block support
    require_once $plugin_path . 'blocks/class-block-adapter.php';
    require_once $plugin_path . 'blocks/shared/product-context.php';
    require_once $plugin_path . 'blocks/class-block-registrar.php';
    require_once $plugin_path . 'blocks/class-block-rest-api.php';
    GGMC_Block_Registrar::init();
    GGMC_Block_REST_API::init();

    // Initialize OpenGraph meta tags (if enabled in settings)
    GGM_Commerce_OpenGraph::init();

    // Initialize "Powered by Goose" footer branding
    GGM_Commerce_Footer_Branding::init();

    // Initialize Wishlist (only if feature is activated)
    if ( GGM_Commerce_License::instance()->is_widget_activated( 'wishlist' ) ) {
        GGM_Commerce_Wishlist::instance();
    }

    // Initialize Recently Viewed tracking (only if feature is activated)
    if ( GGM_Commerce_License::instance()->is_widget_activated( 'recently-viewed' ) ) {
        GGM_Commerce_Recently_Viewed::instance();
    }

    // Initialize Variations (only if feature is activated)
    if ( GGM_Commerce_License::instance()->is_widget_activated( 'product-variations' ) ) {
        GGM_Commerce_Variations::instance();
        GGM_Commerce_Variation_Attributes::get_instance();
    }

    // Initialize Downloads (only if feature is activated)
    if ( GGM_Commerce_License::instance()->is_widget_activated( 'downloads' ) ) {
        GGM_Commerce_Downloads::instance();
    }

    // Initialize Virtual Products helper (always needed for shipping calculations)
    GGM_Commerce_Virtual_Products::instance();

    // Initialize Google Merchant Feed REST API (always, so routes are registered)
    GGM_Commerce_Google_Merchant_REST_API::instance();

    // Initialize scheduler only if feature is activated
    if ( GGM_Commerce_License::instance()->is_widget_activated( 'google-merchant-feed' ) ) {
        GGM_Commerce_Google_Merchant_Scheduler::instance();
        // Schedule cron events if not already scheduled
        GGM_Commerce_Google_Merchant_Scheduler::instance()->schedule_all();
    }

    // Initialize Discounts & Vouchers (only if feature is activated)
    if ( GGM_Commerce_License::instance()->is_widget_activated( 'discount-vouchers' ) ) {
        GGM_Commerce_Discounts::get_instance();
    }

    // Initialize Subscription Renewal Engine (only if feature is activated)
    if ( GGM_Commerce_License::instance()->is_widget_activated( 'subscription-billing' ) ) {
        $renewal_engine = GGM_Commerce_Subscription_Renewal::instance();
        $renewal_engine->schedule_all();
    }

    // Initialize Subscription AJAX handlers (customer self-service).
    GGM_Commerce_Subscription_Ajax::instance();

    // Register shortcodes
    add_shortcode( 'ggmc_image_count', 'ggmc_shortcode_image_count' );
    add_shortcode( 'ggmc_products_in_stock', 'ggmc_shortcode_products_in_stock' );
}

/**
 * Shortcode: [ggmc_image_count]
 * Returns the total number of images (main + gallery) for the current product.
 * Use in any Elementor text/heading widget on a product details page.
 */
function ggmc_shortcode_image_count() {
    $product_id = GGM_Commerce_Helpers::get_current_product_id();
    if ( ! $product_id ) {
        return '0';
    }

    global $wpdb;
    $product = $wpdb->get_row( $wpdb->prepare(
        "SELECT image_id, gallery_ids FROM {$wpdb->prefix}ggmc_products WHERE id = %d",
        $product_id
    ) );

    if ( ! $product ) {
        return '0';
    }

    $count = 0;

    // Count main image
    if ( ! empty( $product->image_id ) ) {
        $count++;
    }

    // Count gallery images
    if ( ! empty( $product->gallery_ids ) ) {
        $gallery = json_decode( $product->gallery_ids, true );
        if ( is_array( $gallery ) ) {
            $count += count( $gallery );
        }
    }

    return (string) $count;
}

/**
 * Shortcode: [ggmc_products_in_stock]
 * Returns the number of active products currently in stock.
 * Optional attribute: status="active" (default) or status="all".
 */
function ggmc_shortcode_products_in_stock( $atts ) {
    global $wpdb;

    $atts = shortcode_atts( array(
        'status' => 'active',
    ), $atts, 'ggmc_products_in_stock' );

    $table = $wpdb->prefix . 'ggmc_products';

    if ( 'all' === $atts['status'] ) {
        $count = $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE stock > 0" );
    } else {
        $count = $wpdb->get_var( $wpdb->prepare(
            "SELECT COUNT(*) FROM {$table} WHERE stock > 0 AND status = %s",
            $atts['status']
        ) );
    }

    return (string) ( $count ?: '0' );
}

// Frontend assets enqueuing (functionality moved to GGM_Commerce_Elementor class)
function ggm_commerce_enqueue_frontend_assets() {
    return GGM_Commerce_Elementor::enqueue_frontend_assets();
}

// Initialize Model Context Protocol (MCP) Support
add_action('rest_api_init', 'ggm_commerce_init_mcp');

function ggm_commerce_init_mcp() {
    $plugin_path = plugin_dir_path(__FILE__);

    // Check if MCP REST API class exists
    $mcp_rest_api_file = $plugin_path . 'includes/class-mcp-rest-api.php';

    if (file_exists($mcp_rest_api_file)) {
        require_once $mcp_rest_api_file;

        // Initialize MCP REST API endpoint
        new GGM_Commerce_MCP_REST_API();
    }

}
