<?php

/**
 * @package: EGPS - Easy Sell for Google Photo
 * 
 * PayPal purchase option class
 */

 if(!defined('ABSPATH')){
    exit; // Exit if accessed directly
}

class EgpsPayPal{

    // ----- variables -----
    private static $pp_api_url = (EGPS_PP_SANDBOX == "on") ? "https://api-m.sandbox.paypal.com" : "https://api-m.paypal.com";
    private static $pp_email = "";
    // ----- /variables -----


    public static function egps_paypal_variables(){
        if(isset(get_option('egps_paypal_options')['paypal_client_id'])){
            define("EGPS_PP_CLIENT", get_option('egps_paypal_options')['paypal_client_id']);
        }else{
            define("EGPS_PP_CLIENT", "");
        }

        if(isset(get_option('egps_paypal_options')['paypal_client_secret'])){
            define("EGPS_PP_SECRET", get_option('egps_paypal_options')['paypal_client_secret']);
        }else{
            define("EGPS_PP_SECRET", "");
        }

        if(isset(get_option('egps_paypal_options')['paypal_access_token'])){
            define("EGPS_PP_ACCESS_TOKEN", get_option('egps_paypal_options')['paypal_access_token']);
        }else{
            define("EGPS_PP_ACCESS_TOKEN", "");
        }

        if(isset(get_option('egps_paypal_options')['paypal_expiration'])){
            define("EGPS_PP_EXPIRATION", get_option('egps_paypal_options')['paypal_expiration']);
        }else{
            define("EGPS_PP_EXPIRATION", "");
        }

        if(isset(get_option('egps_paypal_options')['paypal_sandbox'])){
            define('EGPS_PP_SANDBOX', get_option('egps_paypal_options')['paypal_sandbox']);

        }else{
            define('EGPS_PP_SANDBOX', "");
        }

    }


    public static function egps_get_paypal_token(){

        try{
            $basic_auth = base64_encode(EGPS_PP_CLIENT . ":" . EGPS_PP_SECRET);

            $args = array(
                'method' => 'POST',
                'timeout' => 60,
                'headers' => array('Accept' => 'application/json', 'Authorization' => "Basic " . $basic_auth),
                'body' => array('grant_type' => 'client_credentials')
            );
            $paypal_response = wp_remote_get(self::$pp_api_url . '/v1/oauth2/token', $args);

            $body = wp_remote_retrieve_body($paypal_response);
            $result = !empty($body) ? json_decode($body, true) : null;

            return $result;

        }catch (Error $error){
            Egps::egps_vardump($error);
        }
        return null;
    
    }

    public static function egps_save_pp_token($data = array()){

        if( !isset($data["error"]) ){
            $egps_auth = get_option('egps_paypal_options');

            if (!isset($egps_auth)) {
                $egps_auth = [];
            }
            $egps_auth['paypal_access_token'] = $data['access_token'];
            $egps_auth['token_type'] = $data['token_type'];
            $egps_auth['paypal_expiration'] = EgpsPayPal::egps_count_pp_token_expire_time($data['expires_in']);

            update_option('egps_paypal_options', $egps_auth);
        }
    }

    public static function egps_count_pp_token_expire_time($token_expires){
        $date = new DateTime();
        
        $date->getTimestamp();

        if($token_expires != null) {
            $date->add(new DateInterval('PT' . $token_expires . 'S')); // adds secs
        }
        return $date->getTimestamp();
    }

    public static function egps_check_pp_token(){
        $date = new DateTime();
        $timenow = $date->getTimestamp();

        $token_expires = EGPS_PP_EXPIRATION;

        ////******** SECS BERORE UPDATE TOKEN **********///
        if($token_expires != null && $token_expires != "") {
            if (($token_expires - $timenow) <= 100) {
                $new_token = EgpsPayPal::egps_get_paypal_token();

                if($new_token != null){
                    EgpsPayPal::egps_save_pp_token($new_token);
                }
            }
        }else{
            $new_token = EgpsPayPal::egps_get_paypal_token();

            if($new_token != null){
                EgpsPayPal::egps_save_pp_token($new_token);
            }
        }
        
    }

