<?php
if (!defined('ABSPATH')) exit();
if (class_exists('Ulp_Stripe')) return;
if (!interface_exists('Ulp_Payment_Service_Interface')) require_once ULP_PATH . 'classes/Payment_Services/Ulp_Payment_Service_Interface.php';
class Ulp_Stripe implements Ulp_Payment_Service_Interface{
    private $_metas = array();
    private $_transaction_details = array();
    private $_payment_data = array();
    private $_error = '';
    private $_charge_made = FALSE;
    public function __construct(){
        $this->_metas = DbUlp::getOptionMetaGroup('stripe');
    }
    public function setTransactionDetails($transaction_details=array()){
        $this->_transaction_details = $transaction_details;
        return $this;
    }
    public function set_payment_data($input_data=array()){
        $this->_payment_data = $input_data;
        if (empty($this->_payment_data['card_name'])){
            $this->_error = __('No name provided', 'ulp');
        }
        if (empty($this->_payment_data['card_num'])){
            $this->_error = __('No card number provided', 'ulp');
        }
        if (empty($this->_payment_data['card_exp_month'])){
            $this->_error = __('No card expire month provided', 'ulp');
        }
        if (empty($this->_payment_data['card_exp_year'])){
            $this->_error = __('No card expire year provided', 'ulp');
        }
        if (empty($this->_payment_data['cvc'])){
            $this->_error = __('No card cvc provided', 'ulp');
        }
        add_filter('the_content', array($this, 'final_message'), 999, 1);
    }
    public function get_payment_error(){
        return $this->_error;
    }
    public function pay($input_data=array()){
        require_once ULP_PATH . 'classes/services/Stripe/init.php';
        \Stripe\Stripe::setApiKey($this->_metas['ulp_stripe_secret_key']);
        $token_data = \Stripe\Token::create(
            array(
                  "card" => array(
                                    "name" => $this->_payment_data['card_name'],
                                    "number" => $this->_payment_data['card_num'],
                                    "exp_month" => $this->_payment_data['card_exp_month'],
                                    "exp_year" => $this->_payment_data['card_exp_year'],
                                    "cvc" => $this->_payment_data['cvc']
                  )
            )
        );
        $this->_charge_made = \Stripe\Charge::create(array(
                                            "amount" => $this->_transaction_details['amount'] * 100,
                                            "currency" => $this->_transaction_details['currency'],
                                            "card" => $token_data['id'],
                                            "description" => json_encode([
                                                'order_id' => $this->_transaction_details['order_id'],
                                                'uid' => $this->_transaction_details['uid'],
                                                'course_id' => $this->_transaction_details['course_id'],
                                            ]),
        ));
        return $this->_charge_made;
    }
    public function generate_payment_form(){
      $view = new ViewUlp();
      $view->setTemplate(ULP_PATH . 'views/templates/stripe_payment_form.php');
      $view->setContentData(array());
      return $view->getOutput();
    }
    public function final_message($content=''){
        $view = new ViewUlp();
        $view->setTemplate(ULP_PATH . 'views/templates/stripe_payment_final_message.php');
        $view->setContentData(array('error' => $this->_error, 'charge_made' => $this->_charge_made));
        return $content . $view->getOutput();
    }
    public function ipn(){
        require_once ULP_PATH . 'classes/services/Stripe/init.php';
        ini_set('display_errors','on');
        if (empty($this->_metas['ulp_stripe_secret_key'])){
            die;
        }
        \Stripe\Stripe::setApiKey($this->_metas['ulp_stripe_secret_key']);
        $body = @file_get_contents('php://input');
        $event_arr = json_decode($body, TRUE);
        $event_arr['payment_type'] = 'stripe';//set payment type
        if(isset($event_arr['id'])){
            $event = \Stripe\Event::retrieve($event_arr['id']);
        } else {
            echo '============= Indeed Learning Pro - STRIPE WEBHOOK ============= ';
            echo '<br/><br/>No Event sent. Come later';
            die();
        }
        if ($event && isset($event->data->object->id)){
            if (isset($event_arr['data']['object']['description'])){
                $transaction_custom_data = stripslashes($event_arr['data']['object']['description']);
                $transaction_custom_data = json_decode($event_arr['data']['object']['description'], true);
            }
            $order_id = isset($transaction_custom_data['order_id']) ? $transaction_custom_data['order_id'] : 0;
            if (empty($order_id)) {
                exit();
            }
            $UlpOrder = new UlpOrder();
            $unique = $UlpOrder->getUniqueByOrderId($order_id);
            switch ($event->type){
                case 'charge.succeeded':
                      /// PAYMENT MADE
                      $UlpOrder->modify_status($unique, 'ulp_complete');
                      $UlpOrder->save_service_transaction_details($order_id, serialize($event_arr));
                  break;
                case 'customer.subscription.created':
                  if ($event->data->object->status=="trialing"){
                      /// TRIAL
                  }
                  break;
                case 'invoiceitem.deleted':
                  $UlpOrder->modify_status($unique, 'ulp_fail');
                  $UlpOrder->save_service_transaction_details($order_id, serialize($event_arr));
                  break;
            }
        }
        exit();
    }
}
