Current File : /home/quantums/cryptocopytrade.io/wp-content/themes/hello-elementor-child/functions.php
<?php
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;

// BEGIN ENQUEUE PARENT ACTION
// AUTO GENERATED - Do not modify or remove comment markers above or below:
if ( !function_exists( 'chld_thm_cfg_locale_css' ) ):
function chld_thm_cfg_locale_css( $uri ){
	if ( empty( $uri ) && is_rtl() && file_exists( get_template_directory() . '/rtl.css' ) )
		$uri = get_template_directory_uri() . '/rtl.css';
	return $uri;
}
endif;
add_filter( 'locale_stylesheet_uri', 'chld_thm_cfg_locale_css' );

if ( !function_exists( 'child_theme_configurator_css' ) ):
function child_theme_configurator_css() {
	wp_enqueue_style( 'chld_thm_cfg_child', trailingslashit( get_stylesheet_directory_uri() ) . 'style.css', array( 'hello-elementor','hello-elementor','hello-elementor-theme-style','hello-elementor-header-footer' ) );
}
endif;
add_action( 'wp_enqueue_scripts', 'child_theme_configurator_css', 99 );

// END ENQUEUE PARENT ACTION

// Step 1: Add custom price input field on checkout
add_action('woocommerce_after_order_notes', function($checkout) {
	$range = get_investment_range_from_cart();
	$min = $range ? $range['min'] : 500;
	$max = $range ? $range['max'] : 1000;
	$label = "Your Investment Amount (USD) — Min: $$min, Max: $$max";

	echo '<div id="custom_price_field"><h3>Enter Investment Amount</h3>';
	woocommerce_form_field('custom_price_input', [
		'type'        => 'number',
		'required'    => true,
		'label'       => $label,
		'class'       => ['form-row-wide'],
		'custom_attributes' => [
			'min'  => $min,
			'max'  => $max,
			'step' => 1,
		]
	], $checkout->get_value('custom_price_input'));
	echo '</div>';

?>
<div class="assets_checkout">
	<button id="toggle-info-btn" type="button" >
		Go to Assets Page
	</button>
	<div id="slide-text" >
		💡 Once your information has been successfully submitted, you will gain access to your assets page.
	</div>
</div>

<script>
	document.addEventListener("DOMContentLoaded", function() {
		const toggleBtn = document.getElementById("toggle-info-btn");
		const slideText = document.getElementById("slide-text");

		toggleBtn.addEventListener("click", function() {
			if (slideText.style.display === "none" || slideText.style.display === "") {
				slideText.style.display = "block";
			} else {
				slideText.style.display = "none";
			}
		});
	});
</script>
<?php

});


// Step 2: Capture custom price input on order review update
add_action('woocommerce_checkout_update_order_review', function($post_data) {
	parse_str($post_data, $data);
	if (!empty($data['custom_price_input'])) {
		WC()->session->set('custom_price_input', floatval($data['custom_price_input']));
	}
});

// Step 3: Validate custom input based on product in cart
add_action('woocommerce_checkout_process', function() {
	if (!isset($_POST['custom_price_input']) || !is_numeric($_POST['custom_price_input'])) {
		wc_add_notice('Please enter a valid investment amount.', 'error');
		return;
	}

	$amount = floatval($_POST['custom_price_input']);
	$range = get_investment_range_from_cart();

	if (!$range || $amount < $range['min'] || $amount > $range['max']) {
		wc_add_notice("Please enter a valid investment amount between \${$range['min']} and \${$range['max']}.", 'error');
	}
});

function get_investment_range_from_cart() {
	$ranges = [
		527 => ['min' => 1000, 'max' => 2000],
		717 => ['min' => 2001, 'max' => 5000],
		718 => ['min' => 5001, 'max' => 20000],
	];

	foreach (WC()->cart->get_cart() as $item) {
		$product_id = $item['product_id'];
		if (isset($ranges[$product_id])) {
			return $ranges[$product_id];
		}
	}

	return false;
}

