<?php
if (!defined('ABSPATH')) {
    exit;
}
require_once CHAMA_PATH . '/inc/secrets.php';
$validate_with_recaptcha = CHAMA_RECAPTCHA_SITE_KEY && CHAMA_RECAPTCHA_SECRET_KEY;
$publishable_key = chama_is_live_mode() ? CHAMA_STRIPE_LIVE_PUBLISHABLE_KEY : CHAMA_STRIPE_TEST_PUBLISHABLE_KEY;
$meta = sanitize_text_field( wp_unslash( filter_input(INPUT_GET, 'meta', FILTER_SANITIZE_FULL_SPECIAL_CHARS) ) );
$show_subscription_options = !empty( $meta );
$init_amount = 0;
$init_amount_cents = 0;
$display_amount = '';
$order_summary = array();
$min_limit = 0;
$type = 'membership';
$email = '';
$first_name = '';
$last_name = '';
$description = '';
$confirmation_url = '';
$tier_id = 0;
$product_id = '';
$price_id = '';
$stripe_customer_session_client_secret = '';

if ($show_subscription_options) {
    $payment_data = unserialize(base64_decode($meta));
    if (is_user_logged_in()) {
        $user = wp_get_current_user();
        $user_id            = $user->ID;
        $email = $user->user_email;
        $first_name = $user->first_name;
        $last_name = $user->last_name;
        $full_name          = $first_name . ' ' . $last_name;
        $stripe_customer_id = get_user_meta($user_id, 'chama_stripe_customer_id', true);
        //setup stripe customer session
        if (! $stripe_customer_id) {
            $stripe_customer_id = chama_user_add_stripe_customer_id($user_id, $email, $full_name);
        }
        try {
            $secret_key = chama_is_live_mode() ? CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;
            if ($secret_key && $stripe_customer_id) {
                $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
                    $secret_key // API Secret here
                );
                $stripe_customer_session = $stripe->customerSessions->create([
                    'customer'   => $stripe_customer_id,
                    'components' => [
                        'payment_element' => [
                            'enabled'  => true,
                            'features' => [
                                'payment_method_redisplay'  => 'enabled',
                                'payment_method_save'       => 'enabled',
                                'payment_method_save_usage' => 'off_session',
                                'payment_method_remove'     => 'enabled',
                            ],
                        ],
                    ],
                ]);
                $stripe_customer_session_client_secret = $stripe_customer_session->client_secret;
            }
        } catch (Exception $e) {
            //do nothing
        }
    }
    $init_amount = $payment_data['amount'];
    $init_amount_cents = $init_amount * CHAMA_CURRENCY_MINIMUM;
    $display_amount = chama_get_formatted_price($init_amount_cents);
    $description = $payment_data['tier'];
    $tier_id = (int) $payment_data['tier_id'];
    $min_limit = get_post_meta($tier_id, 'tier_price', true);
    $product_id = $payment_data['product_id'];
    $price_id = $payment_data['price_id'];
    $order_summary = array
        (
        array("label" => $description . ' (per month)', "amount" => $display_amount),
        array("label" => "Total", "amount" => $display_amount),
    );

}
$confirmation_url_args = array(
    'type' => $type,
    'chama_nonce' => wp_create_nonce('chama_issue_receipt'),
    'chama_action' => 'receipt',
);
if ($tier_id) {
    $confirmation_url_args['tier_id'] = $tier_id;
}
$confirmation_url = esc_url(add_query_arg(
    $confirmation_url_args,
    home_url()
));
?>
<?php if ($show_subscription_options): ?>
    <div id="chama-payment-errors" role="alert" class="chama-alert chama-alert-error"></div>
    <div class="chama-card">
    <div class="chama-card-body chama-payment-body">

        <form class="chama-form chama-payment-form">
        <div class="chama-payment-content-wrapper">
        <div class="chama-payment-details">
        <div class="chama-loader-wrapper"><div class="chama-loader"><div></div><div></div><div></div></div><h3>Your payment is processing</h3></div>
       <h3>Subscription details</h3>
       <p>
					<label for="chama_subscription_amount">Subscription Amount</label>
                    <div class="chama-input-wrapper">
		                <div class="chama-input-prepend">
		                                    <span class="chama-input-prepend-text">
                                            <?php echo esc_html(CHAMA_SYMBOL); ?>
		                                  </span>
		                                </div>
                    <input type="number" min="<?php echo esc_attr($min_limit); ?>"  max="999999" maxlength="7" pattern="[-+]?[0-9]*[.,]?[0-9]+" step="any" name="chama_subscription_amount" id="chama_subscription_amount" data-symbol="<?php echo esc_attr(CHAMA_SYMBOL); ?>" data-currency="<?php echo esc_attr(CHAMA_CURRENCY); ?>" data-type="<?php echo esc_attr($type); ?>" value="<?php echo esc_attr($init_amount); ?>" data-amount-cents="<?php echo esc_attr($init_amount_cents); ?>" data-currency-min="<?php echo esc_attr(CHAMA_CURRENCY_MINIMUM); ?>" size="30" required class="required" data-msg-min="You must pay at least <?php echo esc_attr(CHAMA_SYMBOL . $min_limit) ?>!">
                    </div>
				</p>

       <?php if (!is_user_logged_in()): ?>
        <p>
					<label for="chama_email">Email</label>
					<input name="chama_email" id="chama_email" class="required" type="email" required="" data-msg="Please enter your email" data-msg-email="Enter a valid email">
				</p>
                <?php else: ?>
                    <input name="chama_email" id="chama_email" type="hidden" value="<?php echo esc_attr($email); ?>">
        <?php endif;?>
     <?php if ($first_name): ?>
        <input name="chama_first_name" id="chama_first_name" type="hidden" value="<?php echo esc_attr($first_name); ?>">
        <?php endif;?>
        <?php if ($last_name): ?>
        <input name="chama_last_name" id="chama_last_name" type="hidden" value="<?php echo esc_attr($last_name); ?>">
        <?php endif;?>

        <div id="chama-payment-element">
          <!-- Elements will create form elements here -->
        </div>
        <?php if ($validate_with_recaptcha): ?>
						<div class="g-recaptcha"
						data-sitekey="<?php echo esc_attr(CHAMA_RECAPTCHA_SITE_KEY); ?>"
						data-badge="inline" data-size="invisible"
						data-callback="setResponse"></div>
						<input type="hidden" id="chama-captcha-response" name="chama-captcha-response" />

				<?php endif;?>
        <input type="hidden" name="chama_action" value="subscribe"/>
        <input type="hidden" id="chama_subscribe_nonce" name="chama_subscribe_nonce" value="<?php echo esc_attr(wp_create_nonce('chama-subscribe-nonce')); ?>"/>
        <?php wp_nonce_field('wp_rest')?>

        <input type="hidden" id="chama_pub_key" name="chama_pub_key" value="<?php echo esc_attr($publishable_key); ?>" />
        <input type="hidden" id="chama_base_rest_url" name="chama_base_rest_url" value="<?php echo esc_url(get_rest_url(null, '/')); ?>" />
        <input type="hidden" id="chama_confirmation_url" name="chama_confirmation_url" value="<?php echo esc_url($confirmation_url); ?>" />
        <input type="hidden" id="chama_description" name="chama_description" value="<?php echo esc_attr($description) ?>" />
        <input type="hidden" id="chama_tier_id" name="chama_tier_id" value="<?php echo esc_attr($tier_id) ?>" />
        <input type="hidden" id="chama_product_id" name="chama_product_id" value="<?php echo esc_attr($product_id) ?>" />
        <input type="hidden" id="chama_price_id" name="chama_price_id" value="<?php echo esc_attr($price_id) ?>" />
        <input type="hidden" id="chama_type" name="chama_type" value="<?php echo esc_attr($type); ?>" />
        <input type="hidden" id="chama_stripe_configuration_id" name="chama_stripe_configuration_id" value="<?php echo esc_attr($stripe_configuration_id); ?>" />
        <?php
            if ($stripe_customer_session_client_secret):
        ?>
        <input type="hidden" id="chama_stripe_customer_session_client_secret" name="chama_stripe_customer_session_client_secret" value="<?php echo esc_attr($stripe_customer_session_client_secret); ?>" />
        <?php endif; ?>
       <input id="chama-submit" type="submit" class="chama-button chama-button-medium chama-block chama-pay-button chama-desktop-pay-button" value="<?php esc_attr_e('Subscribe', 'chama');?>"/>
       </div>
       <div class="chama-order-summary">
       <h3>Order summary</h3>

       <?php
foreach ($order_summary as $key => $value) {
    echo '<hr class="chama-hr">';
    echo '<div class="chama-order-summary-item chama-' . esc_attr($type) . '">';
    foreach ($value as $sub_key => $sub_val) {
        echo '<div class="chama-summary-' . esc_attr($sub_key) . '">' . esc_html($sub_val) . '</div>';
    }
    echo "</div>";
}
?>

       <input type="submit" class="chama-button chama-button-medium chama-block chama-pay-button chama-mobile-pay-button" value="<?php esc_attr_e('Subscribe', 'chama');?>"/>
       </div>
        </div>
        </form>
    </div>
    </div>
<?php endif;?>