<?php

/**
 * Plugin Name: StoreVoiceAI for WooCommerce
 * Description: A custom plugin to enable WooCommerce AI customer support
 * Version: 0.0.10
 * Author: StoreVoiceAI
 * Author URI: https://storevoiceai.com
 * Text Domain: storevoiceai-for-woocommerce
 * Requires Plugins: woocommerce
 * WC requires at least: 5.0.0
 * Requires at least: 5.0
 * Tested up to: 7.0
 * Requires PHP: 8.0
 * License: GPL2
 */
namespace Kanzu\StoreVoiceAI;

// Prevent direct file access before plugin bootstrapping runs.
if ( !defined( 'ABSPATH' ) ) {
    exit;
}

if ( !function_exists( __NAMESPACE__ . '\\storevoiceai_fs' ) ) {
    // Create a helper function for easy SDK access.
    function storevoiceai_fs() {
        global $storevoiceai_fs;
        if ( !isset( $storevoiceai_fs ) ) {
            // Include Freemius SDK.
            require_once dirname( __FILE__ ) . '/includes/lib/freemius/start.php';
            $storevoiceai_fs = \fs_dynamic_init( array(
                'id'               => '17056',
                'slug'             => 'storevoiceai-for-woocommerce',
                'type'             => 'plugin',
                'public_key'       => 'pk_6dce2057f020705991a0d3be5b5f6',
                'is_premium'       => false,
                'is_premium_only'  => false,
                'is_org_compliant' => true,
                'has_addons'       => false,
                'has_paid_plans'   => false,
                'menu'             => array(
                    'slug'    => 'storevoiceai-for-woocommerce',
                    'support' => false,
                ),
                'is_live'          => true,
            ) );
        }
        return $storevoiceai_fs;
    }

    // Init Freemius.
    storevoiceai_fs();
    // Signal that SDK was initiated.
    do_action( 'storevoiceai_fs_loaded' );

    // Suppress the Freemius "Allow & Continue / Skip" opt-in modal — the plugin
    // ships its own onboarding wizard which handles consent and configuration.
    // Freemius stays loaded for license activation, just without the connect prompt.
    add_action( 'admin_init', function () {
        if ( ! function_exists( __NAMESPACE__ . '\\storevoiceai_fs' ) ) {
            return;
        }
        $fs = storevoiceai_fs();
        if ( ! $fs ) {
            return;
        }
        if ( method_exists( $fs, 'is_registered' ) && $fs->is_registered() ) {
            return;
        }
        if ( method_exists( $fs, 'is_anonymous' ) && $fs->is_anonymous() ) {
            return;
        }
        if ( method_exists( $fs, 'skip_connection' ) ) {
            $fs->skip_connection();
        }
    }, 5 );
}
final class Kanzu_StoreVoiceAI {
    /**
     * Variable that holds the one and only instance of Kanzu_StoreVoiceAI
     *
     * @var Kanzu_StoreVoiceAI
     */
    private static $_instance = null;

    /**
     * A MonoLog log object
     *
     * @var Object
     */
    public $logger = null;

    /**
     * A Dependency Injection Container
     */
    public $container;

