<?php
if (!defined('ABSPATH'))
    exit; // Exit if accessed directly
if (isset($_POST['payment_page_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['payment_page_nonce'])), 'payment_page_action')) {
    $billing_id = sanitize_key($_GET['billing_id']);
    $invoice_id = sanitize_key($_GET['invoice_id']);
} else {
    $billing_id = sanitize_key($_GET['billing_id']);
    $invoice_id = sanitize_key($_GET['invoice_id']);
}
$user_id_wp = get_current_user_id();
$invoice_details = dspp_get_invoice_details($invoice_id);
$decoded_details = json_decode($invoice_details[0]['invoice_items'], true);
$cart_data = json_decode($invoice_details[0]['invoice_items'], true);
$cart_total = 0;
foreach ($cart_data as $item) {
    if (isset($item['price'])) {
        $cart_total += $item['price'] * $item['quantity'];
    }
}
if (isset($cart_data['coupon_code'])) {
    $coupon_value = $cart_data['coupon_discount_type'] == 'fixed_discount' ? $cart_data['coupon_value'] : (($cart_data['coupon_value'] / 100) * $cart_total);
    $cart_total = $cart_total - $coupon_value;
}
?>
<div class="row">
    <div class="col-sm-6">
        <form action="<?php echo esc_url(site_url("/bits-payment-processor/")) ?>" method="post" class="formbuilder-form" id="payment-form">
            <?php wp_nonce_field('payment_processor_action', 'payment_processor_nonce'); ?>
            <input type="hidden" name="invoice_id" value="<?php echo esc_attr($invoice_id); ?>" />
            <input type="hidden" id="cart_total" name="cart_total" value="<?php echo esc_attr($cart_total); ?>"/>
            <input type="hidden" id="billing_id" name="billing_id" value="<?php echo esc_attr($billing_id); ?>"/>
            <div class="form-group form-group-lg" data-field="">
                <h2><a href="<?php echo esc_url(site_url("/bits-checkout/")) ?>"><i class="fa fa-arrow-left" aria-hidden="true"></i></a> Payment method</h2>
                <div class="list-group payment-methods">
                    <?php
                    $details_stripe = array_shift(dspp_check_payment_method_enabled("Strip"));
                    $settings = $details_stripe->methode_details;
                    $decoded = json_decode($settings);
                    $stripe_publishable_key = $decoded->client_or_strip;
                    $enabled_stripe = (isset($details_stripe->enable) && $details_stripe->enable == "true") ? true : false;
                    if ($enabled_stripe) {
                        ?>
                        <div class="list-group-item">
                            <div class="custom-control custom-radio">
                                <input type="radio" name="processor" class="custom-control-input" id="stripe-method-card" value="stripe_card" <?php echo ($enabled_stripe) ? 'checked="checked"' : '' ?> />
                                <label for="stripe-method-card" class="custom-control-label d-flex align-items-center justify-content-between">
                                    <div class="flex-fill stripe-method-card-lable">
                                        <?php esc_html_e('Pay with Card', 'digital-service-provider-crm'); ?>
                                    </div>
                                    <div class="payment-icons">
                                        <img src="https://img.icons8.com/color/36/000000/visa.png" alt="Visa" />
                                        <img src="https://img.icons8.com/color/36/000000/mastercard-logo.png" alt="MasterCard" />
                                        <img src="https://img.icons8.com/color/36/000000/amex.png" alt="Amex" />
                                    </div>
                                </label>
                                <div id="card-element"><!-- Stripe will inject the card field here --></div>
                                <input type="hidden" id="stripeToken" name="stripeToken" />
                            </div>
                        </div>
                        <?php
                    }
                    $details_paypal = array_shift(dspp_check_payment_method_enabled("Paypal"));
                    $paypal_settings = $details_paypal->methode_details;
                    $paypal_decoded = json_decode($paypal_settings);
                    $enabled_paypal = (isset($details_paypal->enable) && $details_paypal->enable == "true") ? true : false;
                    if ($enabled_paypal) {
                        ?>
                        <div class="list-group-item">
                            <div class="custom-control custom-radio">
                                <input type="radio" name="processor" class="custom-control-input" id="paypal" value="paypal" <?php echo (!$enabled_stripe && $enabled_paypal) ? 'checked="checked"' : '' ?>/>
                                <label for="paypal" class="custom-control-label d-flex align-items-center">
                                    <div class="flex-fill"><?php esc_html_e('Pay with PayPal', 'digital-service-provider-crm'); ?></div>
                                </label>
                                <input type="hidden" id="paypal_order_id" name="paypal_order_id" />
                            </div>
                        </div>
                        <?php
                    }
                    $details_bank = array_shift(dspp_check_payment_method_enabled("Bank"));
//                    print_r($details_bank);
                    $enabled_bank = (isset($details_bank->enable) && $details_bank->enable == "true") ? true : false;
                    if ($enabled_bank) {
                        ?>
                        <div class="list-group-item">
                            <div class="custom-control custom-radio">
                                <input type="radio" name="processor" class="custom-control-input" id="manual-payment" value="manual_payment" <?php echo (!$enabled_stripe && !$enabled_paypal) ? 'checked="checked"' : '' ?>/>
                                <label for="manual-payment" class="custom-control-label d-flex align-items-center">
                                    <div class="flex-fill"><?php esc_html_e('Bank transfer', 'digital-service-provider-crm'); ?></div>
                                </label>
                            </div>
                        </div>
                    <?php } ?>
                </div>
            </div>
            <?php if ($enabled_stripe) { ?>
                <button id="stripe_button" style="width: 100%;" class="btn btn-primary btn-block btn-lg stripe_button">
                    <span class="spinner-border spinner-border-sm me-2 d-none" role="status" aria-hidden="true" id="stripeSpinner"></span>
                    <?php esc_html_e('Complete Purchase', 'digital-service-provider-crm'); ?>
                </button>
                <div id="payment-message" class="hidden"></div>
                <script src="https://js.stripe.com/v3/"></script>
                <script>
                    const stripe = Stripe("<?php echo esc_attr($stripe_publishable_key); ?>");
                    let elements;
                    document.addEventListener("DOMContentLoaded", function () {
                        // Show spinner and disable button
                        const submitButton = document.getElementById("stripe_button");
                        const spinner = document.getElementById("stripeSpinner");
                        submitButton.disabled = true;
                        spinner.classList.remove("d-none");
                        $.ajax({
                            url: dspp_nonces.ajax_url,
                            type: "POST",
                            dataType: "json",
                            data: {
                                action: "create_payment_intent",
                                cart_total: "<?php echo $cart_total; ?>"
                            },
                            success: function (response) {
                                // Hide spinner and re-enable button
                                spinner.classList.add("d-none");
                                submitButton.disabled = false;
                                if (response.success && response.data.clientSecret) {
                                    const clientSecret = response.data.clientSecret;
                                    const stripeToken = document.getElementById("stripeToken");
                                    stripeToken.value = clientSecret;
                                    elements = stripe.elements();
                                    const cardElement = elements.create("card");
                                    cardElement.mount("#card-element");
                                    const form = document.getElementById("payment-form");
                                    form.addEventListener("submit", async (event) => {
                                        submitButton.disabled = true;
                                        spinner.classList.remove("d-none");
                                        event.preventDefault();
                                        const {error, paymentIntent} = await stripe.confirmCardPayment(clientSecret, {
                                            payment_method: {
                                                card: cardElement,
                                            }
                                        });
                                        const messageEl = document.getElementById("payment-message");
                                        if (error) {
                                            spinner.classList.add("d-none");
                                            submitButton.disabled = false;
                                            messageEl.textContent = error.message;
                                            messageEl.classList.remove("hidden");
                                        } else if (paymentIntent.status === "succeeded") {
                                            spinner.classList.add("d-none");
                                            submitButton.disabled = false;
                                            messageEl.textContent = "Payment successful!";
                                            messageEl.classList.remove("hidden");
                                        }
                                    });
                                } else {
                                    spinner.classList.add("d-none");
                                    submitButton.disabled = false;
                                    console.error("Stripe init failed:", response);
                                }
                            },
                            error: function (xhr, status, error) {
                                spinner.classList.add("d-none");
                                submitButton.disabled = true;
                                console.error("AJAX Error:", error);
                            }
                        });
                    });
                </script>
            <?php } ?>


            <!--i have working code below-->


            <!--                        <div id="checkout" class="stripe_button">
                                    </div>

                        <script src="https://js.stripe.com/basil/stripe.js"></script>
                        <script>
                            const stripe = Stripe("<?php echo esc_attr($stripe_publishable_key) ?>");
                            initialize();
                            function initialize() {
                                $.ajax({
                                    url: dspp_nonces.ajax_url,
                                    type: "POST",
                                    dataType: "json",
                                    data: {
                                        action: "create_payment_intent"
                                    },
                                    success: function (response) {
                                        if (response.clientSecret) {
                                            stripe.initEmbeddedCheckout({
                                                fetchClientSecret: () => Promise.resolve(response.clientSecret)
                                            }).then(function (checkout) {
                                                checkout.mount('#checkout');
                                            });
                                        } else {
                                            console.error("Stripe error:", response);
                                            alert("Failed to initialize Stripe checkout.");
                                        }
                                    },
                                    error: function (xhr, status, error) {
                                        console.error("AJAX error:", error);
                                        alert("AJAX error occurred while initializing Stripe.");
                                    }
                                });
                            }
                        </script>-->

            <!--            <div id="" class="stripe_button"></div>
                        <script src="https://js.stripe.com/v3/"></script>
                        <script>
                            const stripe = Stripe("<?php // echo esc_attr($stripe_publishable_key)                   ?>");
                            stripe.elements({
                                mode: "payment", // <-- change to payment and it will work
                                amount: <?php // echo esc_attr($cart_total * 100)                   ?>,
                                currency: "usd"
                            }).create('payment').mount('.stripe_button');
                        </script>-->
            <!--            <label for="stripe-method-card" class="custom-control-label d-block stripe_button" <?php echo ($enabled_stripe) ? '' : 'style="display:none !important;"' ?>>
                            <script
                                src="https://checkout.stripe.com/checkout.js" class="stripe-button"
                                data-key="<?php // echo esc_attr($stripe_publishable_key)                               ?>"
                                data-amount="<?php // echo esc_attr($cart_total * 100)                               ?>"
                                data-name="Service Provider Pro CRM"
                                data-description="Service Provider Pro CRM"
                                data-currency="usd"
                                data-email="info@bestitsol.com"
                                data-redirectURL = "test.php">
                            </script>
                        </label>-->
            <div class="panel paypal_button" <?php echo ($enabled_paypal) ? '' : 'style="display:none !important;"' ?> <?php echo ($enabled_stripe) ? 'style="display:none !important;"' : '' ?>>
                <!--<div class="overlay hidden"><div class="overlay-content"><img src="css/loading.gif" alt="Processing..."/></div></div>-->
                <div class="panel-body">
                    <div id="paymentResponse" class="hidden"></div>
                    <div id="paypal-button-container"></div>
                </div>
            </div>
            <button type="submit" class="btn btn-primary btn-block btn-lg submit_cart" <?php echo ($enabled_bank && !$enabled_stripe && !$enabled_paypal) ? '' : 'style="display:none !important;"' ?>>
                <span class="spinner-border spinner-border-sm me-2 d-none" id="bankSpinner" role="status" aria-hidden="true"></span>
                <?php esc_html_e('Complete Purchase', 'digital-service-provider-crm'); ?>
            </button>
        </form>
        <?php if (!$enabled_stripe && !$enabled_paypal && !$enabled_bank) {
            ?>
            <div class="no-payment-method alert alert-danger"><?php esc_html_e('No payment method found!', 'digital-service-provider-crm'); ?></div>
            <?php
        }
        ?>
    </div>
    <div class="col-sm-6">
        <aside class="mr-auto checkout-right">
            <div class="sticky">
                <div class="invoice-items" id="preview">
                    <h2 class="mb-4"><?php esc_html_e('Summary', 'digital-service-provider-crm'); ?></h2>
                    <div class="cart-contents">
                        <?php
                        foreach ($cart_data as $cart_items) {
                            if (!is_array($cart_items)) {
                                continue;
                            }
                            ?>
                            <div class="mb-4 d-flex justify-content-between">
                                <div>
                                    <div class="text-500"><?php echo esc_html($cart_items['site']); ?></div>
                                    <div>
                                        <span class="mr-1 text-muted"><?php esc_html_e('Qty', 'digital-service-provider-crm'); ?></span> <?php echo esc_html($cart_items['quantity']); ?>
                                    </div>
                                </div>
                                <div class="text-right text-500">
                                    $<?php echo esc_html($cart_items['price']); ?>
                                </div>
                            </div>

                        <?php } ?>
                        <hr />
                        <?php if (isset($cart_data['coupon_code'])) {
                            ?>
                            <div class="mb-4 d-flex justify-content-between">
                                <div>
                                    <div class="text-500">Discount (<?php echo esc_html($cart_data['coupon_code']) ?>)</div>
                                    <div class="text-muted">USD</div>
                                </div>
                                <div class="text-right">
                                    <h2 class="margin-0">
                                        $<?php echo esc_html(($coupon_value == 0 ) ? 0 : $coupon_value); ?>
                                    </h2>
                                </div>
                            </div>
                        <?php }
                        ?>
                        <!-- Show total and payment terms -->
                        <div class="mb-4 d-flex justify-content-between">
                            <div>
                                <div class="text-500">Total</div>
                                <div class="text-muted">USD</div>
                            </div>
                            <div class="text-right">
                                <h2 class="margin-0">
                                    $<?php echo esc_html($cart_total); ?>
                                </h2>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </aside>
    </div>
</div>
<?php
//foreach ($cart_data as $cart_items) {
//if (isset($cart_items['site'])) {
//    echo $cart_items['site'];
//}
//
//}
//exit;
?>
<script src="https://www.paypal.com/sdk/js?client-id=<?php echo $paypal_decoded->client_or_strip ?>&currency=USD&disable-funding=credit,card" data-namespace="paypal_sdk"></script>
<script>
                    $ = jQuery;
                    $('.custom-control-input').on('change', function () {
                        if ($(this).is(':checked')) {
                            if ($(this).val() === 'stripe_card') {
                                $('.stripe_button').show();
                                $('.stripe-button-el').show();
                                $('.paypal_button').hide();
                                $('.submit_cart').hide();
                            } else if ($(this).val() === 'manual_payment') {
                                $('.stripe_button').hide();
                                $('.stripe-button-el').hide();
                                $('.paypal_button').hide();
                                $('.submit_cart').show();
                            } else if ($(this).val() === 'paypal') {
                                $('.stripe_button').hide();
                                $('.paypal_button').show();
                                $('.stripe-button-el').hide();
                                $('.submit_cart').hide();
                            }
                        }
                    });
                    $('.submit_cart').on('click', function (e) {
                        e.preventDefault();
                        $("#payment-form").submit();
                    });
                    paypal_sdk.Buttons({
                        createOrder: (data, actions) => {
                            return actions.order.create({
                                "purchase_units": [{
                                        "custom_id": "<?php echo $cart_total ?>",
                                        "description": "<?php echo $cart_total ?>",
                                        "amount": {
                                            "currency_code": "USD",
                                            "value": <?php echo $cart_total ?>,
                                            "breakdown": {
                                                "item_total": {
                                                    "currency_code": "USD",
                                                    "value": <?php echo $cart_total ?>,
                                                }
                                            }
                                        },
                                        "items": [
<?php
foreach ($cart_data as $cart_items) {
    if (isset($cart_items['site'])) {
        ?>
                                                    {
                                                        "name": "<?php echo $cart_items['site']; ?>",
                                                        "description": "<?php echo $cart_items['site']; ?>",
                                                        "unit_amount": {
                                                            "currency_code": "USD",
                                                            "value": <?php echo $cart_items['price']; ?>
                                                        },
                                                        "quantity": "1",
                                                        "category": "DIGITAL_GOODS"
                                                    },
        <?php
    }
}
?>
                                        ]
                                    }]
                            });
                        }, onApprove: (data, actions) => {
                            return actions.order.capture().then(function (orderData) {
                                var postData = {paypal_order_check: 1, order_id: orderData.id};
                                if (orderData.status === 'COMPLETED') {
                                    $("#paypal_order_id").val(orderData.id);
                                    $('#payment-form').submit();
                                } else {
                                    $('#payment-form').submit();
                                }
                            });
                        }
                    }).render('#paypal-button-container');
</script>