<?php

namespace Bspb\Pay;

class BspbPlugin
{
    use OverallTrait;
    use DBTrait;

    const PAYSYSTEMCODE = 'woocommerce-bspb';

    private static $instance;
    private static $pluginDir;
    private $pluginHandler;
    private $mainPluginFile;

    public static function getInstance()
    {
        if (!self::$instance) {
            global $wpdb;
            self::$instance = new self();
            self::$instance::$pluginDir = dirname(__DIR__);
            self::$instance->pluginHandler = __FILE__;
            self::$instance->mainPluginFile = self::$instance::$pluginDir . DIRECTORY_SEPARATOR . 'woocommerce-bspb.php';
            self::$instance->db = $wpdb; //declared in trait
            self::$instance->tableFullName = self::$instance->db->get_blog_prefix() . self::$tableName; //declared in trait
        }

        return self::$instance;
    }

    public static function getPluginDir(): string
    {
        if (!self::$pluginDir) self::$pluginDir = dirname(__DIR__);
        return self::$pluginDir;
    }

    public function run()
    {
        //CompabilityWithWOOBlocks
        add_action( 'woocommerce_blocks_loaded', function () {
            if ( class_exists( 'Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType' ) ) {
                add_action(
                    'woocommerce_blocks_payment_method_type_registration',
                    function( \Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry ) {
                        $payment_method_registry->register( new BspbPaymentMethod );
                    }
                );
            }
        } );

        //Install-uninstall
        register_activation_hook($this->mainPluginFile, [$this, 'registerActivationHook']);
        add_filter('woocommerce_payment_gateways', [$this, 'paymentGateways']);
    }

    public function registerActivationHook()
    {
        $this->db->query("CREATE TABLE IF NOT EXISTS `" . $this->tableFullName . "` (
		`id` int(11) unsigned NOT NULL auto_increment,
		`wp_order_id` int(11) NOT NULL,
		`amount` int(11),
		`bank_order_id` varchar(32) NOT NULL,
		`password` varchar(32) NOT NULL,
		`hppUrl` varchar(32) NOT NULL,
		`status` varchar(100) NOT NULL,
		`basketdata` text NOT NULL,		
		`created` datetime,
		`updated` datetime,
		PRIMARY KEY (`id`),
		INDEX IX_BSPB_ORDERS_WP_ORDER_ID (`wp_order_id`),
        INDEX IX_BSPB_ORDERS_BANK_ORDER_ID (`bank_order_id`)
		) DEFAULT CHARSET=" . $this->db->charset . ";");
    }

    public function paymentGateways($gateways)
    {
        $gateways['bspb_payment'] = '\Bspb\Pay\BspbPayment';
        return $gateways;
    }

}