    /**
     * Load the global instance of Kanzu_StoreVoiceAI
     *
     * @return Kanzu_StoreVoiceAI
     */
    public static function get_instance() {
        if ( is_null( self::$_instance ) ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function __construct() {
        $this->define_constants();
        $this->includes();
        $this->init_di_container();
        $this->register_hooks();
    }

    public function define_constants() {
        $this->define( 'KANZU_STOREVOICEAI_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
        $this->define( 'KANZU_STOREVOICEAI_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
        $this->define( 'KANZU_STOREVOICEAI_PLUGIN_FILE', __FILE__ );
    }

    /**
     * Define constant if not already set.
     *
     * @param string      $name variable.
     * @param string|bool $value variable.
     */
    private function define( $name, $value ) {
        if ( !defined( $name ) ) {
            define( $name, $value );
        }
    }

    private function includes() {
        require_once KANZU_STOREVOICEAI_PLUGIN_DIR . '/vendor/autoload.php';
        require_once KANZU_STOREVOICEAI_PLUGIN_DIR . '/includes/class-service-container.php';
        require_once KANZU_STOREVOICEAI_PLUGIN_DIR . '/includes/class-logger.php';
        require_once KANZU_STOREVOICEAI_PLUGIN_DIR . '/includes/trait-working-hours.php';
        require_once KANZU_STOREVOICEAI_PLUGIN_DIR . '/includes/class-onboarding.php';
        require_once KANZU_STOREVOICEAI_PLUGIN_DIR . '/includes/class-hook-registry.php';
    }

    private function register_hooks() {
        return new \Kanzu\StoreVoiceAI\Hook_Registry();
    }

    private function init_logger() {
        $this->container->set( 'logger', function () {
            try {
                $log_dir = defined( 'WP_CONTENT_DIR' )
                    ? trailingslashit( WP_CONTENT_DIR ) . 'storevoiceai-for-woocommerce-logs/'
                    : '';
                if ( $log_dir && !is_dir( $log_dir ) && function_exists( 'wp_mkdir_p' ) ) {
                    wp_mkdir_p( $log_dir );
                }

                if ( ! $log_dir || ! is_dir( $log_dir ) ) {
                    return $this->create_null_logger();
                }
                if ( ! $this->protect_log_directory( $log_dir ) ) {
                    return $this->create_null_logger();
                }

                return new Logger( $log_dir, 'Kanzu_StoreVoiceAI', 7 );
            } catch ( \Throwable $e ) {
                return $this->create_null_logger();
            }
        } );
    }

    private function protect_log_directory( string $log_dir ): bool {
        $log_dir = trailingslashit( $log_dir );
        if ( ! is_writable( $log_dir ) ) {
            return false;
        }
        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod -- Logger directory permissions must be restricted immediately after creation.
        if ( ! chmod( $log_dir, 0750 ) ) {
            return false;
        }

        $files = array(
            'index.html' => '',
            'index.php'  => "<?php\n// Silence is golden.\n",
            '.htaccess'  => "Require all denied\nDeny from all\n",
            'web.config' => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<configuration><system.webServer><security><requestFiltering><denyUrlSequences><add sequence=\"storevoiceai-\" /></denyUrlSequences></requestFiltering></security></system.webServer></configuration>\n",
        );

        foreach ( $files as $filename => $contents ) {
            $path = $log_dir . $filename;
            if ( ! file_exists( $path ) ) {
                // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- Logger bootstrap must create simple deny files before direct file logging can run.
                if ( false === file_put_contents( $path, $contents ) ) {
                    return false;
                }
            }
            // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod -- Access-control files should not be group/world writable.
            if ( ! chmod( $path, 0640 ) ) {
                return false;
            }
        }

        return true;
    }

	    private function create_null_logger() {
	        return new class {
            public function info( $message, array $context = [] ) {}
            public function error( $message, array $context = [] ) {}
            public function warning( $message, array $context = [] ) {}
        };
    }

    private function init_di_container() {
        $this->container = new Service_Container();
        $this->init_logger();
    }

    public static function storevoiceai_on_activate() {
        // Load plugin.php functions
        if ( !function_exists( 'is_plugin_active' ) ) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        // Check WooCommerce installed & active
        if ( !is_plugin_active( 'woocommerce/woocommerce.php' ) ) {
            deactivate_plugins( plugin_basename( KANZU_STOREVOICEAI_PLUGIN_FILE ) );
            wp_die(
                esc_html__( 'StoreVoiceAI requires WooCommerce to be installed and active.', 'storevoiceai-for-woocommerce' ),
                esc_html__( 'Plugin dependency check', 'storevoiceai-for-woocommerce' ),
                [ 'back_link' => true ]
            );
        }
        // Check WooCommerce configured
        if ( !get_option( 'woocommerce_currency' ) ) {
            deactivate_plugins( plugin_basename( KANZU_STOREVOICEAI_PLUGIN_FILE ) );
            wp_die(
                esc_html__( 'Please complete WooCommerce setup before activating StoreVoiceAI.', 'storevoiceai-for-woocommerce' ),
                esc_html__( 'WooCommerce not configured', 'storevoiceai-for-woocommerce' ),
                [ 'back_link' => true ]
            );
        }
        // Defer site registration to admin_init so the DI container, autoloader,
        // and WooCommerce helpers are guaranteed to be loaded.
        update_option( '_storevoiceai_needs_registration', 1 );

        // Trigger our onboarding wizard on the next admin page load, unless
        // the user has already completed it on a previous install.
        if ( ! get_option( '_storevoiceai_onboarding_complete' ) ) {
            update_option( '_storevoiceai_onboarding_redirect', 1 );
        }
    }

    public static function maybe_register_site() {
        if ( get_option( '_storevoiceai_site_registered' ) ) {
            \Kanzu\StoreVoiceAI\Hook_Registry::sync_license_state();
            return;
        }
        if ( !get_option( '_storevoiceai_needs_registration' ) ) {
            return;
        }
        if ( !class_exists( 'WooCommerce' ) ) {
            return;
        }
        \Kanzu\StoreVoiceAI\Hook_Registry::register_site_with_backend();
    }

}

register_activation_hook( __FILE__, ['Kanzu\\StoreVoiceAI\\Kanzu_StoreVoiceAI', 'storevoiceai_on_activate'] );
add_action( 'admin_init', ['Kanzu\\StoreVoiceAI\\Kanzu_StoreVoiceAI', 'maybe_register_site'] );
/**
 * Make Kanzu_StoreVoiceAI class instance available globally
 */
function Kanzu_StoreVoiceAI() {
    return Kanzu_StoreVoiceAI::get_instance();
}

Kanzu_StoreVoiceAI();