// Step 4: Apply custom price to product
add_action('woocommerce_before_calculate_totals', function($cart) {
	if (is_admin() && !defined('DOING_AJAX')) return;

	$custom_price = WC()->session->get('custom_price_input');
	$range = get_investment_range_from_cart();

	if ($custom_price && $range && $custom_price >= $range['min'] && $custom_price <= $range['max']) {
		foreach ($cart->get_cart() as $item) {
			$item['data']->set_price($custom_price);
		}
	}
}, 20, 1);

// Step 5: Save the price to order item meta
add_action('woocommerce_checkout_create_order_line_item', function($item, $cart_item_key, $values, $order) {
	$custom_price = WC()->session->get('custom_price_input');
	if ($custom_price) {
		$item->update_meta_data('Investment Amount', $custom_price);
	}
}, 10, 4);

// Step 6: Clear session after order
add_action('woocommerce_thankyou', function() {
	WC()->session->__unset('custom_price_input');
});

// Step 7: Live update price on custom input change
add_action('wp_footer', function() {
	if (!is_checkout()) return;
?>
<script>
	jQuery(function($){
		$(document).on('input', '#custom_price_input', function(){
			$('body').trigger('update_checkout');
		});
	});
</script>
<?php
});

// Step 8: Enforce only one plan product in cart
add_filter('woocommerce_add_to_cart_validation', function($passed, $product_id) {
	$plan_ids = [527, 717, 718];
	if (in_array($product_id, $plan_ids)) {
		foreach (WC()->cart->get_cart() as $key => $item) {
			if (in_array($item['product_id'], $plan_ids) && $item['product_id'] !== $product_id) {
				WC()->cart->remove_cart_item($key);
			}
		}
	}
	return $passed;
}, 10, 2);

// Change "Order" Text to "Txnid" 
add_filter( 'woocommerce_my_account_my_orders_columns', 'change_order_column_to_txid' );
function change_order_column_to_txid( $columns ) {
	if ( isset( $columns['order-number'] ) ) {
		$columns['order-number'] = __( 'Txnid', 'woocommerce' );
	}
	return $columns;
}

// Add custom dashboard content with design
add_action( 'woocommerce_account_dashboard', 'custom_account_dashboard_summary' );

function custom_account_dashboard_summary() {
	if ( ! is_user_logged_in() ) return;

	$user_id = get_current_user_id();

	// Get total spent
	$orders = wc_get_orders([
		'customer_id' => $user_id,
		'status'      => ['completed'],
		'return'      => 'ids',
		'limit'       => -1,
	]);

	$total_spent = 0;
	foreach ( $orders as $order_id ) {
		$order = wc_get_order( $order_id );
		$total_spent += (float) $order->get_total();
	}

	// Get recent orders
	$recent_orders = wc_get_orders([
		'customer_id' => $user_id,
		'limit'       => 3,
		'orderby'     => 'date',
		'order'       => 'DESC',
	]);

	// Output starts here
?>
<div style="margin-bottom: 40px;">


	<div style="background: #fff; border-radius: 12px; padding: 30px; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05); display: flex; align-items: center; flex-direction: column; max-width: 300px;">
		<div style="margin-bottom: 15px;">
			<div style="width: 70px; height: 70px; background: #e6f0ff; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
				<img src="https://img.icons8.com/ios-filled/50/3366ff/investment.png" alt="Investment Icon" style="width: 36px; height: 36px;">
			</div>
		</div>
		<div style="font-size: 26px; font-weight: bold; color: #3366ff; margin-bottom: 5px;">
			<?php echo wc_price($total_spent); ?>
		</div>
		<div style="font-size: 14px; color: #555;">
			Total Investment
		</div>
	</div>
</div>

<div class= "table_parent" style="margin-top: 40px;">

	<table class="woocommerce-orders-table woocommerce-MyAccount-orders shop_table  my_account_orders" style="width: 100%;">
		<thead>
			<tr>
				<th><span class="nobr">Txnid</span></th>
				<th><span class="nobr">Date</span></th>
				<th><span class="nobr">Status</span></th>
				<th><span class="nobr">Total</span></th>
			</tr>
		</thead>
		<tbody>
			<?php foreach ( $recent_orders as $order ) :
	$order_id = $order->get_id();
	$order_date = $order->get_date_created()->date('F j, Y');
	$order_status = wc_get_order_status_name( $order->get_status() );
	$order_total = $order->get_formatted_order_total();
			?>
			<tr>
				<td>#<?php echo $order_id; ?></td>
				<td><?php echo $order_date; ?></td>
				<td><?php echo $order_status; ?></td>
				<td><?php echo $order_total; ?></td>
			</tr>
			<?php endforeach; ?>
		</tbody>
	</table>
</div>
<?php
}

