<?php
    /**
     * ipn
     *
     * @package Wojo Framework
     * @author wojoscripts.com
     * @copyright 2023
     * @version 5.00: ipn.php, v1.00 7/18/2023 6:38 PM Gewa Exp $
     *
     */
    const _WOJO = true;
    
    ini_set('log_errors', true);
    ini_set('error_log', dirname(__file__) . '/ipn_errors.log');
    
    if (intval($_POST['status']) == 2) {
        require_once '../../../init.php';
        $pp = Database::Go()->select(Core::gTable)->where('name', 'skrill', '=')->first()->run();
        
        // Check for mandatory fields
        $r_fields = array(
            'status',
            'md5sig',
            'merchant_id',
            'pay_to_email',
            'mb_amount',
            'mb_transaction_id',
            'currency',
            'amount',
            'transaction_id',
            'pay_from_email',
            'mb_currency'
        );
        
        foreach ($r_fields as $f) {
            if (!isset($_POST[$f])) {
                die;
            }
        }
        
        // Check for MD5 signature
        $md5 = strtoupper(md5($_POST['merchant_id'] . $_POST['transaction_id'] . strtoupper(md5($pp->extra3)) . $_POST['mb_amount'] . $_POST['mb_currency'] . $_POST['status']));
        if ($md5 != $_POST['md5sig']) {
            die;
        }
        
        $mb_currency = Validator::sanitize($_POST['mb_currency']);
        $mc_gross = $_POST['amount'];
        $txn_id = Validator::sanitize($_POST['mb_transaction_id']);
        $custom = Utility::decode($_POST['custom']);
        list($user_id, $sesid) = explode('_', $custom);
        
        $user = Database::Go()->select(User::mTable)->where('id', intval($user_id), '=')->first()->run();
        $cart = Product::getCartContentIpn($sesid);
        $totals = Product::getCartTotal($sesid);
        $tax = Content::calculateTax();
        
        $amount = Utility::numberParse($totals->grand);
        $items = array();
        $cdkey = array();
        
        if ($cart) {
            foreach ($cart as $k => $item) {
                $key = Database::Go()->select(Product::cdTable, array('cdkey'))->where('product_id', $item->id, '=')->one()->run();
                $data = array(
                    'user_id' => $user->id,
                    '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' => strtoupper($mb_currency),
                    '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' => $user->id,
                'items' => json_encode($items),
                'coupon' => $totals->discount,
                'tax' => $totals->tax,
                'subtotal' => $totals->subtotal,
                'grand' => $amount,
                'currency' => 'EUR',
            );
            Database::Go()->insert(Product::ivTable, $xdata)->run();
            
            /* == 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,
                $user->fname . ' ' . $user->lname,
                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) {
            }
            
            // empty cart
            Database::Go()->delete(Product::cxTable)->where('user_id', $sesid, '=')->run();
        }
    } else {
        error_log('Process IPN failed: payment or signature mismatch', 3, 'pp_errorlog.log');
    }