<?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_payment_options                  = !empty( $meta );
    $init_amount                           = 0;
    $init_amount_cents                     = 0;
    $display_amount                        = '';
    $order_summary                         = [];
    $min_limit                             = 0;
    $type                                  = '';
    $email                                 = '';
    $first_name                            = '';
    $last_name                             = '';
    $description                           = '';
    $confirmation_url                      = '';
    $campaign_id                           = 0;
    $commission_id                         = 0;
    $commission_request                    = '';
    $allowed_countries                     = '';
    $has_shipping                          = false;
    $stripe_customer_session_client_secret = '';

    if ($show_payment_options) {
        $payment_data = unserialize(base64_decode($meta));
        $type         = $payment_data['type'];
        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' => 'on_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);
        switch ($type) {
            case 'one-time':

                $order_summary =
                    [
                    ["label" => "One time donation", "amount" => $display_amount],
                    ["label" => "Total", "amount" => $display_amount],
                ];
                $min_limit   = get_option('chama_donation_min_limit');
                $description = 'One time donation';
                break;
            case 'membership':
                break;
            case 'crowdfunding':
                $order_summary =
                    [
                    ["label" => $payment_data['description'], "amount" => $display_amount],
                    ["label" => "Total", "amount" => $display_amount],
                ];
                $campaign_id = $payment_data['campaign-id'] ? $payment_data['campaign-id'] : 0;
                $min_limit   = $payment_data['amount'];
                $description = $payment_data['description'];
                break;
            case 'commission':
                $commission_id       = $payment_data['id'] ? $payment_data['id'] : 0;
                $commission_request  = $payment_data['request'];
                $commission_price    = $payment_data['price'];
                $commission_shipping = $payment_data['shipping'];
                $commission_addons   = '';
                $price_cents         = $commission_price * CHAMA_CURRENCY_MINIMUM;
                $price_display       = chama_get_formatted_price($price_cents);
                $order_summary       =
                    [
                    ["label" => $payment_data['description'], "amount" => $price_display],

                ];
                if (array_key_exists('addons', $payment_data) && $payment_data['addons']) {
                    $commission_addons = $payment_data['addons'];
                    $addons            = explode(',', $payment_data['addons']);

                    foreach ($addons as $addon) {
                        $item                = explode('|', $addon);
                        $item_amount         = $item[1];
                        $item_amount_cents   = $item_amount * CHAMA_CURRENCY_MINIMUM;
                        $item_display_amount = chama_get_formatted_price($item_amount_cents);
                        $item_array          = ["label" => $item[0], "amount" => $item_display_amount];
                        $order_summary[]     = $item_array;
                    }
                }
                if ($payment_data['shipping']) {
                    $has_shipping           = true;
                    $shipping               = explode('|', $payment_data['shipping']);
                    $shipping_cost          = $shipping[1];
                    $shipping_location_code = $shipping[2];
                    $continents             = ["AFRICA", "ANTARCTICA", "ASIA", "EUROPE", "NORTH-AMERICA", "OCEANIA", "SOUTH-AMERICA"];
                    if (in_array($shipping_location_code, $continents)) {
                        $allowed_countries = chama_get_coutries_list_by_continent($shipping_location_code);
                    } else {
                        $allowed_countries = $shipping_location_code;
                    }
                    $shipping_cost_cents   = $shipping_cost * CHAMA_CURRENCY_MINIMUM;
                    $shipping_display_cost = chama_get_formatted_price($shipping_cost_cents);
                    $order_summary[]       = ["label" => 'Shipping to ' . $shipping[0], "amount" => $shipping_display_cost];
                }

                $order_summary[] = ["label" => "Total", "amount" => $display_amount];
                $description     = $payment_data['description'];
                break;

            default:
        }
    }
    $confirmation_url_args = [
        'type'         => $type,
        'chama_nonce'  => wp_create_nonce('chama_issue_receipt'),
        'chama_action' => 'receipt',
    ];
    if ($campaign_id) {
        $confirmation_url_args['campaign_id'] = $campaign_id;
    }
    $confirmation_url = esc_url(add_query_arg(
        $confirmation_url_args,
        home_url()
    ));
?>
<?php if ($show_payment_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>
        <?php if ($commission_id && $has_shipping): ?>
            <h3>Shipping details</h3>
        <div id="chama-shipping-element">
          <!-- Elements will create form elements here -->
        </div>
        <?php endif; ?>
       <h3>Payment details</h3>
       <?php if ($type == 'commission'): ?>
        <input type="hidden" name="chama_payment_amount" id="chama_payment_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); ?>" />
        <?php else: ?>
            <p>
					<label for="chama_payment_amount">Payment 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_payment_amount" id="chama_payment_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 endif; ?>

       <?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="pay"/>
        <input type="hidden" id="chama_pay_nonce" name="chama_pay_nonce" value="<?php echo esc_attr(wp_create_nonce('chama-pay-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_type" name="chama_type" value="<?php echo esc_attr($type); ?>" />
        <?php if ($campaign_id): ?>
            <input type="hidden" id="chama_campaign_id" name="chama_campaign_id" value="<?php echo esc_attr($campaign_id); ?>" />
        <?php endif; ?>
<?php if ($commission_id): ?>
            <input type="hidden" id="chama_commission_id" name="chama_commission_id" value="<?php echo esc_attr($commission_id); ?>" />
            <input type="hidden" id="chama_commission_request" name="chama_commission_request" value="<?php echo esc_attr($commission_request); ?>" />
            <input type="hidden" id="chama_commission_price" name="chama_commission_price" value="<?php echo esc_attr($commission_price); ?>" />
            <?php if ($has_shipping): ?>
            <input type="hidden" id="chama_commission_shipping" name="chama_commission_shipping" value="<?php echo esc_attr($commission_shipping); ?>" />
            <?php endif; ?>
<?php if ($commission_addons): ?>
                <input type="hidden" id="chama_commission_addons" name="chama_commission_addons" value="<?php echo esc_attr($commission_addons); ?>" />
            <?php endif; ?>
<?php if ($allowed_countries): ?>
                <input type="hidden" id="chama_commission_allowed_countries" name="chama_commission_allowed_countries" value="<?php echo esc_attr($allowed_countries); ?>" />
            <?php endif; ?>
<?php endif; ?>
        <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 type="submit" class="chama-button chama-button-medium chama-block chama-pay-button chama-desktop-pay-button" value="<?php esc_attr_e('Pay Now', 'chama'); ?>"/>
       </div>
       <div class="chama-order-summary">
       <h3>Order summary</h3>
       <?php if ($commission_request): ?>
        <label>Request</label><br/>
        <?php echo esc_html($commission_request) ?>
<?php endif; ?>
<?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('Pay Now', 'chama'); ?>"/>
       </div>
        </div>
        </form>
    </div>
    </div>
<?php endif; ?>