<?php
error_reporting(E_ALL);
error_reporting(-1);
ini_set('error_reporting', E_ALL);
setlocale(LC_ALL, 'es_CO.utf8');
session_name('DesarrolloProfesionalPermanente');
session_start();
if(file_exists('classes/mysqliConn.php')) {
    require('classes/mysqliConn.php');
    require('common/variables.php');
} else {
    require('../classes/mysqliConn.php');
    require('../common/variables.php');
}
class main extends mysqliConn {
    public $mysqli;
    private $token;
    private $stringlogin;
    public $title = 'Desarrollo Profesional Permanente';
    public $loginCheck = false;
    public $dir_fotos = 'fotos/';
    public $dir_pregrado_acta_grados = 'pregrado_acta_grados/';
    public $dir_tarjeta_profesional = 'tarjeta_profesional/';
    public $dir_especialidad_acta_grado = 'especialidad_acta_grado/';
    public $dir_cont_caract_ficha_tecn = 'cont_caract_ficha_tecn/';
    public $dir_rut = 'rut/';
    public $dir_logo = 'logo/';
    public $dir_organigrama = 'organigrama/';
    public $allowedPdfs = '.pdf';
    public $allowedDocs = '.doc, .docx';
    public $allowedImgs = '.jpg,.jpeg,.gif,.png,.bmp';
    public $firma = '<br /><br /><span style="font-family: tahoma,sans-serif"><strong>Ascofame<br></strong><span><strong><span style="color: #e69138">Desarrollo Profesional Permanente</span></strong><br>Tel. (57) 1 7425380 <br>Carrera 14 N° 101-53 | Bogotá D.C. | Colombia<br><a href="http://www.ascofame.org.co" target="_blank" rel="noreferrer">www.ascofame.org.co</a></span><br></span>';
    function __construct() {
        global $_GET, $_POST, $_SESSION;
        $this->mysqli = parent::mysqliConn();
        $_GET = $this->cleanvar($_GET, false);
        $_POST = $this->cleanvar($_POST);
        $_SESSION = $this->cleanvar($_SESSION, false);
        $this->token = $this->generateToken();
        $this->loginCheck = $this->loginCheck();
        $this->redirect();
    }
    public function cleanvar($var) {
        if(is_array($var)) {
            foreach($var as $key => $value) {
                $var[$key] = $this->cleanvar($value);
            }
        } else if(is_object($var)) {
            // Do nothing
        } else {
            if($var === '') {
                $var = null;
            } else if(is_numeric($var)) {
                if(strstr($var, '.')) {
                    $var = (float) $var;
                } else if(substr($var, 0, 2) == '0x') {
                    $var = intval($var, 16);
                } else if(substr($var, 0, 1) == '0') {
                    $var = intval($var, 8);
                } else {
                    $var = (int) $var;
                }
            } else if(strtolower((string)$var) == 'true' || strtolower((string)$var) == 'on') {
                $var = true;
            } else if(strtolower((string)$var) == 'false' || strtolower((string)$var) == 'off') {
                $var = false;
            } else if(defined((string)$var)) {
                $var = constant((string)$var);
            }
            $var = htmlspecialchars(trim($var), ENT_QUOTES);
        }
        return $var;
    }
    public function alphanumeric($str) {
        return preg_replace("/[^a-zA-Z0-9]+/", "", $str);
    }
    /* START - Login functions */
    private function logoutHandler() {
        //$app = isset($_SESSION['app']) ? $_SESSION['app'] : 'login';
        if ($stmt = $this->mysqli->prepare('SELECT idsesion FROM session WHERE iduser = ? AND timeend IS NULL')) {
            $stmt->bind_param('s', $_SESSION['iduser']);
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows >= 1) {
                $stmt->bind_result($idsesion);
                while($stmt->fetch()) {
                    $this->mysqli->query('UPDATE session SET timeend = now() WHERE iduser = "' . $_SESSION['iduser'] . '"') or exit(__LINE__ . ':' . $this->mysqli->error);
                }
            }
            $stmt->close();
        }
        $_SESSION = array();
        session_unset();
        session_destroy(); 
        $this->header('login', 'success=Ha cerrado sesión.');
    }
    public function checkBrute($iduser = 0) {
        $intentosvalidos = time() - (2 * 60 * 60); //30Min (1 * 30 * 60) - 1Hr (1 * 60 * 60) - 2Hr (2 * 60 * 60) - 3Hr (3 * 60 * 60) ...
        if ($stmt = $this->mysqli->prepare('SELECT time FROM trysession WHERE iduser = ? AND time > ?')) {
            $stmt->bind_param('ss', $iduser, $intentosvalidos);
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows > 5) {
                return true;
            }
        }
        return false;
    }
    private function loginCheck() {
        if(isset($_SESSION['iduser'], $_SESSION['email'], $_SESSION['fname'], $_SESSION['lname'], $_SESSION['admin'], $_SESSION['estado'], $_SESSION['stringlogin'])) {
            $user_browser = $_SERVER['HTTP_USER_AGENT'] . $this->userIp();
            if($stmt = $this->mysqli->prepare('SELECT user.clave, user.estado FROM user JOIN session ON user.iduser = session.iduser WHERE user.iduser = ? AND session.stringlogin = ? AND session.timeend IS NULL')) {
                $stmt->bind_param('ss', $_SESSION['iduser'], $_SESSION['stringlogin']);
                $stmt->execute();
                $stmt->store_result();
                if ($stmt->num_rows > 0) {
                    $stmt->bind_result($clave, $estado);
                    $stmt->fetch();
                    $login_check = hash('sha512', $clave . $user_browser);
                    if($estado == 1) {
                        if(hash_equals($login_check, $_SESSION['stringlogin'])) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }
    public function icon_ok() {
        return '<div class="icon-ok"></div>';
    }
    /* END - Login functions */
    public function getmedicodata($idmedico = '') {
        $idmedico = isset($_SESSION['iduser']) ? $_SESSION['iduser'] : $this->cleanvar($idmedico);
        $return = array();
        if($this->loginCheck) {
            $query = $this->mysqli->query('SELECT * FROM medico WHERE idmedico = "' . $idmedico . '"') or exit(__LINE__ . ':' . $this->mysqli->error);
            while($result = $query->fetch_array(MYSQLI_ASSOC)) {
                foreach($result as $column => $value) {
                    $return[$column] = html_entity_decode($value);
                }
            }
            $return['linea_pro_des_pro'] = array();
            $query = $this->mysqli->query('SELECT idlinea_pro_des_pro FROM medico_linea_pro_des_pro WHERE idmedico = "' . $idmedico . '"') or exit(__LINE__ . ':' . $this->mysqli->error);
            while($result = $query->fetch_array()) {
                array_push($return['linea_pro_des_pro'], $result['idlinea_pro_des_pro']);
            }
            $return['areas_tematicas'] = array();
            $query = $this->mysqli->query('SELECT idareas_tematicas FROM medico_areas_tematicas WHERE idmedico = "' . $idmedico . '"') or exit(__LINE__ . ':' . $this->mysqli->error);
            while($result = $query->fetch_array()) {
                array_push($return['areas_tematicas'], $result['idareas_tematicas']);
            }
            $return['areas_alertas'] = array();
            $query = $this->mysqli->query('SELECT idareas_alertas FROM medico_areas_alertas WHERE idmedico = "' . $idmedico . '"') or exit(__LINE__ . ':' . $this->mysqli->error);
            while($result = $query->fetch_array()) {
                array_push($return['areas_alertas'], $result['idareas_alertas']);
            }
        }
        return $return;
    }
    public function getoferentedata($idoferente = '') {
        $idoferente = isset($_SESSION['admin']) && isset($idoferente) && $_SESSION['admin'] == 1 && $idoferente != '' ? $this->cleanvar($idoferente) : (isset($_SESSION['idoferente']) ? $_SESSION['idoferente'] : 0);
        $return = array();
        if($this->checkUserOferente()) { 
            $query = $this->mysqli->query('SELECT * FROM oferente WHERE idoferente = "' . $idoferente . '"') or exit(__LINE__ . ':' . $this->mysqli->error);
            while($result = $query->fetch_array(MYSQLI_ASSOC)) {
                foreach($result as $column => $value) {
                    $return[$column] = html_entity_decode($value);
                }
            }
        }
        return $return;
    }
    public function checkUserOferente() {
        if($this->loginCheck && isset($_SESSION['idoferente']) && $_SESSION['idoferente'] != '') {
            if($stmt = $this->mysqli->prepare('SELECT idoferente FROM useroferente WHERE iduser = ? AND idoferente = ?')) {
                $stmt->bind_param('ss', $_SESSION['iduser'], $_SESSION['idoferente']);
                $stmt->execute();
                $stmt->store_result();
                if ($stmt->num_rows > 0) {
                    $stmt->bind_result($idoferente);
                    $stmt->fetch();
                    $stmt->close();
                    if($idoferente == $_SESSION['idoferente']) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    public function getofertadata($idoferente = '', $idoferta = '') {
        $idoferente = isset($_SESSION['admin']) && isset($idoferente) && $_SESSION['admin'] == 1 && $idoferente != '' ? $this->cleanvar($idoferente) : (isset($_SESSION['idoferente']) ? $_SESSION['idoferente'] : 0);
        $return = array();
        if($this->checkUserOferente()) { 
            $query = $this->mysqli->query('SELECT * FROM oferta WHERE idoferta = "' . $idoferta . '"') or exit(__LINE__ . ':' . $this->mysqli->error);
            while($result = $query->fetch_array(MYSQLI_ASSOC)) {
                foreach($result as $column => $value) {
                    $return[$column] = html_entity_decode($value);
                }
            }
        }
        return $return;
    }
    /* START - Form functions */
    public function formOpen($pg = '', $action = '', $id = 'uniqueForm') {
        $pg = $this->cleanPg($pg);
        return '<form action="index.php?pg=' . $pg . '&' . $action . '" id="' . $id . '" method="post" enctype="multipart/form-data" onsubmit="return validateForm(this);" novalidate><input type="hidden" name="token" value="' . $this->token . '">';
    }
    public function formClose() {
        return '</form>';
    }
    public function cleanPg ($pg) {
        return strpos($pg, '.php') !== false ? substr(basename($pg), 0, -4) : $pg;
    }
    protected function generateToken() {
        $this->token = hash('sha512', openssl_random_pseudo_bytes(16));
        $_SESSION['token'] = $this->token;
        return $this->token;
    }
    public function checkToken() {
        /*if(isset($_SESSION['token'], $_POST['token']) && $_SESSION['token'] == $_POST['token']) {
            return true;
        }
        $this->header('error=La validación del formulario no ha sido exitosa. Intente de nuevo.');
        return false; */
        return true;
    }
    public function checkCaptcha() {
        $captcha = isset($_POST['captcha']) ? hash('sha512', $_POST['captcha']) : 'null';
        $seesion_captcha = isset($_SESSION['captcha']) ? $_SESSION['captcha'] : 'null2';
        if(hash_equals($seesion_captcha, $captcha)) {
            return true;
        }
        $this->header((isset($_GET['pg']) ? 'pg=' . $this->cleanPg($_GET['pg']) : '') . '&error=El código de la imagen no es correcto. Intente de nuevo.');
        return false;
    }
    public function userIp() {
        $ipaddress = '';
        if (getenv('HTTP_CLIENT_IP')) {
            $ipaddress = getenv('HTTP_CLIENT_IP');
        } else if(getenv('HTTP_X_FORWARDED_FOR')) {
            $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
        } else if(getenv('HTTP_X_FORWARDED')) {
            $ipaddress = getenv('HTTP_X_FORWARDED');
        } else if(getenv('HTTP_FORWARDED_FOR')) {
            $ipaddress = getenv('HTTP_FORWARDED_FOR');
        } else if(getenv('HTTP_FORWARDED')) {
            $ipaddress = getenv('HTTP_FORWARDED');
        } else if(getenv('REMOTE_ADDR')) {
            $ipaddress = getenv('REMOTE_ADDR');
        } else {
            $ipaddress = 'UNKNOWN';
        }
        return $ipaddress;
    }
    /* END - Form functions */
    public function openPopup($id) {
        return '<div id="' . $id . '" class="popup"><a onclick="document.getElementById(\'' . $id . '\').style.display = \'none\'" class="popup-close btn error">Cerrar</a><div class="popup-body">';
    }
    public function closePopup() {
        return '</div></div>';
    }
    public function linea_pro_des_pro() {
        $return = array();
        if($stmt = $this->mysqli->prepare('SELECT idlinea_pro_des_pro, linea_pro_des_pro FROM linea_pro_des_pro ORDER BY linea_pro_des_pro ASC')) {
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows > 0) {
                $stmt->bind_result($idlinea_pro_des_pro, $linea_pro_des_pro);
                while($stmt->fetch()) {
                    $return[$idlinea_pro_des_pro] = $linea_pro_des_pro;
                }
            }
        }
        return $return;
    }
    public function areas_tematicas() {
        $return = array();
        if($stmt = $this->mysqli->prepare('SELECT idareas_tematicas, areas_tematicas FROM areas_tematicas ORDER BY areas_tematicas ASC')) {
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows > 0) {
                $stmt->bind_result($idareas_tematicas, $areas_tematicas);
                while($stmt->fetch()) {
                    $return[$idareas_tematicas] = $areas_tematicas;
                }
            }
        }
        return $return;
    }
    public function areas_alertas() {
        $return = array();
        if($stmt = $this->mysqli->prepare('SELECT idareas_alertas, areas_alertas FROM areas_alertas ORDER BY areas_alertas ASC')) {
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows > 0) {
                $stmt->bind_result($idareas_alertas, $areas_alertas);
                while($stmt->fetch()) {
                    $return[$idareas_alertas] = $areas_alertas;
                }
            }
        }
        return $return;
    }
    public function input($params, $options = array()) {
        $params['id'] = isset($params['name']) ? $params['name'] : 'undefined';
        $params['class'] = isset($params['class']) ? $params['class'] : 'input';
        $params['type'] = isset($params['type']) ? $params['type'] : 'text';
        $params['class'] = $params['type'] != 'file' ? $params['class'] : '';
        $required = false;
        $value = '';
        $attributes = '';
        foreach($params as $key => $val) {
            if($key == 'span') {
                $span = isset($params['span']) ? $params['span'] : 'undefined';
            } else if($key == 'required') {
                $required = $val === true ? true : false;
            } else if($key == 'value') {
                $value = $val;
            } else {
                if($val != '') {
                    $attributes .= ' ' . $key . '="' . $val . '" ';
                }
            }
        }
        $dataspan = $span;
        $return = '<span ' . ($required ? 'required' : '') . '>' . $span . ($params['type'] == 'file' && isset($params['accept']) && (strpos($params['accept'], 'pdf') !== false || strpos($params['accept'], 'doc') !== false) ? ' ('.$params['accept'].')' : '') . ':</span>';
        if($params['type'] == 'file' && file_exists($value)) {
            $return .= '<a href="' . $value . '" target="_blank">Consultar documento cargado &gt;&gt;</a><br />';
        }
        if($params['type'] == 'select') {
            $return .= '<select ' . $attributes . ' ' . ($required ? 'required' : '') . ' data-span="' . $dataspan . '"><option value="" ' . ($value == '' ? 'selected' : '') . '>--Seleccione--</option>';
            if(is_array($options)) {
                foreach($options as $key => $val) {
                    $return .= '<option value="' . $val . '" ' . ($value == $val ? 'selected' : '') . '>' . $val . '</option>';
                }
            }
            $return .= '</select>';
        } else if($params['type'] == 'textarea') {
            $return .= '<textarea ' . $attributes . ' ' . ($required ? 'required' : '') . ' data-span="' . $dataspan . '">' . $value . '</textarea>';
        } else {
            $return .= '<input ' . $attributes . ' ' . ($required ? 'required' : '') . ' ' . ($params['type'] == 'url' ? 'placeholder="https://"' : '') . ' data-span="' . $dataspan . '" ' . ($params['type'] != 'file' ? 'value="' . $value . '"' : '') . ' />';
        }
        return $return;
    }
    public function radio_si_no($name, $value = '') {
        return '<div class="onoffswitch"><input type="checkbox" name="' . $name . '" class="onoffswitch-checkbox toggle" id="' . $name . '" value="Si" ' . ($value == 'Si' ? 'checked' : '') . ' data-div="' . $name . '"><label class="onoffswitch-label" for="' . $name . '"><span class="onoffswitch-inner"></span><span class="onoffswitch-switch"></span></label></div>';
    }
    public function select_si_no_algunas($name, $value = '') {
        return '<select name="' . $name . '" class="input"><option value="">--Seleccione--</option><option value="Si" ' . ($value == 'Si' ? 'selected' : '') . '>Si</option><option value="No" ' . ($value == 'No' ? 'selected' : '') . '>No</option><option value="Algunas veces" ' . ($value == 'Algunas veces' ? 'selected' : '') . '>Algunas veces</option></select>';
    }
    public function ayuda_icon($text) {
        $id = mt_rand(1000,9999);
        return '<div class="tooltip icon-help" alt="' . $text . '" data-tip="' . $text . '" data-tipid="' . $id . '" data-copyright="Icons made by Roundicons [https://roundicons.com/] from Flaticon[www.flaticon.com]"><span class="tooltip-text" id="data-tipid-' . $id . '">' . $text . '</span></div>';
    }
    public function status($status = 0) {
        if($status == 1) {
            return '<img src="img/icon-ok.png" alt="Validado" title="Validado" class="img-status" />';
        } else if($status == 2) {
            return '<img src="img/icon-warning.png" alt="Observaciones" title="Observaciones" class="img-status" />';
        }
        return '<img src="img/icon-error.png" alt="Sin validar" title="Sin validar" class="img-status" />';
    }
    public function file_upload($file, $id, $dir) {
        $fileCheck = isset($_FILES[$file]) ? true : false;
        if($fileCheck === true && isset($_FILES[$file]["name"]) && $_FILES[$file]["name"] != '') {
            $fileOrigen = basename($_FILES[$file]["name"]);
            $fileExtention = strtolower(pathinfo($fileOrigen, PATHINFO_EXTENSION));
            $fileDestination = $dir . $id . '_' . date('YmdHis') . '.' . $fileExtention;
            if(move_uploaded_file($_FILES[$file]["tmp_name"], $fileDestination)) {
                return $fileDestination;
            }
        }
        return false;
    }
    public function popupOnClick($url = '') {
        return 'window.open(\'' . $url . '\',\'popUpWindow\',\'height=800,width=1000,left=5,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes\')';
    }
    private function redirect() {
        if(isset($_GET['logoutHandler'])) {
            return $this->logoutHandler();
        }
    }
    public function header($pg = '', $params = '?') {
        echo '
        Haga <a href="index.php?pg=' . $this->cleanPg($pg) . '&' . $params . '">clic aquí</a> para continuar.
        <script>window.location = "index.php?pg=' . $this->cleanPg($pg) . '&' . $params . '";</script>';
        exit;
    }
}
$main = new main($_GET, $_POST); ?>