<?php
    /**
     * controller
     *
     * @package Wojo Framework
     * @author wojoscripts.com
     * @copyright 2023
     * @version 5.50: controller.php, v1.00 7/12/2023 10:25 AM Gewa Exp $
     *
     */
    
    use Mpdf\Mpdf;
    use Mpdf\MpdfException;
    
    const _WOJO = true;
    require_once('../../init.php');
    
    $delete = Validator::post('delete');
    $trash = Validator::post('trash');
    $pAction = Validator::post('action');
    $gAction = Validator::get('action');
    $iAction = Validator::post('iaction');
    $restore = Validator::post('restore');
    $title = Validator::post('title') ? Validator::sanitize($_POST['title']) : null;
    
    $front = App::Front();
    
    /* == Post Actions == */
    switch ($pAction):
        //Login
        case 'userLogin':
        case 'adminLogin':
            App::Auth()->login($_POST['username'], $_POST['password']);
            break;
        
        //Password Reset
        case 'uResetPass':
        case 'aResetPass':
            $front->passReset();
            break;
        
        //Register
        case 'register':
            $front->registration();
            break;
        
        //Pass Change
        case 'password':
            $front->passwordChange();
            break;
        
        //Update Profile
        case 'profile':
            if (!App::Auth()->is_User()) {
                exit;
            }
            App::Front()->updateProfile();
            break;
        
        //Contact == */
        case 'contact':
            $front->processContact();
            break;
        
        //Buy Membership
        case 'membership':
            if (!App::Auth()->is_User()) {
                exit;
            }
            App::Front()->buyMembership();
            break;
        
        //Select Membership Gateway
        case 'mGateway':
            if (!App::Auth()->is_User()) {
                exit;
            }
            App::Front()->selectGateway();
            break;
        
        //Wishlist Compare
        case 'wcomp':
            if (Filter::$id and isset($_POST['type'])) {
                if ($_POST['type'] == 'wishlist') {
                    if (App::Auth()->is_User()) {
                        Database::Go()->insert(Content::wTable, array('product_id' => Filter::$id, 'user_id' => App::Auth()->uid))->run();
                    } else {
                        Session::setKey('wishlist', Filter::$id, Filter::$id);
                    }
                } else {
                    Session::setKey('compare', Filter::$id, Filter::$id);
                }
                $json['type'] = 'success';
            } else {
                $json['type'] = 'error';
            }
            print json_encode($json);
            break;
        
        //Compare Items
        case 'compare':
            $tpl = App::View(THEMEBASE . '/snippets/');
            $tpl->data = '';
            if (App::Session()->get('compare')) {
                $ids = Utility::implodeFields(Session::get('compare'));
                $tpl->data = App::Product()->Compare($ids);
            }
            $tpl->core = App::Core();
            $tpl->template = 'viewCompare';
            echo $tpl->render();
            break;
        
        //Vote Up/Down
        case 'vote':
            if (Filter::$id) {
                $type = Validator::sanitize($_POST['type'], 'alpha');
                $vote = ($type == 'down') ? 'vote_down = vote_down - 1' : 'vote_up = vote_up + 1';
                
                Database::Go()->rawQuery('
				  UPDATE `' . Comment::mTable . "`
				  SET $vote
				  WHERE id = ?
			  ", array(Filter::$id));
                
                $json['type'] = $type;
                $json['status'] = 'success';
                print json_encode($json);
            }
            break;
        
        //Add to cart
        case 'add':
            Product::addToCart(Filter::$id);
            break;
        
        // Remove from big cart
        case 'removeBig':
            if (Filter::$id) {
                Database::Go()->delete(Product::cxTable)->where('product_id', Filter::$id, '=')->where('user_id', App::Auth()->sesid, '=')->run();
                
                if ($totals = Product::getCartTotal()) {
                    $json['coupon'] = '<div class="icon-text"><i class="icon dash positive alt"></i> ' . Utility::formatNumber($totals->discount) . '</div>';
                    $json['tax'] = '<div class="icon-text"><i class="icon plus negative alt"></i>' . Utility::formatNumber($totals->tax) . '</div>';
                    $json['subtotal'] = Utility::formatNumber($totals->subtotal);
                    $json['total'] = Utility::formatMoney($totals->grand);
                    $json['counter'] = 1;
                } else {
                    $json['coupon'] = '0.00';
                    $json['tax'] = '0.00';
                    $json['subtotal'] = 0;
                    $json['total'] = 0;
                    $json['counter'] = 0;
                }
                $json['count'] = Product::cartCounter();
                $json['status'] = 'success';
            } else {
                $json['status'] = 'error';
            }
            print json_encode($json);
            break;
        
        //Comment Reply
        case 'comment':
        case 'reply':
            App::Comment()->processComment();
            break;
        
        /* == Delete Comment== */
        case 'deleteComment':
            if (App::Auth()->is_Admin()) {
                Database::Go()->delete(Comment::mTable)->where('id', Filter::$id, '=')->run();
                Database::Go()->delete(Comment::mTable)->where('parent_id', Filter::$id, '=')->run();
            }
            break;
        
        //Apply Coupon
        case 'coupon':
            App::Content()->applyCoupon();
            break;
    endswitch;
    
    /* == Get Actions == */
    switch ($gAction):
        //Small Cart
        case 'smallCart':
            $tpl = App::View(THEMEBASE . '/snippets/');
            $tpl->template = 'cart';
            $tpl->url = (isset($_GET['url'])) ? $_GET['url'] : 'index';
            $tpl->data = Product::getCartContent();
            
            $json['html'] = $tpl->render();
            $json['status'] = 'success';
            print json_encode($json);
            break;
        
        //Membership Invoice
        case 'mInvoice':
            if (!App::Auth()->is_User()) {
                exit;
            }
            
            if (!array_key_exists('id', $_GET)) {
                Url::redirect(Url::currentUrl() . '?msg=' . urlencode(Language::$word->FRONT_ERROR01));
                exit;
            }
            
            if ($row = User::membershipInvoice(Filter::$id)) {
                $tpl = App::View(THEMEBASE . '/snippets/');
                $tpl->row = $row;
                $tpl->user = Auth::$userdata;
                $tpl->core = App::Core();
                $tpl->template = 'mInvoice';
                $title = Validator::sanitize($row->title, 'alpha');
                
                require_once(BASEPATH . 'lib/mPdf/vendor/autoload.php');
                try {
                    $mpdf = new Mpdf(['mode' => 'utf-8']);
                    $mpdf->SetTitle($title);
                    $mpdf->WriteHTML($tpl->render());
                    $mpdf->Output($title . '.pdf', 'D');
                } catch (MpdfException $e) {
                }
                exit;
            } else {
                Url::redirect(Url::currentUrl() . '?msg=' . urlencode(Language::$word->FRONT_ERROR01));
            }
            exit;
            break;
        
        //Product Invoice
        case 'pInvoice':
            if (!App::Auth()->is_User()) {
                exit;
            }
            
            if (!array_key_exists('tid', $_GET)) {
                Url::redirect(Url::currentUrl() . '?msg=' . urlencode(Language::$word->FRONT_ERROR01));
                exit;
            }
            
            if ($row = User::productInvoice(Validator::sanitize($_GET['tid'], 'int'))) {
                $tpl = App::View(THEMEBASE . '/snippets/');
                $tpl->row = $row;
                $tpl->user = Auth::$userdata;
                $tpl->items = Utility::jSonToArray($row->items);
                $tpl->core = App::Core();
                $tpl->template = 'pInvoice';
                $title = Validator::sanitize($row->created, 'alphanumeric');
                
                require_once(BASEPATH . 'lib/mPdf/vendor/autoload.php');
                try {
                    $mpdf = new Mpdf(['mode' => 'utf-8']);
                    $mpdf->SetTitle($title);
                    $mpdf->WriteHTML($tpl->render());
                    $mpdf->Output($title . '.pdf', 'D');
                } catch (MpdfException $e) {
                }
            } else {
                Url::redirect(Url::currentUrl() . '?msg=' . urlencode(Language::$word->FRONT_ERROR01));
            }
            exit;
            break;
        
        //Load Gateway
        case 'gateway':
            if (Filter::$id) {
                if ($gateway = Database::Go()->select(Core::gTable)->where('id', Filter::$id, '=')->where('active', 1, '=')->first()->run()) {
                    $tpl = App::View(BASEPATH . 'gateways/' . $gateway->dir . '/shop/');
                    $tpl->gateway = $gateway;
                    $tpl->core = App::Core();
                    $tpl->cart = Product::getCartTotal();
                    $tpl->template = 'form';
                    $json['message'] = $tpl->render();
                } else {
                    $json['message'] = Message::msgSingleError(Language::$word->SYSERROR);
                }
            } else {
                $json['message'] = Message::msgSingleError(Language::$word->SYSERROR);
            }
            print json_encode($json);
            break;
    endswitch;
    
    /* == Instant Actions== */
    switch ($iAction) :
        //Remove Compare
        case 'removeCompare':
            Session::removeKey('compare', Filter::$id);
            $json['type'] = 'success';
            print json_encode($json);
            break;
        
        //Remove Wishlist
        case 'removeWishlist':
            Session::removeKey('wishlist', Filter::$id);
            if (App::Auth()->is_User()) {
                Database::Go()->delete(Content::wTable)->where('product_id', Filter::$id, '=')->where('user_id', App::Auth()->uid, '=')->run();
            }
            $json['type'] = 'success';
            print json_encode($json);
            break;
        
        //Clear Session Temp Queries
        case 'session':
            Session::remove('debug-queries');
            Session::remove('debug-warnings');
            Session::remove('debug-errors');
            print 'ok';
            break;
    endswitch;