<?php
/*+*******************************************************************************
 * The content of this file is subject to the CRMTiger Pro license.
 * ("License"); You may not use this file except in compliance with the License
 * The Initial Developer of the Original Code is vTiger
 * The Modified Code of the Original Code owned by https://crmtiger.com/
 * Portions created by CRMTiger.com are Copyright(C) CRMTiger.com
 * All Rights Reserved.
  ***************************************************************************** */

class CTMobileSettings_APILogsSettings_View extends Settings_Vtiger_Index_View {

    function __construct() {
        parent::__construct();
    }

    public function checkPermission(Vtiger_Request $request) {
        $license_data = CTMobileSettings_Module_Model::getLicenseData();
        if(strtolower($license_data['Plan']) === 'free'){
            throw new AppException(vtranslate('LBL_PERMISSION_DENIED', 'Vtiger'));
        }else{
            $currentUserModel = Users_Record_Model::getCurrentUserModel();
            if(!$currentUserModel->isAdminUser()) {
                throw new AppException(vtranslate('LBL_PERMISSION_DENIED', 'Vtiger'));
            }
        }
    }

    public function preProcess(Vtiger_Request $request) {
        parent::preProcess($request);        
    }

    public function process(Vtiger_Request $request) {
        $currentUser = Users_Record_Model::getCurrentUserModel();
        $module = $request->getModule();
        $adb = PearDatabase::getInstance();
        $mode = $request->getMode();
        if($mode == 'removeLogs'){
            $query= $adb->pquery("TRUNCATE TABLE ctmobile_apilogs");
            $result = array('success' => true);
            $response = new Vtiger_Response();
            $response->setResult($result);
            $response->emit();
        }else if($mode == 'downloadLogs'){
            $query = $adb->pquery("SELECT * FROM ctmobile_apilogs");
            $numofrows = $adb->num_rows($query);

            if($numofrows > 0){
                $fileName = 'APILogData.csv';
                header("Content-Disposition:attachment;filename=$fileName");
                header("Content-Type:text/csv;charset=UTF-8");

                $headers = array("Sr No","Username","Request","Response");
                $header =  implode("\t", $headers) . "\n";
                echo $header;
                
                $entries = array();
                for($i=0;$i<$numofrows;$i++){
                    $srno = $i+1;
                    $row = $adb->query_result_rowdata($query,$i);
                    $UserName  = '';
                    if($row['userid'] != ''){
                        $userModel = Users_Record_Model::getInstanceById($row['userid'],'Users');
                        $UserName = decode_html(decode_html($userModel->get('first_name').' '.$userModel->get('last_name')));
                    }
                    $rowData = array($srno,$UserName,decode_html(decode_html($row['apirequest'])),decode_html(decode_html($row['apiresponse'])));
                    
                    echo implode("\t", array_values($rowData)) . "\n";
                }
                
            }

        }else if($mode == 'updateLogs'){
            $logvalue = $request->get('logvalue');
            
        }else{
            $viewer = $this->getViewer($request);
            $query = $adb->pquery("SELECT user_setting_value FROM ctmobile_user_settings WHERE user_setting_type=?", array('api_logs'));
            $ALLOW_API_LOGS = $adb->query_result($query,0,'user_setting_value');
            $viewer->assign('ALLOW_APILOGS',$ALLOW_API_LOGS);   
            echo $viewer->view('CTMobileAPILogsSettings.tpl',$module,true);
        }
    }

    /**
     * Function to get the list of Script models to be included
     * @param Vtiger_Request $request
     * @return <Array> - List of Vtiger_JsScript_Model instances
     */
    function getHeaderScripts(Vtiger_Request $request) {
        $headerScriptInstances = parent::getHeaderScripts($request);
        $moduleName = $request->getModule();

        $jsFileNames = array(
            "modules.CTMobileSettings.resources.APILogsSettings",
            '~/layouts/vlayout/modules/CTMobileSettings/bootstrap-switch.min.js'
        );

        $jsScriptInstances = $this->checkAndConvertJsScripts($jsFileNames);
        $headerScriptInstances = array_merge($headerScriptInstances, $jsScriptInstances);
        return $headerScriptInstances;
    }

    public function getHeaderCss(Vtiger_Request $request) {
        $headerCssInstances = parent::getHeaderCss($request);
        $cssFileNames = array(
            '~/layouts/vlayout/modules/CTMobileSettings/bootstrap2-switch.min.css'
        );
        $cssInstances = $this->checkAndConvertCssStyles($cssFileNames);
        $headerCssInstances = array_merge($headerCssInstances, $cssInstances);
        return $headerCssInstances;
    }

}
