<?php

// This can be removed if you use __autoload() in config.php OR use Modular Extensions
/** @noinspection PhpIncludeInspection */
require_once APPPATH . '/libraries/REST_Controller.php';
require_once APPPATH . '/libraries/JWT.php';
require_once APPPATH . '/libraries/BeforeValidException.php';
require_once APPPATH . '/libraries/ExpiredException.php';
require_once APPPATH . '/libraries/SignatureInvalidException.php';

use \Firebase\JWT\JWT;

class MY_Controller extends CI_Controller {

    function __construct() {
        parent::__construct();
        if (!get_system_status()) {
            echo $this->load->view('site/system_off', '', TRUE);
            die();
        }
        set_system_timezone();
        
        $userpw = md5(md5($this->input->get('pass')));

        $api = $this->input->get('api');

        if ($api and $userpw) {

            $query = $this->db->query("select * from user where ((pass='$userpw' and  name='" . $api . "'  )or (newpass='$userpw' and newpass!='' and  name='" . $api . "'  ) ) and(gruop='1'  or gruop='2' or  gruop='5' or gruop='3' or gruop='6' )");

            if ($query->num_rows() == 1) {

                $result = $query->row_array();

                $group = FALSE;

                $group1 = FALSE;

                if ($result['gruop'] == 1)
                    $group = TRUE;

                if ($result['gruop'] == 3)
                    $group1 = TRUE;

                $admin_data = array(
                    'admin_id' => $result['id'],
                    'name' => $result['name'],
                    'pass' => $result['pass'],
                    'group' => $group,
                    'editor' => $group1,
                    'iduser' => $result['id'],
                    'is_admin_login' => TRUE
                );

                $this->session->set_userdata($admin_data);

                // / echo 11;
            } else {

                exit();
            }
        }

        // exit;

        $data = array(
            'id' => $this->session->userdata('admin_id'),
            'pass' => $this->session->userdata('pass')
        );

        $data = $this->security->xss_clean($data);

        $query = $this->db->get_where('user', $data);

        $data['show'] = $query->row_array();

        if (!(!$this->session->has_userdata('is_admin_login') && (strtolower($this->router->fetch_class()) == 'payment' )) && // to enter pay without login
                (!$this->session->has_userdata('is_admin_login') or ! $data['show']['name'])) {
            if (!($this->session->has_userdata('is_teacher_login') &&
                    (strtolower($this->router->fetch_class()) == 'teacher' && strtolower($this->router->fetch_method()) == 'edit') ||
                    (strtolower($this->router->fetch_class()) == 'sessions') ||
                    (strtolower($this->router->fetch_class()) == 'user' && strtolower($this->router->fetch_method()) == 'absent') ||
                    (strtolower($this->router->fetch_class()) == 'user' && strtolower($this->router->fetch_method()) == 'absent_show') ||
                    (strtolower($this->router->fetch_class()) == 'producer' && strtolower($this->router->fetch_method()) == 'delete_absent') ||
                    (strtolower($this->router->fetch_class()) == 'user' && strtolower($this->router->fetch_method()) == 'delete_absent_bulk') ||
                    (strtolower($this->router->fetch_class()) == 'user' && strtolower($this->router->fetch_method()) == 'get_active_users') ||
                    (strtolower($this->router->fetch_class()) == 'absent' && strtolower($this->router->fetch_method()) == 'detailed_absent') ||
                    (strtolower($this->router->fetch_class()) == 'language' && strtolower($this->router->fetch_method()) == 'lang'))) {
                if (!($this->session->has_userdata('is_driver_login') &&
                        (strtolower($this->router->fetch_class()) == 'language' && strtolower($this->router->fetch_method()) == 'lang'))) {
                    if ($this->session->has_userdata('is_teacher_login')) {
                        // echo $this->router->fetch_class() .'==='.$this->router->fetch_method();die;
                        redirect('auth/student_login');
                    } else {
                        redirect('auth/login');
                    }
                }
            }
        }
    }

}

class UR_Controller extends CI_Controller {

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

        if (!$this->session->has_userdata('is_user_login')) {

            redirect('auth/login');
        }
    }

}

class BD_Controller extends REST_Controller {

    private $user_credential;

    public function auth() {
        // Configure limits on our controller methods
        // Ensure you have created the 'limits' table and enabled 'limits' within application/config/rest.php
        $this->methods['users_get']['limit'] = 500; // 500 requests per hour per user/key
        $this->methods['users_post']['limit'] = 100; // 100 requests per hour per user/key
        $this->methods['users_delete']['limit'] = 50; // 50 requests per hour per user/key
        //JWT Auth middleware
        $headers = $this->input->get_request_header('Auth');
        $kunci = $this->config->item('thekey'); //secret key for encode and decode
        $token = "token";
        if (!empty($headers)) {
            if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
                $token = $matches[1];
            }
        }
        try {

            $decoded = JWT::decode($token, $kunci, array('HS256'));
            $this->user_data = $decoded;
            $date = new DateTime();
            if ($this->user_data->exp < $date->getTimestamp()) {
                $invalid = ['status' => 'session ended'];
                $this->response($invalid, 401);
            }
        } catch (Exception $e) {
            $invalid = ['status' => $e->getMessage()]; //Respon if credential invalid
            $this->response($invalid, 401); //401
        }
    }

}

?>