<?php
    /**
     * helper
     *
     * @package Wojo Framework
     * @author wojoscripts.com
     * @copyright 2023
     * @version 5.00: helper.php, v1.00 7/23/2023 8:27 AM Gewa Exp $
     *
     */
    const _WOJO = true;
    require_once('../../init.php');
    
    if (!App::Auth()->is_Admin()) {
        exit;
    }
    
    $gAction = Validator::get('action');
    $pAction = Validator::post('action');
    $iAction = Validator::post('iaction');
    $title = Validator::post('title') ? Validator::sanitize($_POST['title']) : null;
    
    $content = App::Content();
    $user = App::User();
    $admin = App::Admin();
    
    /* == Post Actions== */
    switch ($pAction) :
        //Edit language phrase
        case 'editPhrase':
            $payload = BASEPATH . Language::langdir . $_POST['path'];
            if (File::exists($payload)) {
                $data = json_decode(File::loadFile($payload), true);
                $update = array();
                $what = Validator::sanitize($_POST['key']);
                
                foreach ($data as $key => $value) {
                    foreach ($value as $name => $row) {
                        if ($name == $what) {
                            $value[$name] = $title;
                        }
                        $update[$key] = $value;
                    }
                }
                
                $jsonData = json_encode($update, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
                File::writeToFile($payload, $jsonData);
                
                $json['title'] = $title;
                print json_encode($json);
            }
            break;
        
        //Update Country Tax
        case 'editTax':
            if (array_key_exists('title', $_POST)) {
                print '0.000';
                exit;
            }
            $data['vat'] = Validator::sanitize($_POST['title'], 'float');
            Database::Go()->update(Content::cnTable, $data)->where('id', Filter::$id, '=')->run();
            
            $json['title'] = $title;
            print json_encode($json);
            break;
        
        //Change Coupon Status
        case 'couponStatus':
            Database::Go()->update(Content::dcTable, array('active' => intval($_POST['active'])))->where('id', Filter::$id, '=')->run();
            break;
        
        //Change Gateway Status
        case 'gatewayStatus':
            if (Auth::checkAcl('owner')) {
                Database::Go()->update(Core::gTable, array('active' => intval($_POST['active'])))->where('id', Filter::$id, '=')->run();
            }
            break;
        
        //Rename File
        case 'renameFile':
            $admin->renameFile();
            break;
        
        //Optimize Database
        case 'optimizeDatabase':
            $json['html'] = DatabaseTools::optimize();
            $json['type'] = 'success';
            print json_encode($json);
            break;
        
        /* == Process Notification == */
        case 'resend':
            $user->resendNotification();
            break;
        
        /* == Update Role Description == */
        case 'editRole':
            $user->updateRoleDescription();
            break;
        
        /* == Change Role == */
        case 'changeRole':
            if (Auth::checkAcl('owner')) {
                Database::Go()->update(User::rpTable, array('active' => intval($_POST['active'])))->where('id', Filter::$id, '=')->run();
            }
            break;
        
        //Ajax Search
        case 'ajax_search':
            $string = Validator::sanitize($_POST['value'], 'string', 15);
            if (strlen($string) > 2) {
                $sql = '
                SELECT id, fname, lname, email
                  FROM `' . User::mTable . "`
                  WHERE MATCH (fname) AGAINST ('" . $string . "*' IN BOOLEAN MODE) or
                  MATCH (lname) AGAINST ('" . $string . "*' IN BOOLEAN MODE) or
                  MATCH (email) AGAINST ('" . $string . "*' IN BOOLEAN MODE)
                  AND type = ?
                  ORDER BY fname
                  LIMIT 10
                ";
                $html = '';
                
                if ($result = Database::Go()->rawQuery($sql, array('member'))->run()) {
                    $html .= '<table class="wojo basic dashed table">';
                    foreach ($result as $row) {
                        $html .= '<tr>';
                        $html .= '<td>';
                        $html .= '<span class="wojo simple label">' . $row->id . '</span>';
                        $html .= '</td>';
                        $html .= '<td>';
                        $html .= '<a data-name="' . $row->fname . ' ' . $row->lname . '" data-id="' . $row->id . '">' . $row->fname . ' ' . $row->lname . ' - (' . $row->email . ')</a>';
                        $html .= '</td>';
                        $html .= '</tr>';
                    }
                    $html .= '</table>';
                    $json['html'] = $html;
                    $json['status'] = 'success';
                } else {
                    $json['status'] = 'error';
                }
                print json_encode($json);
            }
            break;
    endswitch;
    
    /* == Get Actions== */
    switch ($gAction) :
        //Index Payments Chart
        case 'getIndexStats':
            $data = Stats::indexSalesStats();
            print json_encode($data);
            break;
        
        //Main Stats
        case 'getMainStats':
            $data = Stats::getMainStats();
            print json_encode($data);
            break;
        
        //Language Section == */
        case 'languageSection':
            $payload = BASEPATH . Language::langdir . $_GET['abbr'] . '.lang.json';
            if (File::exists($payload)) {
                $tpl = App::View(BASEPATH . 'view/admin/snippets/');
                
                $data = json_decode(File::loadFile($payload), true);
                $section = $data[Validator::sanitize($_GET['section'])];
                
                $tpl->section = $section;
                $tpl->type = $_GET['type'];
                $tpl->abbr = $_GET['abbr'];
                $tpl->template = 'languageSection';
                $json['html'] = $tpl->render();
            } else {
                $json['type'] = 'error';
                $json['title'] = Language::$word->ERROR;
                $json['message'] = Language::$word->FU_ERROR15;
            }
            print json_encode($json);
            break;
        
        //Get Content Type
        case 'contentType':
            $type = Validator::sanitize($_GET['type'], 'alpha');
            $html = '';
            if ($type == 'page') {
                $data = Database::Go()->select(Content::pTable, array('id', 'title'))->where('active', 1, '=')->orderBy('title', 'ASC')->run();
                if ($data) {
                    foreach ($data as $row) {
                        $html .= "<option value=\"" . $row->id . "\">" . $row->title . "</option>\n";
                    }
                    $json['type'] = 'page';
                }
            } else {
                $json['type'] = 'web';
            }
            $json['message'] = $html;
            print json_encode($json);
            break;
        
        // Export Users
        case 'exportUsers':
            header('Pragma: no-cache');
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename=UserList.csv');
            
            $data = fopen('php://output', 'w');
            fputcsv($data, array('Name', 'Membership', 'Expire', 'Email', 'Newsletter', 'Created'));
            
            $result = Stats::exportUsers();
            if ($result) {
                foreach ($result as $row) {
                    fputcsv($data, $row);
                }
            }
            break;
        
        //User Payments Chart
        case 'getUserProductPaymentsChart':
            $data = Stats::getUserProductPaymentsChart(Filter::$id);
            print json_encode($data);
            break;
        
        //Export User Payments
        case 'exportUserProductPayments':
            header('Pragma: no-cache');
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename=UserPayments.csv');
            
            $data = fopen('php://output', 'w');
            fputcsv($data, array('TXN ID', 'Item', 'Amount', 'TAX/VAT', 'Coupon', 'Total', 'Currency', 'Processor', 'Created'));
            
            $result = Stats::exportUserProductPayments(Filter::$id);
            if ($result) {
                foreach ($result as $row) {
                    fputcsv($data, $row);
                }
            }
            break;
        
        /* == Membership Payments Chart == */
        case 'getMembershipPaymentsChart':
            $data = Stats::getMembershipPaymentsChart(Filter::$id);
            print json_encode($data);
            break;
            
        /* == Export Membership Payments == */
        case 'exportMembershipPayments':
            header('Pragma: no-cache');
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename=MembershipPayments.csv');
            
            $data = fopen('php://output', 'w');
            fputcsv($data, array('TXN ID', 'User', 'Amount', 'TAX/VAT', 'Coupon', 'Total Amount', 'Currency', 'Processor', 'Created'));
            
            $result = Stats::exportMembershipPayments(Filter::$id);
            if($result):
                foreach ($result as $row) :
                    fputcsv($data, $row);
                endforeach;
            endif;
            break;
            
        /* == Resend Notification == */
        case 'resend':
            $tpl = App::View(BASEPATH . 'view/admin/snippets/');
            $tpl->template = 'resendNotification';
            $tpl->data = Database::Go()->select(User::mTable, array('id', 'email', "CONCAT(fname,' ',lname) as name"))->where('id', Filter::$id, '=')->first()->run();
            echo $tpl->render();
            break;
        
        //Edit Role
        case 'editRole':
            $tpl = App::View(BASEPATH . 'view/admin/snippets/');
            $tpl->data = Database::Go()->select(User::rTable)->where('id', Filter::$id, '=')->first()->run();
            $tpl->template = 'editRole';
            echo $tpl->render();
            break;
        
        //Rename File
        case 'renameFile':
            $tpl = App::View(BASEPATH . 'view/admin/snippets/');
            $tpl->template = 'renameFile';
            $tpl->row = Database::Go()->select(Product::fTable)->where('id', Filter::$id, '=')->first()->run();
            echo $tpl->render();
            break;
        
        //All Sales Chart
        case 'getSalesChart':
            $data = Stats::getAllSalesStats();
            print json_encode($data);
            break;
        
        //Export All Payments
        case 'exportAllTransactions':
            header('Pragma: no-cache');
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename=AllPayments.csv');
            
            $data = fopen('php://output', 'w');
            fputcsv($data, array('TXN ID', 'Item', 'User', 'Amount', 'TAX/VAT', 'Coupon', 'Total Amount', 'Currency', 'Processor', 'Created'));
            
            $result = Stats::exportAllTransactions();
            if ($result) {
                foreach ($result as $row) {
                    fputcsv($data, $row);
                }
            }
            break;
        
        //Item Chart
        case 'itemChart':
            $data = Stats::itemChart(Filter::$id);
            print json_encode($data);
            break;
        
        //Export Item Payments
        case 'itemPayments':
            header('Pragma: no-cache');
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename=ItemPayments.csv');
            
            $data = fopen('php://output', 'w');
            fputcsv($data, array('TXN ID', 'User', 'Amount', 'TAX/VAT', 'Coupon', 'Total Amount', 'Currency', 'Processor', 'Created'));
            
            $result = Stats::itemPayments(Filter::$id);
            if ($result) {
                foreach ($result as $row) {
                    fputcsv($data, $row);
                }
                fclose($data);
            }
            break;
    endswitch;
    
    /* == Instant Actions== */
    switch ($iAction) :
        //Sort Menus
        case 'sortMenus':
            $i = 0;
            $query = 'UPDATE `' . Content::mTable . '` SET `sorting` = CASE ';
            $list = '';
            foreach ($_POST['sorting'] as $item) {
                $i++;
                $query .= ' WHEN id = ' . $item . ' THEN ' . $i . ' ';
                $list .= $item . ',';
            }
            $list = substr($list, 0, -1);
            $query .=
                'END WHERE id IN (' . $list . ')';
            Database::Go()->rawQuery($query)->run();
            break;
        
        //Sort Categories
        case 'sortCategories':
            $i = 0;
            $query = 'UPDATE `' . Content::cTable . '` SET `sorting` = CASE ';
            $list = '';
            foreach ($_POST['sorting'] as $item) {
                $i++;
                $query .= ' WHEN id = ' . $item . ' THEN ' . $i . ' ';
                $list .= $item . ',';
            }
            $list = substr($list, 0, -1);
            $query .=
                'END WHERE id IN (' . $list . ')';
            Database::Go()->rawQuery($query)->run();
            break;
        
        //Sort Images
        case 'sortImages':
            $i = 0;
            $query = 'UPDATE `' . Product::iTable . '` SET `sorting` = CASE ';
            $idlist = '';
            foreach ($_POST['sorting'] as $item) {
                $i++;
                $query .= ' WHEN id = ' . $item . ' THEN ' . $i . ' ';
                $idlist .= $item . ',';
            }
            $idlist = substr($idlist, 0, -1);
            $query .= '
				  END
				  WHERE id IN (' . $idlist . ')';
            Database::Go()->rawQuery($query)->run();
            break;
        
        //Sort Memberships
        case 'sortMemberships':
            $i = 0;
            $query = 'UPDATE `' . Membership::mTable . '` SET `sorting` = CASE ';
            $list = '';
            foreach ($_POST['sorting'] as $item) {
                $i++;
                $query .= ' WHEN id = ' . $item . ' THEN ' . $i . ' ';
                $list .= $item . ',';
            }
            $list = substr($list, 0, -1);
            $query .=
                'END WHERE id IN (' . $list . ')';
            Database::Go()->rawQuery($query)->run();
            break;
        
        //Comment Approve
        case 'commentApprove':
            if (Database::Go()->update(Comment::mTable, array('active' => 1))->where('id', Filter::$id, '=')->run()) {
                $json['type'] = 'success';
                print json_encode($json);
            }
            break;
        
        //Sort Custom Fields
        case 'sortFields':
            $i = 0;
            $query = 'UPDATE `' . Content::cfTable . '` SET `sorting` = CASE ';
            $idlist = '';
            foreach ($_POST['sorting'] as $item) {
                $i++;
                $query .= ' WHEN id = ' . $item . ' THEN ' . $i . ' ';
                $idlist .= $item . ',';
            }
            $idlist = substr($idlist, 0, -1);
            $query .= '
				  END
				  WHERE id IN (' . $idlist . ')';
            Database::Go()->rawQuery($query)->run();
            break;
        
        //Sort F.A.Q.
        case 'sortFaq':
            $i = 0;
            $query = 'UPDATE `' . Content::fTable . '` SET `sorting` = CASE ';
            $idlist = '';
            foreach ($_POST['sorting'] as $item) {
                $i++;
                $query .= ' WHEN id = ' . $item . ' THEN ' . $i . ' ';
                $idlist .= $item . ',';
            }
            $idlist = substr($idlist, 0, -1);
            $query .= '
				  END
				  WHERE id IN (' . $idlist . ')';
            Database::Go()->rawQuery($query)->run();
            break;
        
        //Database Backup
        case 'databaseBackup':
            if ($sql = DatabaseTools::fetch()) {
                $fname = UPLOADS . '/backups/';
                $fname .= date(DatabaseTools::suffix);
                $fname .= '.sql';
                
                DatabaseTools::save($fname, $sql, false);
                
                $data['backup'] = basename($fname);
                Database::Go()->update(Core::sTable, $data)->where('id', 1, '=')->run();
                
                $tpl = App::View(BASEPATH . 'view/admin/snippets/');
                $tpl->template = 'loadDatabaseBackup';
                $tpl->backup = $data['backup'];
                $tpl->dbdir = UPLOADS . '/backups/';
                
                Message::msgModalReply(Database::Go()->affected(), 'success', Language::$word->DBM_BKP_OK, $tpl->render());
            }
            break;
        
        //File Upload
        case 'fileUpload':
            if (array_key_exists('file', $_FILES)) {
                $tpl = App::View(BASEPATH . 'view/admin/snippets/');
                $tpl->template = 'loadFile';
                
                $upl = Upload::instance(Product::FS, Product::FE);
                $upl->process('file', App::Core()->file_dir);
                if (count(Message::$msgs) === 0) {
                    $data = array(
                        'alias' => $upl->fileInfo['name'],
                        'name' => $upl->fileInfo['fname'],
                        'filesize' => $upl->fileInfo['size'],
                        'extension' => $upl->fileInfo['ext'],
                        'type' => $upl->fileInfo['type_short'],
                        'token' => Utility::randomString(16),
                    );
                    
                    $last_id = Database::Go()->insert(Product::fTable, $data)->run();
                    $row = Database::Go()->select(Product::fTable)->where('id', $last_id, '=')->first()->run();
                    $tpl->row = $row;
                    
                    $json['status'] = 'success';
                    $json['filename'] = $data['name'];
                    $json['type'] = File::getFileType($data['name']);
                    $json['id'] = $last_id;
                    $json['html'] = $tpl->render();
                } else {
                    $json['type'] = 'error';
                    $json['message'] = Message::$msgs['name'];
                }
                print json_encode($json);
            }
            break;
        
        //Process Images
        case 'processImages':
            $num_files = count($_FILES['images']['tmp_name']);
            $filedir = UPLOADS . Product::DATA . Filter::$id;
            File::makeDirectory($filedir . '/thumbs');
            
            for ($x = 0; $x < $num_files; $x++) {
                $image = $_FILES['images']['name'][$x];
                $newName = 'IMG_' . Utility::randomString(12);
                $ext = substr($image, strrpos($image, '.') + 1);
                $name = $newName . '.' . strtolower($ext);
                $fullname = $filedir . '/' . $name;
                
                if (!move_uploaded_file($_FILES['images']['tmp_name'][$x], $fullname)) {
                    die(Message::msgSingleError(Language::$word->FU_ERROR13));
                }
                
                try {
                    $img = new Image($filedir . '/' . $name);
                    $img->bestFit(App::Core()->thumb_w, App::Core()->thumb_h)->save($filedir . '/thumbs/' . $name);
                } catch (Exception $e) {
                    echo 'Error: ' . $e->getMessage();
                }
                
                $last_id = Database::Go()->insert(Product::iTable, array('parent_id' => Filter::$id, 'name' => $name))->run();
                
                print '
                       <div class="columns" id="item_' . $last_id . '" data-id="' . $last_id . '">
                           <div class="wojo compact segment center-align">
                              <div class="handle">
                                 <i class="icon grip horizontal"></i>
                              </div>
                              <img src="' . Product::hasThumb($name, Filter::$id) . '" alt="" class="wojo rounded image">
                              <a data-set=\'{"option":[{"delete": "deleteImage","id":' . $last_id . '}],"action":"delete", "parent":"#item_' . $last_id . '"}\'
                                 class="wojo mini icon negative simple button data">
                                 <i class="icon x alt"></i>
                              </a>
                           </div>
                       </div>';
            }
            break;
        
        //Clear Session Temp Queries
        case 'session':
            Session::remove('debug-queries');
            Session::remove('debug-warnings');
            Session::remove('debug-errors');
            print 'ok';
            break;
    endswitch;