<?php
/**
 * Includes: Utilities
 */
if (! defined('ABSPATH')) {
    die('Sorry, you cannot access this page.');
}
add_action('admin_print_styles', 'chama_load_admin_styles_and_scripts');
/* Enqueue admin tyles and scripts*/
function chama_load_admin_styles_and_scripts()
{
    wp_register_style('chama-admin-css', CHAMA_ASSETS_URL . 'css/admin.css', [], CHAMA_VERSION, 'all');
    wp_enqueue_style('chama-admin-css');
    wp_enqueue_script('chama-admin-script', CHAMA_ASSETS_URL . 'js/admin.js', ['jquery'], CHAMA_VERSION, true);
    wp_enqueue_script('chama-admin-script');
    //color picker
    wp_enqueue_style('wp-color-picker');
    wp_enqueue_script('wp-color-picker');
    //media
    wp_enqueue_media();
}
function chama_synchronize_subscription_renewals_ajax()
{
    if (! isset($_POST['chama_nonce']) || ! wp_verify_nonce(sanitize_key($_POST['chama_nonce']), 'chama_sync_subscription_renewals_nonce')) {
        return;
    }
    if (isset($_POST["id"]) && isset($_POST["stripe_subscription_id"])) {
        $subscription_id        = sanitize_text_field(wp_unslash($_POST["id"]));
        $stripe_subscription_id = sanitize_text_field(wp_unslash($_POST["stripe_subscription_id"]));
        $transactions_link      = $subscriptions_link      = admin_url('edit.php?post_type=chama_subscription');
        $transactions_link      = esc_url(add_query_arg(
            [
                'sid' => $stripe_subscription_id,
            ],
            $transactions_link
        ));
        if ($stripe_subscription_id) {
            try {
                $mode       = chama_is_live_mode() ? 'live' : 'test';
                $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
                    );
                    $invoices = $stripe->invoices->all([
                        'limit'        => 12,
                        'subscription' => $stripe_subscription_id,
                    ]);
                    $payment_date = $renewal_date = $stripe_current_period_start = $stripe_current_period_end = '';
                    if ($invoices) {
                        foreach ($invoices->autoPagingIterator() as $invoice) {
                            if ($invoice->billing_reason == 'subscription_cycle') {
                                $stripe_payment_intent_id = $invoice->payment_intent;

                                /*=============================================CHECK IF IT IS ALREADY IN DATABASE=============================================*/
                                $transaction_in_db = false;
                                $payment_args      = [
                                    'meta_key'       => 'chama_stripe_payment_intent_id', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
                                    'meta_value'     => $invoice->payment_intent,         // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
                                    'post_status'    => 'any',
                                    'post_type'      => 'chama_subscription',
                                    'posts_per_page' => 1,
                                ];
                                $payment           = get_posts($payment_args);
                                $transaction_in_db = $payment && $payment[0]->ID;

                                /*=============================================PROCEED IF NOT IN DATABASE=============================================*/
                                if (! $transaction_in_db) {
                                    $stripe_billing_reason  = $invoice->billing_reason;
                                    $total_amount_cents     = $invoice->amount_paid;
                                    $stripe_subscription_id = $invoice->subscription;
                                    $tier_id                = $invoice->subscription_details->metadata->tier_id;
                                    $customer_email         = $invoice->customer_email;
                                    $stripe_customer_id     = $invoice->customer;
                                    $currency               = $invoice->currency;
                                    $description            = $invoice->subscription_details->metadata->description;
                                    $total_amount_formatted = '0.00';
                                    $total_amount           = 0;
                                    $receipt_id             = 0;
                                    $user_id                = 0;
                                    $user                   = null;

                                    if ($total_amount_cents) {
                                        $currency_minimum       = chama_get_currency_minimum($currency);
                                        $total_amount           = $total_amount_cents / $currency_minimum;
                                        $total_amount_formatted = number_format(floatval($total_amount), 2);
                                    }

                                    if ($invoice->period_start) {
                                        $payment_date = gmdate("Y-m-d H:i:s", $invoice->period_start);
                                    }
                                    if ($invoice->period_end) {
                                        $renewal_date = gmdate("F, j, Y", $invoice->period_end);
                                    }
                                    /*=============================================GET STRIPE CUSTOMER=============================================*/
                                    $stripe_customer = $stripe->customers->retrieve($stripe_customer_id, []);
                                    if ($stripe_customer && $stripe_customer->metadata->user_id) {
                                        $user_id = $stripe_customer->metadata->user_id;
                                    }
                                    /*=============================================ADD TO DATABASE=============================================*/
                                    $cpt_args = [
                                        'post_type'   => 'chama_subscription',
                                        'post_status' => 'publish',
                                    ];
                                    $receipt_id = wp_insert_post($cpt_args);
                                    if ($receipt_id) {
                                        if ($customer_email) {
                                            $user = null;
                                            if ($user_id) {
                                                $user = get_user_by('id', $user_id);
                                            } else {
                                                $user = get_user_by('email', $customer_email);
                                            }

                                            if ($user) {
                                                $user_id = $user->ID;
                                                update_post_meta($receipt_id, 'chama_user_id', $user_id);
                                                update_post_meta($receipt_id, 'chama_email', $customer_email);
                                                if ($user->first_name && $user->last_name) {
                                                    update_post_meta($receipt_id, 'chama_full_name', $user->first_name . ' ' . $user->last_name);
                                                }
                                            }

                                        }
                                        if ($stripe_customer_id) {
                                            update_post_meta($receipt_id, 'chama_stripe_customer_id', sanitize_text_field($stripe_customer_id));
                                        }
                                        if ($description) {
                                            update_post_meta($receipt_id, 'chama_subscription_description', sanitize_text_field($description));
                                        }
                                        if ($tier_id) {
                                            update_post_meta($receipt_id, 'chama_subscription_item_id', sanitize_text_field($tier_id));
                                        }

                                        update_post_meta($receipt_id, 'chama_payment_status', 'complete');
                                        if ($total_amount_cents) {
                                            update_post_meta($receipt_id, 'chama_subscription_currency', sanitize_text_field($currency));
                                            update_post_meta($receipt_id, 'chama_subscription_total_amount', sanitize_text_field($total_amount_formatted));

                                        }

                                        update_post_meta($receipt_id, 'chama_subscription_date_time', $payment_date);
                                        update_post_meta($receipt_id, 'chama_is_test_subscription', ! chama_is_live_mode());
                                        update_post_meta($receipt_id, 'chama_stripe_payment_intent_id', $stripe_payment_intent_id);
                                        if ($stripe_subscription_id) {
                                            update_post_meta($receipt_id, 'chama_subscription_status', 'active');
                                            update_post_meta($receipt_id, 'chama_subscription_event', 'renewal');
                                            update_post_meta($receipt_id, 'chama_stripe_subscription_id', $stripe_subscription_id);
                                        }
                                    }
                                    /*=============================================UPDATE PERIODS=============================================*/

                                    if ($renewal_date) {
                                        update_post_meta($receipt_id, 'chama_subscription_renewal_date', $renewal_date);
                                    }
                                    /*=============================================COMPLETED DATA ENTRY============================================*/
                                }

                            }

                        }
                        //loop completed update subscription
                        $subscription = $stripe->subscriptions->retrieve(
                            $stripe_subscription_id, []
                        );
                        if ($subscription && $subscription->status === 'active') {
                            $latest_invoice_id  = $subscription->latest_invoice;
                            $latest_invoice     = $stripe->invoices->retrieve($latest_invoice_id, []);
                            $total_amount_cents = $latest_invoice->amount_paid;
                            if ($total_amount_cents) {
                                $currency_minimum       = chama_get_currency_minimum($currency);
                                $total_amount           = $total_amount_cents / $currency_minimum;
                                $total_amount_formatted = number_format(floatval($total_amount), 2);
                                update_user_meta($user_id, 'chama_subscription_level', $total_amount_formatted);
                            }

                            update_user_meta($user_id, 'chama_subscription_status', 'active');

                            if ($subscription->current_period_start) {
                                $stripe_current_period_start = gmdate("F, j, Y", $subscription->current_period_start);
                                update_user_meta($user_id, 'chama_subscription_current_period_start', $stripe_current_period_start);
                            }
                            if ($subscription->current_period_end) {
                                $stripe_current_period_end = gmdate("F, j, Y", $subscription->current_period_end);
                                update_user_meta($user_id, 'chama_subscription_current_period_end', $stripe_current_period_end);
                                update_post_meta($subscription_id, 'chama_subscription_renewal_date', $stripe_current_period_end);
                            }

                        }
                        echo '<strong>Completed synchronization of transactions! <a href="' . esc_attr($transactions_link) . '">Click here</a> to view all related transactions.</strong>';
                    } else {
                        echo 'No invoices found!';
                    }
                }

            } catch (Exception $e) {
                die(esc_html($e->getMessage()));
            }
        }
    }

    die('');
}
add_action('wp_ajax_chama_synchronize_subscription_renewals', 'chama_synchronize_subscription_renewals_ajax');

