<?php
if (!defined('ABSPATH')) {
    exit;
}
wp_enqueue_script('chama-stripe');
wp_enqueue_script('chama-billing');
$publishable_key = chama_is_live_mode() ? CHAMA_STRIPE_LIVE_PUBLISHABLE_KEY : CHAMA_STRIPE_TEST_PUBLISHABLE_KEY;
$user = wp_get_current_user();
$payment_method_id = $payment_method_brand = $payment_method_expiration = $payment_method_last4 = $stripe_customer_id = '';
$email = $user->user_email;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$updated = isset($_GET['redirect_status']) && $_GET['redirect_status'] == 'succeeded';
$has_subscription = false;

if ($user) {
    $user_id = $user->ID;
    $has_subscription = get_user_meta($user_id, 'chama_stripe_subscription_id', true);
    if ($has_subscription) {
        $stripe_customer_id = get_user_meta($user_id, 'chama_stripe_customer_id', true);
        if ($updated) {
            $secret_key = chama_is_live_mode() ? CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;
            if ($secret_key) {
                $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
                    $secret_key // API Secret here
                );

                //update payment method
                $payment_methods = $stripe->paymentMethods->all([
                    'type' => 'card',
                    'limit' => 1,
                    'customer' => $stripe_customer_id,
                ]);

                if ($payment_methods) {
                    $latest_payment_method = $payment_methods->data[0];
                    $payment_method_id = $latest_payment_method->id;
                    //update payment method on stripe for customer and subscription
                    $stripe->paymentMethods->attach(
                        $payment_method_id,
                        ['customer' => $stripe_customer_id]
                    );
                    $stripe->customers->update(
                        $stripe_customer_id,
                        ['invoice_settings' => ['default_payment_method' => $payment_method_id]]
                    );
                    //update subscription payment method
                    $stripe_subscription_id = get_user_meta($user_id, 'chama_stripe_subscription_id', true);
                    if ($stripe_subscription_id) {
                        $stripe->subscriptions->update(
                            $stripe_subscription_id,
                            ['default_payment_method' => $payment_method_id]
                        );
                    }
                    $payment_method_brand = $latest_payment_method->card->brand;
                    $payment_method_exp_month = $latest_payment_method->card->exp_month;
                    $payment_method_exp_year = $latest_payment_method->card->exp_year;
                    $payment_method_expiration = $latest_payment_method->card->exp_month . '/' . $latest_payment_method->card->exp_year;
                    $payment_method_last4 = 'Last 4 digits:' . $latest_payment_method->card->last4;
                    update_user_meta($user_id, 'chama_payment_method_id', $payment_method_id);
                    update_user_meta($user_id, 'chama_payment_method_brand', ucfirst($payment_method_brand));
                    update_user_meta($user_id, 'chama_payment_method_expiration', $payment_method_expiration);
                    update_user_meta($user_id, 'chama_payment_method_last4', $payment_method_last4);
                }
            }
        } else {
            $payment_method_id = get_user_meta($user_id, 'chama_payment_method_id', true);
            $payment_method_brand = get_user_meta($user_id, 'chama_payment_method_brand', true);
            $payment_method_expiration = get_user_meta($user_id, 'chama_payment_method_expiration', true);
            $payment_method_last4 = get_user_meta($user_id, 'chama_payment_method_last4', true);

        }
    }

} else {
    // invalid reqeuest
    chama_errors()->add('invalid_request', __('Invalid request.' , 'chama'));
    exit;
}
?>



        <div id="chama-page-content-wrapper">
        <div id="chama-page-content">
        <?php if ($has_subscription): ?>
        
        <h4 class="chama-item-title">Current Payment Method</h4>

<div class="chama-current-payment-method">
<i class="fa-brands fa-2x fa-cc-<?php echo esc_attr(strtolower($payment_method_brand)); ?>"></i> <?php echo esc_html(ucfirst($payment_method_brand) . ' ending in ' . str_replace("Last 4 digits:", "", $payment_method_last4) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Expiration: ' . $payment_method_expiration); ?>
</div>
<hr class="chama-hr" />
<h4 class="chama-item-title">Update Payment Method</h4>
<div  class="chama-alert chama-alert-error" id="chama-payment-errors" role="alert"></div>

<?php if ($updated): ?>
    <div  class="chama-alert chama-alert-success" id="chama-card-updated" role="alert">Your payment method has been updated</div>
<?php else: ?>
    <form class="chama-form chama-payment-form">
<div  id="chama-payment-element">
              <!-- A Stripe card Element will be inserted here. -->
            </div>


            <?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_currency" name="chama_currency" value="<?php echo esc_attr(CHAMA_CURRENCY); ?>" />
            <input name="chama_stripe_customer_id" id="chama_stripe_customer_id" type="hidden" value="<?php echo esc_attr($stripe_customer_id); ?>">
            <input name="chama_default_text" id="chama_default_text" type="hidden" value="<?php esc_attr_e('Update Payment Method' , 'chama');?>">
            <input name="chama_processing_text" id="chama_processing_text" type="hidden" value="<?php esc_attr_e('Processing' , 'chama');?>">
            <button id="chama-submit" class="chama-button chama-button-medium chama-pay-button">
            <i class="chama-button-spinner fa-solid fa-circle-notch fa-spin chama-hide"></i>
            <span id="chama-button-text"><?php esc_html_e('Update Payment Method' , 'chama');?></span>
          </button>
</form>
<?php endif;?>
<?php else: ?>
    You currently do not have any subscriptions. You can only update payment methods for subscriptions.
    <?php endif;?>
            </div>
</div>