add_action( 'template_redirect', 'custom_redirect_after_purchase' );
function custom_redirect_after_purchase() {
	global $wp;

	if ( strpos( $wp->request, 'checkout/thank-you/' ) === 0 && isset( $_GET['key'] ) ) {
		$order_key = sanitize_text_field( $_GET['key'] );
		$order_id = wc_get_order_id_by_order_key( $order_key );

		if ( $order_id ) {
			$redirect_url = add_query_arg( 'id', $order_id, get_permalink( 1724 ) );
			wp_redirect( $redirect_url );
			exit;
		}
	}

	if ( strpos( $wp->request, 'my-account/assets/' ) === 0 ) {
		$redirect_url = 'https://cryptocopytrade.io/assets/';
		wp_redirect( $redirect_url );
		exit;
	}
}

add_filter('woocommerce_checkout_fields', function($fields) {
	unset($fields['shipping']);
	unset( $fields['billing']['billing_country'] );
	unset( $fields['billing']['billing_address_1'] );
	unset( $fields['billing']['billing_address_2'] );
	unset( $fields['billing']['billing_city'] );
	unset( $fields['billing']['billing_state'] );
	unset( $fields['billing']['billing_postcode'] );
	unset( $fields['billing']['billing_phone'] );
	return $fields;
});

add_filter('woocommerce_enable_order_notes_field', '__return_false');
add_filter('woocommerce_cart_needs_shipping_address', '__return_false');
add_filter('woocommerce_coupons_enabled', '__return_false');
add_filter('woocommerce_cart_needs_shipping', '__return_false');
add_filter('woocommerce_get_order_item_totals', function ($total_rows, $order) {
	if (isset($total_rows['payment_method'])) {
		unset($total_rows['payment_method']);
	}
	return $total_rows;
}, 10, 2);


if (function_exists('acf_add_options_page')) {
	acf_add_options_page(array(
		'page_title'    => 'Payment Settings',
		'menu_title'    => 'Payment Settings',
		'menu_slug'     => 'payment-settings',
		'capability'    => 'manage_options',
		'redirect'      => false
	));
}


function payment_settings_function() {
	$coin_name = get_field('coin_name', 'option');
	$coin_network = get_field('coin_network', 'option');
	$wallet_account_address = get_field('wallet_account_address', 'option');
	$wallet_account_qr = get_field('wallet_account_qr', 'option');
	$wallet_qr_url = is_array($wallet_account_qr) ? $wallet_account_qr['url'] : '';
?>

<div class="deposit-container">
	<div class="form-section">
		<label>Coin to deposit</label>
		<select id="coinSelect">
			<?php if ($coin_name): ?>
			<option value="<?php echo esc_attr(strtolower($coin_name)); ?>"><?php echo esc_html($coin_name); ?></option>
			<?php endif; ?>
		</select>

		<label>Network</label>
		<div class="custom-select">
			<select id="networkSelect">
				<?php if ($coin_network): ?>
				<option value="<?php echo esc_attr('network_' . strtolower($coin_network)); ?>"><?php echo esc_html($coin_network); ?></option>
				<?php endif; ?>
			</select>
		</div>
	</div>

	<div class="qr-section">
		<p class="qr-title">Your verified Bitcoin funding address</p>
		<p class="wallet-address" id="walletAddress"><?php echo esc_html($wallet_account_address); ?></p>

		<div class="qr-buttons">
			<button onclick="copyAddress()"><i class="fas fa-copy"></i> Copy Address</button>
			<button onclick="toggleQR(this)"><i class="fas fa-qrcode"></i> Hide QR Code</button>
		</div>

		<div class="qr-code" id="qrCode" style="display: block;">
			<img id="qrImg" src="<?php echo esc_url($wallet_qr_url); ?>" alt="QR Code">
		</div>
	</div>
</div>

<script>
	function copyAddress() {
		const address = document.getElementById("walletAddress").innerText;
		navigator.clipboard.writeText(address).then(() => {
			alert("Address copied!");
		});
	}

	function toggleQR(btn) {
		const qr = document.getElementById("qrCode");
		const visible = qr.style.display === "block";
		qr.style.display = visible ? "none" : "block";
		btn.innerHTML = `<i class="fas fa-qrcode"></i> ${visible ? "Show QR Code" : "Hide QR Code"}`;
	}
</script>
<?php
}

