<?php
namespace App\Core\Controller;
use App\Core\Service\Logger;
use App\Core\Service\Validator;
abstract class CoreController
{
    public $headers;
    public $input = [];
    private $logger;
    public $user_agent  = null;
    public $ip_address  = null;
    public $logged_user = null;
    public $redis = null;
    public function __construct() {
        try {
            $post = json_decode(file_get_contents("php://input"), true);
            if(!empty($post)) {
                foreach($post as $key=>$val) {
                    $this->input[$key] = $val;
                }
            }
            if(!empty($_REQUEST)) {
                foreach($_REQUEST as $key=>$val) {
                    $this->input[$key] = $val;
                }
            }
            if (!empty($_SERVER['REMOTE_ADDR'])) {
                $this->ip_address = $_SERVER['REMOTE_ADDR'];
            } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $this->ip_address = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
            }
            if(!empty($_SERVER['HTTP_USER_AGENT'])) {
                $this->user_agent = $_SERVER['HTTP_USER_AGENT'];
            }
            
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
        }
    }

    public function sendResponse(Array $resp) {
        try {
            http_response_code(200);
            $empdata = json_encode($resp);
            echo $empdata;
            exit;
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
        }
    }

    public function pr($message) {
        try {
            echo "<pre>";
            print_r($message);
            echo "<pre>";
            exit;
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
        }

    }

    public function validateReqData(Array $rules, Array $data) {
        try {            
            Validator::setRules($rules);
            Validator::setData($data);
            return Validator::run();
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            return ["status"=>false, "error"=>$e->getMessage()];
        }
    }

    public function getFirstValidationError() {
        return Validator::getFirstError();
    }
}