<?php 
/**
 * class @var ST_WC_Order_Integration
 * working @var 'for handling WooCommerce order integration with custom licensing'.
 */
class ST_WC_Order_Integration {
    public $version = '1.0.0';
    protected static $_instance = null;

    public static function instance() {
        if (is_null(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function __construct() {
        $this->hooks();
    }

    public function hooks() {
        add_action('woocommerce_order_status_completed', [$this, 'on_order_payment_confirmed'], 10, 1);
        add_action('woocommerce_order_status_processing', [$this, 'on_order_payment_confirmed'], 10, 1);

    }

    public function on_order_payment_confirmed($order_id) {
        if (!function_exists('wc_get_order')) return;
        if (!class_exists('ST_License_OAuth')) return;

        $order = wc_get_order($order_id);
        if (!$order) return;

        $user_id = $order->get_user_id();
        
        
        if (!$user_id) return;
        # get user details
        $user_details = (object) $this->get_user_details($user_id, $order);
        
        
        
        # just alert flag hook
        update_user_meta($user_id, '_spacetree_licence_order-'.$order_id, 'started');

        # previous order hook
        $previous_status = get_user_meta($user_id, '_spacetree_licence_order-status-'.$order_id, true);
        if ($previous_status === 'completed') return;

        foreach ($order->get_items() as $item) {
            $product_id = $item->get_product_id();
            $product = wc_get_product($product_id);

            if ( $product ) {

                $license_type = get_post_meta($product_id, '_spacetree-license-type', true);
                $license_items = get_post_meta($product_id, '_spacetree-license-items', true);
                $license_expires_in = get_post_meta($product_id, '_spacetree-license-expires-in', true);

                if ($license_type === "proqyz-wp" || $license_type === "ieltslms-wp") {
                    $start_date = time();
                    $expiry_date = $start_date + ($license_expires_in * 24 * 60 * 60);

                    $order_basic_details = [
                        "order_id" => $order_id,
                        "product_id" => $product_id,
                        "license_expires_in" => $license_expires_in,
                        "license_per_items" => $license_items,
                        "license_type" => $license_type,
                        "license_starts_in" => $start_date,
                        "license_expire_on" => $expiry_date,
                    ];

                    $product_details = (object) [
                        "id"                => $product_id,
                        "title"             => $product->get_name(),
                        "tags"              => wp_get_post_terms($product_id, 'product_tag', ['fields' => 'names']),
                        'image_url'         => get_the_post_thumbnail_url($product_id, 'full'),
                        'sale_price'        => $product->get_sale_price(),
                        'regular_price'     => $product->get_regular_price(),
                        'price_currency'    => html_entity_decode(get_woocommerce_currency_symbol()),
                        'license'           => (object) [
                            "expires_in"        => $license_expires_in,
                            "license_type"      => $license_type,
                            "license_domains"   => $license_items,
                        ]
                    ];

                    
                    // Remote API request
                    $remote_response = (object) ST_License_OAuth::rest_post_request("/remote/customer/order/completed", (object) [
                        "product_details"   => (object) $product_details,
                        "order_details"     => (object) $order_basic_details,
                        "user_details"      => $user_details,
                        "wp_user"           => (object) [
                            "user_email"            => $user_details->usermeta->email,
                            "user_id"               => $user_id,
                            "display_name"          => $user_details->display_name
                        ]
                    ]);

                    if ( isset($remote_response->success) ) {
                        $remote_success = (object) $remote_response->success;
                        update_user_meta($user_id, '_spacetree_licence_order-status-'.$order_id, 'completed');
                        update_user_meta($user_id, '_spacetree_licence_order-remote_id-'.$order_id, $remote_success->_id);
                        // Send custom email notification on success
                            
                    } else {
                        update_user_meta($user_id, '_spacetree_licence_order-status-'.$order_id, 'failed');
                        update_user_meta($user_id, '_spacetree_licence_order-failed-'.$order_id, $remote_response);
                    }
                    
                }
            }
        }
    }

    public function on_order_hold( $order_id ) {
        if (!function_exists('wc_get_order')) return;
        if (!class_exists('ST_License_OAuth')) return;

        $order = wc_get_order($order_id);
        if (!$order) return;

        $user_id = $order->get_user_id();
        if (!$user_id) return;
        # get user details
        $user_details = (object) $this->get_user_details($user_id, $order);

        # just alert flag hook
        update_user_meta($user_id, '_spacetree_licence_order-'.$order_id, 'processing-suspend'); // just status flag

        $previous_status = get_user_meta($user_id, '_spacetree_licence_order-status-'.$order_id, true);
        # if already suspended then do nothing and return back
        if ($previous_status === 'suspended') return;

        # if not then make suspend call to api
        foreach ($order->get_items() as $item) {
            $product_id = $item->get_product_id();
            $product = wc_get_product($product_id);

            if ( $product ) {

                $license_type = get_post_meta($product_id, '_spacetree-license-type', true);
                $license_items = get_post_meta($product_id, '_spacetree-license-items', true);
                $license_expires_in = get_post_meta($product_id, '_spacetree-license-expires-in', true);

                if ($license_type === "proqyz-wp" || $license_type === "ieltslms-wp") {
                    $start_date = time();
                    $expiry_date = $start_date + ($license_expires_in * 24 * 60 * 60);

                    $order_basic_details = [
                        "order_id" => $order_id,
                        "product_id" => $product_id,
                        "license_expires_in" => $license_expires_in,
                        "license_per_items" => $license_items,
                        "license_type" => $license_type,
                        "license_starts_in" => $start_date,
                        "license_expire_on" => $expiry_date,
                    ];

                    $product_details = (object) [
                        "id"                => $product_id,
                        "title"             => $product->get_name(),
                        "tags"              => wp_get_post_terms($product_id, 'product_tag', ['fields' => 'names']),
                        'image_url'         => get_the_post_thumbnail_url($product_id, 'full'),
                        'sale_price'        => $product->get_sale_price(),
                        'regular_price'     => $product->get_regular_price(),
                        'price_currency'    => html_entity_decode(get_woocommerce_currency_symbol()),
                        'license'           => (object) [
                            "expires_in"        => $license_expires_in,
                            "license_type"      => $license_type,
                            "license_domains"   => $license_items,
                        ]
                    ];

                    
                    # Remote API request
                    $remote_response = (object) ST_License_OAuth::rest_post_request("/remote/customer/order/suspend", (object) [
                        "product_details"   => (object) $product_details,
                        "order_details"     => (object) $order_basic_details,
                        "user_details"      => $user_details
                    ]);

                    if ( isset($remote_response->success) ) {
                        $remote_success = (object) $remote_response->success;
                        update_user_meta($user_id, '_spacetree_licence_order-status-'.$order_id, 'suspend');
                    } else {
                        update_user_meta($user_id, '_spacetree_licence_order-failed-'.$order_id, $remote_response);
                    }

                }
            }
        }
        
    }

    public function get_user_details( $user_id = null, $order ) {
        if( !$user_id ) return;
        # get user details
        $user = get_userdata($user_id);
        // 1. Get the username
        $username = $user->user_login;
        // 2. Get the email
        $email = strtolower($user->user_email);
        $display_name = $user->display_name;
        // 3. Get billing details from the order
        $billing_address_line_1 = $order->get_billing_address_1();
        $billing_address_line_2 = $order->get_billing_address_2();
        $billing_city = $order->get_billing_city();
        $billing_state = $order->get_billing_state();
        $billing_country = $order->get_billing_country();
        $billing_country_code = $order->get_billing_country(); // Two-letter country code
        $billing_phone = $order->get_billing_phone();
        $billing_pincode = $order->get_billing_postcode(); // pincode

        // 4. Get the first and last name
        $first_name = $order->get_billing_first_name();
        $last_name = $order->get_billing_last_name();

        $address_object = (object) [
            "address_type"    => "billing-address-1",  
            "country"         => $billing_country_code,
            "state"           => $billing_state,
            "address_line_1"  => $billing_address_line_1,
            "address_line_2"  => $billing_address_line_2,  
            "zipcode"         => $billing_pincode
        ];
        

        return (object) [
            "display_name"  => $display_name,
            "usermeta"      =>  (object) [
                "email"         => $email,
                "emailVerified" => false,
                "phone"         => [],
                "profession"    => "",
                "first_name"    => $first_name,
                "last_name"     => $last_name,
                "mobile"        => (object) [
                    "cc"        => "",
                    "number"    => $billing_phone,
                    "verified"  => false,
                    "_uid"      => ""
                ]
            ],
            "address"       => $address_object,
            "billing"       => (array) [$address_object],
            "providers"     => (object) [
                "email"     => (array) [$email]
            ],
            "connections"   => [],
            "products"      => [],
            "status"        => "active",
            "_verified"     => true,
        ];
    
    }

}

return ST_WC_Order_Integration::instance();