add_shortcode('payment_settings', 'payment_settings_function');

function show_user_account_link() {
	if ( is_user_logged_in() ) {
		$current_user = wp_get_current_user();
		ob_start();
?>
<div class="account-dropdown-wrapper">
	<a href="/my-account" class="account-button">
		👤 My Account 
	</a>
	<div class="account-dropdown-menu">
		<a href="<?php echo esc_url( wp_logout_url( home_url() ) ); ?>" class="logout-button">Logout</a>
	</div>
</div>

<script>
	document.addEventListener('DOMContentLoaded', function() {
		const wrapper = document.querySelector('.account-dropdown-wrapper');
		const menu = wrapper.querySelector('.account-dropdown-menu');

		wrapper.addEventListener('mouseenter', function() {
			menu.style.display = 'block';
		});
		wrapper.addEventListener('mouseleave', function() {
			menu.style.display = 'none';
		});
	});
</script>
<?php
		return ob_get_clean();
	} else {
		return '<a href="/login" class="login-button">Login</a> <a href="/plans" class="signup-button">Sign up</a>';
	}
}
add_shortcode('account_button', 'show_user_account_link');

add_action('template_redirect', 'redirect_my_account_if_not_logged_in');
function redirect_my_account_if_not_logged_in() {
	if (is_page('my-account') && !is_user_logged_in()) {
		wp_redirect(home_url('/login'));
		exit;
	}
}


function selected_plan_function() {
	if ( ! isset( $_GET['id'] ) ) {
		return 'Invalid.';
	}

	$order_id = absint( $_GET['id'] );
	$order = wc_get_order( $order_id );

	if ( ! $order ) {
		return 'Invalid.';
	}

	$product_names = [];

	foreach ( $order->get_items() as $item ) {
		$product = $item->get_product();
		if ( $product ) {
			$product_names[] = $product->get_name();
		}
	}

	if ( empty( $product_names ) ) {
		return 'No plan found.';
	}

	return implode( ', ', $product_names );
}
add_shortcode( 'selected_plan', 'selected_plan_function' );


function min_deposit_function() {
	if ( ! isset( $_GET['id'] ) ) {
		return 'Invalid.';
	}

	$order_id = absint( $_GET['id'] );
	$order = wc_get_order( $order_id );

	if ( ! $order ) {
		return 'Invalid.';
	}

	return wc_price( $order->get_total() );
}
add_shortcode( 'min_deposit', 'min_deposit_function' );

add_action('woocommerce_before_checkout_form', 'show_dynamic_bonus_notice', 5);
function show_dynamic_bonus_notice() {
	if (is_admin() || is_cart()) return;

	$plans = [
		527 => ['invest' => 1500, 'bonus' => 100],
		717 => ['invest' => 4300, 'bonus' => 200],
		718 => ['invest' => 15000, 'bonus' => 1000],
	];

	foreach (WC()->cart->get_cart() as $cart_item) {
		$product_id = $cart_item['product_id'];
		if (isset($plans[$product_id])) {
			$invest = $plans[$product_id]['invest'];
			$bonus = $plans[$product_id]['bonus'];

			echo '
                <div style="
                    display: flex;
                    align-items: center;
                    flex-wrap: wrap;
                    gap: 10px;
                    background-color: #0058ff;
                    color: #fff;
                    padding: 15px 20px;
                    box-sizing: border-box;
                    max-width: 1216px;
                    margin: 0 auto 20px auto;
                    width: 100%;
                ">
                    <svg xmlns=\'http://www.w3.org/2000/svg\' fill=\'#ffffff\' viewBox=\'0 0 24 24\' width=\'24\' height=\'24\' style=\'flex-shrink: 0;\'>
                        <path d=\'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10
                                10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 
                                8-8 8 3.59 8 8-3.59 8-8 8zm-1-13h2v2h-2zm0 
                                4h2v6h-2z\'/>
                    </svg>
                    <div style="flex: 1; min-width: 200px;">
                        <strong>Note:</strong> Invest $' . number_format($invest) . ' or more to get a $' . number_format($bonus) . ' bonus – the bonus will be added automatically once we receive your funds.
                    </div>
                </div>';
			break; // stop after first matched product
		}
	}
}


