<?php

namespace BSD_Split_Pay_Stripe_Connect_Woo\Inc;

defined( 'ABSPATH' ) || exit;

if ( ! function_exists( 'BSD_Split_Pay_Stripe_Connect_Woo\Inc\bsd_scsp_activate_plugin' ) ) {
	function bsd_scsp_activate_plugin() {
	global $wpdb;
	
	if ( version_compare( get_bloginfo( 'version' ), '5.0', '<' ) ) {
		wp_die( esc_html__( 'You must update WordPress to use this plugin.', 'bsd-split-pay-stripe-connect-woo' ) );
	}
	require_once ABSPATH . 'wp-admin/includes/upgrade.php';

	if (function_exists('is_multisite') && is_multisite()) {
			$blog_ids = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs");
            foreach ($blog_ids as $blog_id) {
                switch_to_blog($blog_id);
                create_plugin_tables();
                restore_current_blog();
            }
		}else{
			create_plugin_tables();
		}
		

		$has_stripe_keys = false;

		$woocommerce_stripe_settings = get_option( 'woocommerce_stripe_settings' );
		if ( $woocommerce_stripe_settings && isset( $woocommerce_stripe_settings['enabled'] ) && $woocommerce_stripe_settings['enabled'] == 'yes' ) {
			$testmode = $woocommerce_stripe_settings['testmode'] ?? '';

			$stripe_test_api_public_key = get_option( 'stripe_test_api_public_key', false );
			$stripe_test_api_secret_key = get_option( 'stripe_test_api_secret_key', false );
			$stripe_api_public_key      = get_option( 'stripe_api_public_key', false );
			$stripe_api_secret_key      = get_option( 'stripe_api_secret_key', false );

			if ( $testmode == 'yes' ) {
				if ( ! empty( $stripe_test_api_public_key ) || ! empty( $stripe_test_api_secret_key ) ) {
					$has_stripe_keys = true;
				}
			} elseif ( ! empty( $stripe_api_public_key ) || ! empty( $stripe_api_secret_key ) ) {
				$has_stripe_keys = true;
			}
		}

		$stripe_test_api_secret_key = get_option( 'stripe_test_api_secret_key', false );
		$stripe_api_secret_key      = get_option( 'stripe_api_secret_key', false );
		if ( ! empty( $stripe_test_api_secret_key ) || ! empty( $stripe_api_secret_key ) ) {
			$has_stripe_keys = true;
		}

		if ( $has_stripe_keys ) {
			add_option( 'spp_setting_redirect', '2' );
		} else {
			add_option( 'spp_setting_redirect', '1' );
		}
	}
}


if ( ! function_exists( 'BSD_Split_Pay_Stripe_Connect_Woo\Inc\create_plugin_tables' ) ) {
	function create_plugin_tables() {
		global $wpdb;
		$table_prefix = $wpdb->prefix;
		$table_name   = $table_prefix . SPP_TRANSFER_LOG_TABLE;
		try {

			// $table_name is the constant log table ($wpdb->prefix . SPP_TRANSFER_LOG_TABLE); SHOW takes a constant identifier with no bindable user input.
			if ( $wpdb->get_var( "SHOW TABLES LIKE '" . $table_name . "'" ) != $table_name ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- constant table identifier, no user input.
				// dbDelta( "SET sql_mode = '';" );
				$sql = 'CREATE TABLE ' . $table_name . '(
                        id INT NOT NULL AUTO_INCREMENT
                        , wc_order_id BIGINT UNSIGNED
                        , charge_amount decimal(10,2)
                        , transfer_amount decimal(10,2)
                        , transfer_tax_value decimal(10,2)
                        , transfer_entered_value decimal(10,2)
                        , item_total decimal(10,2)
                        , item_transfer_amount decimal(10,2)
                        , item_tax_total decimal(10,2)
                        , tax_transfer_type char(5)
                        , charge_id VARCHAR(50)
                        , charge_date DATETIME
                        , charge_description VARCHAR(200)
                        , transfer_id VARCHAR(50)
                        , transfer_destination VARCHAR(50)
                        , stripe_mode VARCHAR(5)
                        , transfer_type tinyint(2)
                        , date_created DATETIME NOT NULL DEFAULT "0000-00-00 00:00:00"
                        , date_modified DATETIME NOT NULL DEFAULT "0000-00-00 00:00:00"
                        , PRIMARY KEY (id)
              ) ENGINE=InnoDB ' . $wpdb->get_charset_collate() . ';';

				$is_table_created = dbDelta( $sql );
				update_option( 'bsd_log_table_created', '1.4' );
			}
		} catch ( \Exception $e ) {
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( '[BSD Split Pay for Stripe Connect Activation] Error creating database table: ' . $table_name ); } // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log

		}

		$charset_collate = $wpdb->get_charset_collate();
		$table_name      = $table_prefix . SPP_STRP_ACCNT_TABLE;
		try {
			// $table_name is the constant account table ($wpdb->prefix . SPP_STRP_ACCNT_TABLE); SHOW takes a constant identifier with no bindable user input.
			if ( $wpdb->get_var( "SHOW TABLES LIKE '" . $table_name . "'" ) != $table_name ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- constant table identifier, no user input.
				$sql = 'CREATE TABLE IF NOT EXISTS ' . $table_name . " (
                        bsd_sat_id bigint(20) NOT NULL AUTO_INCREMENT,
                        bsd_account_id varchar(55) DEFAULT '' NOT NULL,
                        bsd_account_name varchar(55) DEFAULT '' NOT NULL,
                        bsd_account_email varchar(255) DEFAULT '' NOT NULL,
                        bsd_account_mode varchar(10) DEFAULT '' NOT NULL,
                        PRIMARY KEY  (bsd_sat_id)
                    ) $charset_collate;";

				$is_table_created = dbDelta( $sql );
				if ( ! empty( $is_table_created ) ) {
					update_option( 'spp_account_id_table', '1.1' );
				}
			}
		} catch ( \Exception $e ) {
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( '[BSD Split Pay for Stripe Connect Activation] Error creating database table: ' . $table_name ); } // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
		}

		$table_name = $table_prefix . SPP_CONNECTED_ID_TABLE;
		try {
			// $table_name is the constant connected-id table ($wpdb->prefix . SPP_CONNECTED_ID_TABLE); SHOW takes a constant identifier with no bindable user input.
			if ( $wpdb->get_var( "SHOW TABLES LIKE '" . $table_name . "'" ) != $table_name ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- constant table identifier, no user input.
				$sql = 'CREATE TABLE IF NOT EXISTS ' . $table_name . " (
                        bsd_connected_id bigint(20) NOT NULL AUTO_INCREMENT,
                        bsd_connected_account_id varchar(55) DEFAULT '' NOT NULL,
                        bsd_spscwt_type varchar(50) DEFAULT '' NOT NULL,
                        bsd_spscwt_percentage_amount double DEFAULT 0 NOT NULL,
                        bsd_global_shipping_type varchar(50) DEFAULT '' NOT NULL,
                        bsd_global_shipping_percentage_amount double DEFAULT 0 NOT NULL,
                        PRIMARY KEY  (bsd_connected_id)
                    ) $charset_collate;";

				$is_table_created = dbDelta( $sql );
				if ( ! empty( $is_table_created ) ) {
					update_option( 'bsd_connected_id_table_created', '1.1' );
				}
			}
		} catch ( \Exception $e ) {
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( '[BSD Split Pay for Stripe Connect Activation] Error creating database table: ' . $table_name ); } // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
		}
	}
}