<?php
/**
 * Plugin Name: AI Virtual Try-On for WooCommerce
 * Description: AI-powered virtual try-on for WooCommerce products using Replicate.com IDM-VTON model. Let customers visualize how clothing looks on different models before purchasing.
 * Version: 1.0.2
 * Author: ReplicateWP
 * Author URI: https://replicatewp.com
 * Text Domain: ai-virtual-try-on-for-woocommerce
 * Domain Path: /languages
 * Requires at least: 6.0
 * Requires PHP: 7.4
 * Requires Plugins: woocommerce
 * WC requires at least: 7.0
 * WC tested up to: 10.4
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Define plugin constants
define( 'RWPVTO_VERSION', '1.0.2' );
define( 'RWPVTO_PLUGIN_FILE', __FILE__ );
define( 'RWPVTO_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'RWPVTO_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'RWPVTO_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );

/**
 * Main plugin class
 */
class ReplicateWP_Virtual_TryOn {
    
    /**
     * Single instance of the class
     *
     * @var ReplicateWP_Virtual_TryOn
     */
    private static $instance = null;
    
    /**
     * Get single instance of the class
     *
     * @return ReplicateWP_Virtual_TryOn
     */
    public static function instance() {
        if ( is_null( self::$instance ) ) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        $this->includes();
        $this->init_hooks();
    }
    
    /**
     * Include required files
     */
    private function includes() {
        // Core classes
        require_once RWPVTO_PLUGIN_DIR . 'includes/class-rwpvto-database.php';
        require_once RWPVTO_PLUGIN_DIR . 'includes/class-rwpvto-replicate-api.php';
        require_once RWPVTO_PLUGIN_DIR . 'includes/class-rwpvto-ajax-handler.php';
        
        // Admin classes
        if ( is_admin() ) {
            require_once RWPVTO_PLUGIN_DIR . 'admin/class-rwpvto-settings.php';
            require_once RWPVTO_PLUGIN_DIR . 'admin/class-rwpvto-dashboard.php';
            require_once RWPVTO_PLUGIN_DIR . 'admin/class-rwpvto-product-meta.php';
        }
    }
    
    /**
     * Initialize hooks
     */
    private function init_hooks() {
        // Activation/Deactivation hooks
        register_activation_hook( RWPVTO_PLUGIN_FILE, array( $this, 'activate' ) );
        register_deactivation_hook( RWPVTO_PLUGIN_FILE, array( $this, 'deactivate' ) );
        
        // Initialize plugin after WordPress and WooCommerce load
        add_action( 'plugins_loaded', array( $this, 'init' ) );
        
        // Declare HPOS compatibility
        add_action( 'before_woocommerce_init', array( $this, 'declare_hpos_compatibility' ) );
        
        // Load text domain
        // WordPress.org automatically loads translations, no need to call load_textdomain
        
        // Enqueue admin assets
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
        
        // Enable WebP support
        add_filter( 'upload_mimes', array( $this, 'enable_webp_upload' ) );
        add_filter( 'file_is_displayable_image', array( $this, 'webp_is_displayable' ), 10, 2 );
    }
    
    /**
     * Initialize the plugin
     */
    public function init() {
        // Check if WooCommerce is active
        if ( ! $this->is_woocommerce_active() ) {
            add_action( 'admin_notices', array( $this, 'woocommerce_missing_notice' ) );
            return;
        }
        
        // Initialize database
        RWPVTO_Database::instance();
        
        // Initialize AJAX handler
        RWPVTO_Ajax_Handler::instance();
        
        // Initialize admin classes
        if ( is_admin() ) {
            RWPVTO_Settings::instance();
            RWPVTO_Dashboard::instance();
            RWPVTO_Product_Meta::instance();
        }
    }
    