add_shortcode('order_bonus_notice', 'render_order_bonus_notice');
function render_order_bonus_notice($atts) {
	if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
		return '';
	}

	$order_id = absint($_GET['id']);
	$order = wc_get_order($order_id);
	if (!$order) {
		return '';
	}

	$plans = [
		527 => ['invest' => 1500, 'bonus' => 100],
		717 => ['invest' => 4300, 'bonus' => 200],
		718 => ['invest' => 15000, 'bonus' => 1000],
	];

	foreach ($order->get_items() as $item) {
		$product_id = $item->get_product_id();
		if (isset($plans[$product_id])) {
			$invest = $plans[$product_id]['invest'];
			$bonus = $plans[$product_id]['bonus'];

			return '<strong>Note:</strong> Invest $' . number_format($invest) . ' or more to get a $' . number_format($bonus) . ' bonus – the bonus will be added automatically once we receive your funds.';
		}
	}

	return ''; 
}



// Assets data code
function custom_dashboard_shortcode() {
	if ( ! is_user_logged_in() ) {
		return '<p>Please log in to view your dashboard.</p>';
	}

	ob_start();
	$user_id = get_current_user_id();
	$my_total_assets = get_field('my_total_assets', 'user_' . $user_id);
?>

<div style="margin-bottom: 40px;">
	<div class="flex_box_parent">
		<div class="cardBox" style="background: #fff; border-radius: 12px; padding: 30px; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05); display: flex; align-items: center; flex-direction: column; width: 300px;">
			<div style="margin-bottom: 15px;">
				<div style="width: 70px; height: 70px; background: #e6f0ff; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
					<img src="https://img.icons8.com/ios-filled/50/3366ff/investment.png" alt="Investment Icon" style="width: 36px; height: 36px;">
				</div>
			</div>
			<div style="font-size: 26px; font-weight: bold; color: #3366ff; margin-bottom: 5px;">
				<p style="font-weight: bold; margin-bottom: 25px;">
					<span class="light_txt">$</span> <?php echo esc_html($my_total_assets); ?>
				</p>
			</div>
			<div style="font-size: 14px; color: #555;">
				MY ASSETS
			</div>
		</div>
		<div class="flex_box dsh_btn">
			<a href="https://cryptocopytrade.io/deposits/"><button class="deposit_btn">Deposit</button></a>
			<a href="https://cryptocopytrade.io/contact-us/"><button class="withdraw_btn"> Withdraw</button></a>
		</div>
	</div>
</div>

<h2>Open Position</h2>
<div class="table_parent" style="margin-top: 40px;">
	<table class="woocommerce-orders-table woocommerce-MyAccount-orders shop_table my_account_orders" style="width: 100%;">
		<thead>
			<tr>
				<th><span class="nobr">Contract</span></th>
				<th><span class="nobr">QTY</span></th>
				<th><span class="nobr">Value</span></th>
				<th><span class="nobr">Entry Price</span></th>
				<th><span class="nobr">Market Price</span></th>
				<th><span class="nobr">Liq. Price</span></th>
				<th><span class="nobr">Margin</span></th>
				<th><span class="nobr">Unreal. P&L</span></th>
				<th><span class="nobr">Realized P&L</span></th>
			</tr>
		</thead>
		<tbody>
			<?php if( have_rows('open_position', 'user_' . $user_id) ): ?>
			<?php while( have_rows('open_position', 'user_' . $user_id) ): the_row(); ?>
			<tr>
				<td><?php the_sub_field('contract'); ?></td>
				<td><?php the_sub_field('qty'); ?></td>
				<td><?php the_sub_field('value'); ?></td>
				<td><?php the_sub_field('entry_price'); ?></td>
				<td><?php the_sub_field('market_price'); ?></td>
				<td><?php the_sub_field('liq_price'); ?></td>
				<td><?php the_sub_field('margin'); ?></td>
				<td><?php the_sub_field('unreal_p&l'); ?></td>
				<td><?php the_sub_field('realized_p&l'); ?></td>
			</tr>
			<?php endwhile; ?>
			<?php else: ?>
			<tr><td colspan="9">No open positions found.</td></tr>
			<?php endif; ?>
		</tbody>
	</table>
</div>

<h2>Closed Position</h2>
<div class="table_parent" style="margin-top: 40px;">
	<table class="woocommerce-orders-table woocommerce-MyAccount-orders shop_table my_account_orders" style="width: 100%;">
		<thead>
			<tr>
				<th><span class="nobr">Market</span></th>
				<th><span class="nobr">Instrument</span></th>
				<th><span class="nobr">Direction</span></th>
				<th><span class="nobr">Entry Price</span></th>
				<th><span class="nobr">Exit Price</span></th>
				<th><span class="nobr">Quantity</span></th>
				<th><span class="nobr">P&L</span></th>
			</tr>
		</thead>
		<tbody>
			<?php if( have_rows('closed_position', 'user_' . $user_id) ): ?>
			<?php while( have_rows('closed_position', 'user_' . $user_id) ): the_row(); ?>
			<tr>
				<td><?php the_sub_field('market'); ?></td>
				<td><?php the_sub_field('instrument'); ?></td>
				<td><?php the_sub_field('direction'); ?></td>
				<td><?php the_sub_field('entry_price'); ?></td>
				<td><?php the_sub_field('exit_price'); ?></td>
				<td><?php the_sub_field('quantity'); ?></td>
				<td><?php the_sub_field('p&l'); ?></td>
			</tr>
			<?php endwhile; ?>
			<?php else: ?>
			<tr><td colspan="7">No closed positions found.</td></tr>
			<?php endif; ?>
		</tbody>
	</table>
</div>

<?php
	return ob_get_clean();
}
add_shortcode('custom_dashboard', 'custom_dashboard_shortcode');

