Your code is a bit outdated and you are not using the right hook. Also there are some mistakes. Try the following instead:
add_action( 'woocommerce_before_calculate_totals', 'country_based_discount' );
function country_based_discount( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$coupon_code = 'mohannad';
$allowed_countries = array('PS');
$is_coupon_applied = in_array( $coupon_code, $cart->get_applied_coupons() );
$is_country_allowed = in_array( WC()->customer->get_shipping_country(), $allowed_countries );
if( ! $is_coupon_applied && $is_country_allowed ) {
$cart->apply_coupon( $coupon_code );
}
elseif( $is_coupon_applied && ! $is_country_allowed ) {
$cart->remove_coupon( $coupon_code );
}
}
Code goes in functions.php file of the active child theme (or active theme). It should work.
Addition - Handling a minimal subtotal amount (related to your comment):
add_action( 'woocommerce_before_calculate_totals', 'country_based_discount' );
function country_based_discount( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$coupon_code = 'mohannad';
$allowed_countries = array('PS');
$min_amount = 120;
$cart_subtotal = WC()->cart->subtotal;
$is_coupon_applied = in_array( $coupon_code, $cart->get_applied_coupons() );
$is_country_allowed = in_array( WC()->customer->get_shipping_country(), $allowed_countries );
if( ! $is_coupon_applied && $is_country_allowed && $cart_subtotal >= $min_amount ) {
$cart->apply_coupon( $coupon_code );
}
elseif( $is_coupon_applied && ! $is_country_allowed && $cart_subtotal < $min_amount ) {
$cart->remove_coupon( $coupon_code );
}
}
It should work too.