<?php
namespace App\Controllers;
use App\Core\Controller\CoreController;
use App\Core\Service\Logger;
use App\Core\Service\Redis;
use App\Core\Library\Crypto;
use App\Service\Kafkam;
abstract class BaseController extends CoreController
{
    public $headers;
    public $input = [];
    public $logged_user = null;
    public $user_data = null;
    public $redis = null;
    public $Kafkam;
    public function __construct() {
        parent::__construct();
        try {
            $this->redis = new Redis();
            $this->Kafkam = new Kafkam();
            if(function_exists('getallheaders')) {
                $this->headers = getallheaders();
                if(!empty($this->headers['User-Token'])) {
                    $this->headers['user_token'] = $this->headers['User-Token'];
                }
                if(!empty($this->headers['User_token'])) {
                    $this->headers['user_token'] = $this->headers['User_token'];
                }
                if(!empty($this->headers['user_token'])) {
                    $logged_user = Crypto::decryptJwtToken($this->headers['user_token']);
                    $data = $this->redis->getData('sanordo_logged_admin_users', $logged_user->id);
                    if(!empty($data)) {
                        $this->logged_user = $data;
                    }
                }
                if(!empty($this->headers['Authorization']) || !empty($this->headers['authorization'])) {
                    $key = !empty($this->headers['Authorization'])?$this->headers['Authorization']:(!empty($this->headers['authorization'])?$this->headers['authorization']:'');
                    if(!empty($key)) {
                        $token = $this->getBearerToken($key);
                        if(!empty($token)) {
                            $logged_user = Crypto::decryptJwtToken($token);
                            $data = $this->redis->getData('logged_users', $logged_user->id);
                            if(!empty($data)) {
                                $this->user_data = $data;
                            }
                        }
                    }
                }
            }
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
        }
    }

    function getBearerToken($token) {
        if (!empty($token)) {
            if (preg_match('/Bearer\s(\S+)/', $token, $matches)) {
                return $matches[1];
            }
        }
        return null;
    }
}