    /**
     * Declare HPOS compatibility
     */
    public function declare_hpos_compatibility() {
        if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
            \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility(
                'custom_order_tables',
                RWPVTO_PLUGIN_FILE,
                true
            );
        }
    }
    
    /**
     * Check if WooCommerce is active
     *
     * @return bool
     */
    private function is_woocommerce_active() {
        return class_exists( 'WooCommerce' );
    }
    
    /**
     * WooCommerce missing notice
     */
    public function woocommerce_missing_notice() {
        ?>
        <div class="notice notice-error">
            <p>
                <?php
                echo wp_kses_post(
                    sprintf(
                        /* translators: %s: WooCommerce link */
                        __( '<strong>AI Virtual Try-On for WooCommerce</strong> requires WooCommerce to be installed and active. Please install %s first.', 'ai-virtual-try-on-for-woocommerce' ),
                        '<a href="https://wordpress.org/plugins/woocommerce/" target="_blank">WooCommerce</a>'
                    )
                );
                ?>
            </p>
        </div>
        <?php
    }
    
    /**
     * Enqueue admin assets
     */
    public function enqueue_admin_assets( $hook ) {
        // Check if we're on a product page or plugin page
        $is_product_page = in_array( $hook, array( 'post.php', 'post-new.php' ) ) && get_post_type() === 'product';
        $is_plugin_page = in_array( $hook, array( 'toplevel_page_rwpvto-dashboard', 'ai-virtual-try-on_page_rwpvto-settings' ) );
        
        if ( ! $is_product_page && ! $is_plugin_page ) {
            return;
        }
        
        // Enqueue WordPress media uploader on product pages
        if ( $is_product_page ) {
            wp_enqueue_media();
        }
        
        // Enqueue CSS
        wp_enqueue_style(
            'rwpvto-admin-css',
            RWPVTO_PLUGIN_URL . 'assets/css/admin.css',
            array(),
            RWPVTO_VERSION
        );
        
        // Enqueue JavaScript
        wp_enqueue_script(
            'rwpvto-admin-js',
            RWPVTO_PLUGIN_URL . 'assets/js/admin.js',
            array( 'jquery', 'media-upload', 'media-views' ),
            RWPVTO_VERSION,
            true
        );
        
        // Localize script
        wp_localize_script(
            'rwpvto-admin-js',
            'rwpvtoAdmin',
            array(
                'ajaxUrl' => admin_url( 'admin-ajax.php' ),
                'nonce' => wp_create_nonce( 'rwpvto_nonce' ),
                'strings' => array(
                    'generating' => __( 'Generating...', 'ai-virtual-try-on-for-woocommerce' ),
                    'success' => __( 'Image generated successfully!', 'ai-virtual-try-on-for-woocommerce' ),
                    'error' => __( 'Error generating image. Please try again.', 'ai-virtual-try-on-for-woocommerce' ),
                    'confirmDelete' => __( 'Are you sure you want to delete this image?', 'ai-virtual-try-on-for-woocommerce' ),
                )
            )
        );
    }
    
    /**
     * Plugin activation
     */
    public function activate() {
        // Create database tables
        RWPVTO_Database::create_tables();
        
        // Set default options
        $default_options = array(
            'api_key' => '',
            'model_version' => 'cuuupid/idm-vton:0513734a452173b8173e907e3a59d19a36266e55b48528559432bd21c7d7e985',
            'default_steps' => 30,
            'default_seed' => 42,
            'default_category' => 'upper_body',
        );
        
        add_option( 'rwpvto_settings', $default_options );
        
        // Flush rewrite rules
        flush_rewrite_rules();
    }
    
    /**
     * Plugin deactivation
     */
    public function deactivate() {
        // Flush rewrite rules
        flush_rewrite_rules();
    }
    
    /**
     * Enable WebP upload support
     *
     * @param array $mimes Allowed MIME types
     * @return array
     */
    public function enable_webp_upload( $mimes ) {
        // Add WebP support if not already present
        if ( ! isset( $mimes['webp'] ) ) {
            $mimes['webp'] = 'image/webp';
        }
        return $mimes;
    }
    
    /**
     * Mark WebP as displayable image
     *
     * @param bool $result Whether the image is displayable
     * @param string $path Path to the image
     * @return bool
     */
    public function webp_is_displayable( $result, $path ) {
        if ( $result === false ) {
            $info = @getimagesize( $path );
            if ( ! empty( $info['mime'] ) && $info['mime'] === 'image/webp' ) {
                $result = true;
            }
        }
        return $result;
    }
}

/**
 * Initialize the plugin
 */
function rwpvto() {
    return ReplicateWP_Virtual_TryOn::instance();
}

// Start the plugin
rwpvto();