function change_assets_link_script() {
?>
<script>
	document.addEventListener("DOMContentLoaded", function () {
		const menuLinks = document.querySelectorAll('.woocommerce-MyAccount-navigation-link a');
		menuLinks.forEach(link => {
			if (link.textContent.trim() === "Assets") {
				link.href = "https://cryptocopytrade.io/assets/";
			}
		});
	});
</script>
<?php
}
add_action('wp_footer', 'change_assets_link_script');

add_filter('woocommerce_checkout_fields', 'add_confirm_password_checkout_field');
function add_confirm_password_checkout_field($fields) {
	if (get_option('woocommerce_enable_signup_and_login_from_checkout') === 'yes') {
		$fields['account']['account_password2'] = array(
			'type'        => 'password',
			'label'       => __('Confirm password'),
			'required'    => true,
			'priority'    => 999,
		);
	}
	return $fields;
}

add_action('woocommerce_checkout_process', 'validate_confirm_password_field');
function validate_confirm_password_field() {
	if (!is_user_logged_in()) {
		$checkout_registration_enabled = get_option('woocommerce_enable_signup_and_login_from_checkout') === 'yes';

		$password1 = isset($_POST['account_password']) ? $_POST['account_password'] : '';
		$password2 = isset($_POST['account_password2']) ? $_POST['account_password2'] : '';

		if ($checkout_registration_enabled && !empty($password1)) {
			if (empty($password2)) {
				wc_add_notice(__('Please confirm your password.'), 'error');
			} elseif ($password1 !== $password2) {
				wc_add_notice(__('Passwords do not match.'), 'error');
			}
		}
	}
}

add_action('template_redirect', function () {
	if (is_singular('product')) {
		wp_redirect('https://cryptocopytrade.io/plans/', 301);
		exit;
	}
	if (is_tax('product_cat')) {
		wp_redirect('https://cryptocopytrade.io/plans/', 308);
		exit;
	}
});