<?php
    /**
     * ipn
     *
     * @package Wojo Framework
     * @author wojoscripts.com
     * @copyright 2023
     * @version 5.50: ipn.php, v1.00 7/18/2023 6:01 PM Gewa Exp $
     *
     */
    
    use Stripe\Customer;
    use Stripe\Exception\CardException;
    use Stripe\Stripe;
    
    const _WOJO = true;
    require_once '../../../init.php';
    
    if (!App::Auth()->is_User()) {
        exit;
    }
    
    ini_set('log_errors', true);
    ini_set('error_log', dirname(__file__) . '/ipn_errors.log');
    
    if (isset($_POST['processStripePayment'])) {
        $validate = Validator::run($_POST);
        $validate->set('payment_method', 'Invalid Payment Methods')->required()->string();
        $safe = $validate->safe();
        
        if (!$cart = Product::getCartContentIpn()) {
            Message::$msgs['cart'] = Language::$word->STR_ERR;
        }
        
        if (empty(Message::$msgs)) {
            require_once BASEPATH . '/gateways/stripe/vendor/autoload.php';
            $pp = Database::Go()->select(Admin::gTable, array('extra'))->where('name', 'ideal', '=')->first()->run();
            $core = App::Core();
            $auth = App::Auth();
            
            $totals = Product::getCartTotal();
            $amount = Utility::numberParse($totals->grand);
            $items = array();
            $cdkey = array();
            
            $txn_id = time();
            
            Stripe::setApiKey($pp->extra);
            try {
                //Charge client
                $client = Customer::create(array(
                    'payment_method' => $safe->payment_method,
                    'name' => $auth->name
                ));
                
                // insert payment record
                foreach ($cart as $k => $item) {
                    $key = Database::Go()->select(Product::cdTable, array('cdkey'))->where('product_id', $item->id, '=')->one()->run();
                    $data = array(
                        'user_id' => $auth->uid,
                        'product_id' => $item->id,
                        'txn_id' => $txn_id,
                        'tax' => Utility::numberParse($item->totaltax),
                        'amount' => Validator::sanitize($item->total, 'float'),
                        'total' => Validator::sanitize($item->totaltax + $item->total, 'float'),
                        'coupon' => $item->coupon,
                        'cdkey' => ($key) ? : '',
                        'pp' => $pp->displayname,
                        'ip' => Url::getIP(),
                        'file_date' => time(),
                        'currency' => $pp->extra2,
                        'status' => 1,
                    );
                    
                    $items[$k]['title'] = $item->title;
                    $items[$k]['qty'] = 1;
                    $items[$k]['price'] = $item->total;
                    $items[$k]['cdkey'] = $data['cdkey'];
                    $cdkey[] = $data['cdkey'];
                    
                    Database::Go()->insert(Product::xTable, $data)->run();
                    if ($key) {
                        Database::Go()->delete(Product::cdTable)->where('cdkey', $data['cdkey'], '=')->run();
                    }
                }
                
                // invoice table
                $xdata = array(
                    'invoice_id' => substr(time(), 5),
                    'transaction_id' => $txn_id,
                    'user_id' => $auth->uid,
                    'items' => json_encode($items),
                    'coupon' => $totals->discount,
                    'tax' => $totals->tax,
                    'subtotal' => $totals->subtotal,
                    'grand' => $amount,
                    'currency' => strtoupper($pp->extra2),
                );
                Database::Go()->insert(Product::ivTable, $xdata)->run();
                
                $jn['type'] = 'success';
                $jn['title'] = Language::$word->SUCCESS;
                $jn['message'] = Language::$word->STR_POK;
                print json_encode($jn);
                
                /* == Notify Administrator == */
                $mailer = Mailer::sendMail();
                $tpl = Database::Go()->select(Content::eTable, array('body', 'subject'))->where('typeid', 'payComplete', '=')->first()->run();
                $core = App::Core();
                $body = str_replace(array(
                    '[LOGO]',
                    '[CEMAIL]',
                    '[COMPANY]',
                    '[SITE_NAME]',
                    '[DATE]',
                    '[SITEURL]',
                    '[NAME]',
                    '[TYPE]',
                    '[ITEMNAME]',
                    '[CDKEY]',
                    '[PRICE]',
                    '[STATUS]',
                    '[PP]',
                    '[IP]',
                    '[FB]',
                    '[TW]'
                ), array(
                    $core->plogo,
                    $core->site_email,
                    $core->company,
                    $core->site_name,
                    date('Y'),
                    SITEURL,
                    App::Auth()->name,
                    Language::$word->PRD_PRODUCT,
                    implode(', ', array_column($cart, 'title')),
                    implode(', ', array_column($items, 'cdkey')),
                    $amount,
                    'Completed',
                    $pp->displayname,
                    Url::getIP(),
                    $core->social->facebook,
                    $core->social->twitter
                ), $tpl->body);
                
                $mailer->Subject = $tpl->subject;
                $mailer->Body = $body;
                
                try {
                    $mailer->setFrom($core->site_email, $core->company);
                    $mailer->addAddress($core->site_email, $core->company);
                    $mailer->isHTML();
                    $mailer->send();
                } catch (\PHPMailer\PHPMailer\Exception) {
                }
                
                /* == Notify User == */
                $umailer = Mailer::sendMail();
                $tpl2 = Database::Go()->select(Content::eTable, array('body', 'subject'))->where('typeid', 'payCompleteUser', '=')->first()->run();
                $ubody = str_replace(array(
                    '[LOGO]',
                    '[CEMAIL]',
                    '[COMPANY]',
                    '[SITE_NAME]',
                    '[DATE]',
                    '[SITEURL]',
                    '[NAME]',
                    '[TYPE]',
                    '[ITEMNAME]',
                    '[CDKEY]',
                    '[PRICE]',
                    '[TAX]',
                    '[PP]',
                    '[FB]',
                    '[TW]'
                ), array(
                    $core->plogo,
                    $core->site_email,
                    $core->company,
                    $core->site_name,
                    date('Y'),
                    SITEURL,
                    App::Auth()->name,
                    Language::$word->PRD_PRODUCT,
                    implode(', ', array_column($items, 'title')),
                    Language::$word->PRD_CDKEYS . ': ' . implode(', ', array_column($items, 'cdkey')),
                    $amount,
                    $totals->tax,
                    $pp->displayname,
                    Url::getIP(),
                    $core->social->facebook,
                    $core->social->twitter
                ), $tpl2->body);
                
                $umailer->Subject = $tpl2->subject;
                $umailer->Body = $ubody;
                
                try {
                    $umailer->setFrom($core->site_email, $core->company);
                    $umailer->addAddress($auth->email, $auth->name);
                    $umailer->isHTML();
                    $umailer->send();
                } catch (\PHPMailer\PHPMailer\Exception) {
                }
                
                // empty cart
                Database::Go()->delete(Product::cxTable)->where('user_id', $auth->sesid, '=')->run();
                
            } catch (CardException $e) {
                $body = $e->getJsonBody();
                $err = $body['error'];
                $json['type'] = 'error';
                Message::$msgs['msg'] = 'Message is: ' . $err['message'] . "\n";
                Message::msgSingleStatus();
            }
        } else {
            Message::msgSingleStatus();
        }
    }