function chama_cancel_subscription_ajax()
{
    if (! isset($_POST['chama_nonce']) || ! wp_verify_nonce(sanitize_key($_POST['chama_nonce']), 'chama_cancel_subscription_nonce')) {
        return;
    }
    if (isset($_POST["id"]) && isset($_POST["stripe_subscription_id"])) {
        $subscription_id        = sanitize_textarea_field(wp_unslash($_POST["id"]));
        $stripe_subscription_id = sanitize_textarea_field(wp_unslash($_POST["stripe_subscription_id"]));
        /*=============================================CANCEL SUBSCRIPTION=============================================*/
        if ($stripe_subscription_id) {
            try {
                $mode       = chama_is_live_mode() ? 'live' : 'test';
                $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
                    );
                    $subscription = $stripe->subscriptions->cancel($stripe_subscription_id, []);
                    chama_update_subscription_transactions($stripe_subscription_id, 'canceled');
                    echo '<strong>Subscription has been canceled</strong>';
                }

            } catch (Exception $e) {
                //die(esc_html($e->getMessage()));
                echo '<strong>Error occured while canceling subscription: </strong>' . esc_html($e->getMessage());
            }
        }

    }

    die('');
}
add_action('wp_ajax_chama_cancel_subscription', 'chama_cancel_subscription_ajax');
