<?php

class Ajax {


    /**
     * Undocumented function
     *
     * @param string $sField
     * @param int [$iFilter]
     * @param bool [$bAsArray]
     * @return void
     */
    public function getPostField($sField, $iFilter = FILTER_DEFAULT, $fallback = null, $bAsArray = false) {
        $options = $bAsArray ? FILTER_REQUIRE_ARRAY : 0;
        $value = filter_input(INPUT_POST, $sField, $iFilter, $options);
        if ($value === null || $value === false || $value === '' || (is_array($value) && empty($value))) {
            return $fallback;
        }

        return $value;
    }


    /**
     * Validate OVIS API authentication key
     *
     * @param string $sFileName
     * @return void|string
     */
    public function validateApiAuthKey($sFileName, $aSession, $sSessionKey) {

        $oResponse = new \stdClass();
        $oResponse->message = '';

        $sAuthenticationKeyFile = !empty($sFileName) ? $sFileName : 'ovis_api_auth';

        if(!file_exists($sAuthenticationKeyFile)) {
            $oResponse->message = 'No API authentication file found';
            return $oResponse;
        }

        if(!isset($aSession[$sSessionKey])) {
            $oResponse->message = 'No API authentication key in session found';
            return $oResponse;
        }

        $sAuthenticationKeyHash = file_get_contents($sAuthenticationKeyFile);
        $sSessionAuthenticationKeyHash = $aSession[$sSessionKey];

        if(hash('sha256', trim($sSessionAuthenticationKeyHash)) !== $sAuthenticationKeyHash) {
            $oResponse->message = 'Invalid API authentication key';
            return $oResponse;
        }

        return $sSessionAuthenticationKeyHash;
    }


    /**
     * Get data from local cache
     *
     * @param string $sRawCacheKey
     * @param string $sCacheDir
     * @param int $iCacheLifetime
     * @return mixed
     */
    public function getCacheData($sRawCacheKey, $sCacheDir, $iCacheLifetime) {

        if(empty($sRawCacheKey)) return;
        if(empty($sCacheDir)) return;

        $sCacheKey = $sRawCacheKey;
    
        $sCacheFilePath = $sCacheDir . '/' . '_'.strval($iCacheLifetime).'_' . $sCacheKey . '.cache';
        
        if(file_exists($sCacheFilePath)) {
            $lastModified = filemtime($sCacheFilePath);
            
            if(($lastModified + $iCacheLifetime) > time()) {
                $oCache = file_get_contents($sCacheFilePath);
                return unserialize($oCache);
            } else {
                unlink($sCacheFilePath);
                return null;
            }
        } else {
            return null;
        }
    }


    /**
     * Add data to local cache
     *
     * @param string $sRawCacheKey
     * @param string $sCacheDir
     * @param mixed $data
     * @param int $iCacheLifetime
     * @return mixed
     */
    public function addCacheData($sRawCacheKey, $sCacheDir, $data, $iCacheLifetime) {

        if(empty($sRawCacheKey)) return;
        if(empty($sCacheDir)) return;

        $sCacheKey = $sRawCacheKey;
    
        $bCachActive = false;
    
        if(!is_dir($sCacheDir)) {
            if(@mkdir($sCacheDir, 0755, true)){
		$bCachActive = true;					
            }
        } else {			
            $bCachActive = true;			
	}
		
	if(!empty($bCachActive)){    
            $sCacheFilePath = $sCacheDir . '/' . '_'.strval($iCacheLifetime).'_' . $sCacheKey . '.cache';
			
            file_put_contents($sCacheFilePath, serialize($data));
        }
    }


    /**
     * Undocumented function
     *
     * @param string $message
     * @param int [$httpCode]
     * @return void
     */
    public function json_error($message, $httpCode = 400) {
        $oResponse = new \stdClass();
        $oResponse->message = $message;
        $oResponse->success = false;
        http_response_code($httpCode);
        echo json_encode($oResponse);
        exit;
    }


    /**
     * Set HTTP response headers for successful response
     *
     * @return void
     */
    public function setSuccessHeaders() {
        header('Cache-Control: public, max-age=3600, must-revalidate');
        header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 3600) . ' GMT');
        header('Pragma: cache');
        header('Content-Type: application/json; charset=utf-8');
    }


    /**
     * Set HTTP response headers for cache response
     *
     * @return void
     */
    public function setCacheHeaders() {
        header('Cache-Control: public, max-age=3600, must-revalidate');
        header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 3600) . ' GMT');
        header('Pragma: cache');
        header('Content-Type: application/json; charset=utf-8');
        header('Custom-Header-Name: Response From Cache');
    }
}