    public static function egps_save_order_to_db($email, $inv_id){

        $tn_orders = "egps_orders";
        $tn_invoices = "egps_invoices";
        $tn_cart = "egps_cart";
        $tn_customer_data = "egps_customers";
        $tn_photos = "egps_photos";
        $items = array();
        $return = null;
        $dboptions = get_option("egps_prices");
        
        try{
            //get cart items by email
            $cart_items = EgpsDatabase::egps_get_table_rows_where($tn_cart, "customer_email", $email);

            //get order data from PayPal by id
            $ord_details = self::egps_get_order_details($inv_id);

            if( !empty($ord_details)){
                $order["customer_name"] = $ord_details["payment_source"]["paypal"]["name"]["given_name"] . " " . $ord_details["payment_source"]["paypal"]["name"]["surname"];
                $order["customer_country"] = $ord_details["payment_source"]["paypal"]["address"]["country_code"];
            }else{
                $order["customer_name"] = "";
                $order["customer_country"] = "";
            }

            //save order data for email
            $order["customer_email"] = $email;
            $i = 0;

            $customer_all_orders = EgpsOrders::getCustomerAllOrders($email);

            foreach($cart_items as $ci){

                //if photo previously purchased update database else insert new data
                $photo_already = false;

                if( !empty($customer_all_orders) ){

                    foreach($customer_all_orders as $cau){
                        if($cau->order_items == $ci->cart_items){
                            $photo_already = true;
                            $dwldmax_original = $cau->dwld_max;
                        }
                    }

                }

                // set default value
                $order["order_exclusive"] = "";
                $order["purchase_currency"] = trim($dboptions["currencySetupCode"]);
                $order["purchase_price"] = $dboptions["regularPrice"];

                if($photo_already){

                    //sign exclusive photos
                    if($ci->text == "exclusive"){
                        $order["order_exclusive"] = "y";
                        $order["purchase_price"] = $dboptions["exclusivePrice"];
                        EgpsAlbums::egps_set_photo_exclusive($ci->cart_items);
                    }

                    $order["order_invoice_number"] = $inv_id;
                    $order["time"] = date('Y-m-d');
                    $order["dwld_max"] = $dwldmax_original + $dboptions["maxDownloadCount"];
                    $order["dwld_count"] = 0;

                    $where_array["customer_email"] = $email;
                    $where_array["order_items"] = $ci->cart_items;

                    EgpsDatabase::egps_update_db_table($tn_orders, $order, $where_array);

                }else{
                    //sign exclusive photos
                    if($ci->text == "exclusive"){
                        $order["order_exclusive"] = "y";
                        $order["purchase_price"] = $dboptions["exclusivePrice"];
                        EgpsAlbums::egps_set_photo_exclusive($ci->cart_items);
                    }

                    $order["order_items"] = $ci->cart_items;
                    $order["order_invoice_number"] = $inv_id;
                    $order["order_invoice_link"] = "";
                    $order["time"] = date('Y-m-d');
                    $order["dwld_max"] = $dboptions["maxDownloadCount"];
                    $order["dwld_count"] = 0;

                    EgpsDatabase::egps_insert_to_db($tn_orders, $order);
                }

                //increase egps_photos table photo purchase number
                EgpsDatabase::egps_inc_photo_purchase($ci->cart_items);
                
                //save invoice
                $inv_data['customer_email'] = $email;
                $inv_data['order_invoice_number'] = $inv_id;
                $inv_data['order_invoice_link'] = "";
                $inv_data['time'] = date('Y-m-d');
                $inv_data['order_invoice_price'] = "";
                EgpsDatabase::egps_insert_to_db($tn_invoices, $inv_data);

                $i++;

            }

            if($i == count($cart_items)){
                EgpsDatabase::egps_delete_record_multiple($tn_cart, "customer_email", $email);
                $return = "ok";
            }

            //send email for purchase
            $egps_email_opt = get_option('egps_email_order_options');

            $mailform = new EgpsEmailSend;
            $field_array = $mailform->egpsEmailGetFieldsOrder();
            $dataout = $mailform->egpsEmailFieldData($egps_email_opt, $field_array);

            $dataret = $mailform->egpsEmailRegister( array("email" => $email) );

            return $return;

        }catch(Exception $e){
            return json_encode($e);
        }

    }

    public static function egps_get_order_details($orderid){
        
        $api_url = self::$pp_api_url . '/v2/checkout/orders/'.$orderid;

        try{

            $paypal_response = wp_remote_get($api_url, array(
                    'timeout' => 60,
                    'headers' => array(
                        'Content-Type' => 'application/json', 
                        'Authorization' => "Bearer " . EGPS_PP_ACCESS_TOKEN, 
                    )
                )
            );

            $body = wp_remote_retrieve_body($paypal_response);
            $result = !empty($body) ? json_decode($body, true) : null;
            

            return $result;

        }catch (Error $error){
            Egps::egps_vardump($error);
        }
        return null;

    }

    public static function egps_get_invoice_details($orderid){

        try{

            $args = array(
                'method' => 'POST',
                'timeout' => 60,
                'headers' => array('Accept' => 'application/json', 'Authorization' => "Bearer " . EGPS_PP_ACCESS_TOKEN),
                'body' => array('grant_type' => 'client_credentials')
            );
            $paypal_response = wp_remote_get(self::$pp_api_url . '/v2/checkout/orders/'.$orderid, $args);

            $body = wp_remote_retrieve_body($paypal_response);
            $result = !empty($body) ? json_decode($body, true) : '';

            $return = json_decode($result, true);

            return $return;

        }catch (Error $error){
            Egps::egps_vardump($error);
        }
        return null;
        
    }

    public static function egps_save_pp_invoice($data = array()){}

    public static function egps_pp_save_order_to_db($atts = array()){}

}