<?php
class administration extends mysqliConn {
    private $main;
    private $mysqli;
    function __construct($main) {
        $this->mysqli = parent::dbconn();
        $this->main = $main;
        if($main->adminCheck !== true) {
            exit;
        }
        $this->redirect();
    }
    private function redirect() {
        if(isset($this->_GET['saveSubject'])) {
            return $this->saveSubject();
        } else if(isset($this->_GET['saveProfile'])) {
            return $this->saveProfile();
        } else if(isset($this->_GET['saveSite'])) {
            return $this->saveSite();
        } else if(isset($this->_GET['saveSubjectDocument'])) {
            return $this->saveSubjectDocument();
        }
    }
    private function saveSubject() {
        $suc = '';
        $err = '';
        if($this->main->checkToken) {
            $idsubject = isset($this->_POST['idsubject']) ? (int) $this->_POST['idsubject'] : 0;
            $subject = isset($this->_POST['subject']) ? $this->_POST['subject'] : '';
            $profile = isset($this->_POST['profile']) ? $this->_POST['profile'] : '';
            if($idsubject > 0) {
                $status = isset($this->_POST['status']) ? (int) $this->_POST['status'] : 0;
                if($stmt = $this->mysqli->prepare("UPDATE subject SET subject = ?, profile = ?, status = ? WHERE idsubject = ?")) {
                    $stmt->bind_param("ssii", $subject, $profile, $status, $idsubject);
                    $stmt->execute();
                } else {
                    $err .= html_entity_decode($this->mysqli->error);
                }
                $suc = 'Se ha editado la especialidad.';
            } else {
                if($stmt = $this->mysqli->prepare("INSERT INTO subject(subject, profile) VALUES (?, ?)")) {
                    $stmt->bind_param("ss", $subject, $profile);
                    $stmt->execute();
                    $idsubject = $stmt->insert_id;
                } else {
                    $err .= html_entity_decode($this->mysqli->error);
                }
                $suc = 'Se ha creado la especialidad.';
            }
            if($idsubject > 0) {
                $stepverificationArray = array();
                foreach($this->main->users() as $iduser => $dataUser) {
                    $stepverificationArray[$iduser] = 0;
                    $sql = 'SELECT stepverification FROM usersubject WHERE iduser = ' . $iduser . ' AND idsubject = ' . $idsubject;
                    $consulta = $this->mysqli->query($sql) or $this->header('index.php', '?err=' . html_entity_decode(__LINE__ . $this->mysqli->error));
                    while($resultado = $consulta->fetch_array()) {
                        $stepverificationArray[$iduser] = $resultado['stepverification'];
                    }
                }
                if($stmt = $this->mysqli->prepare('DELETE FROM usersubject WHERE idsubject = ?')) {
                    $stmt->bind_param('i', $idsubject);
                    $stmt->execute();
                    $idusercont = isset($this->_POST['idusercont']) ? (int) $this->_POST['idusercont'] : 0;
                    for($cont=1; $cont<=$idusercont; $cont++) {
                        $iduser = isset($this->_POST['iduser' . $cont]) ? (int) $this->_POST['iduser' . $cont] : 0;
                        if($iduser > 0) {
                            $stepverification = isset($stepverificationArray[$iduser]) ? $stepverificationArray[$iduser] : 0;
                            if($stmt = $this->mysqli->prepare('INSERT INTO usersubject(iduser, idsubject, stepverification) VALUES(?, ?, ?)')) {
                                $stmt->bind_param('iii', $iduser, $idsubject, $stepverification);
                                $stmt->execute();
                                $stmt->store_result();
                            } else {
                                $err .= html_entity_decode($this->mysqli->error);
                            }
                        }
                    }
                } else {
                    $err .= html_entity_decode($this->mysqli->error);
                }
            }
            $this->main->header('', '?suc=' . $suc);
        } else {
            $err .= 'La validación del formulario no ha sido exitosa. Intente de nuevo.';
        }
        $this->main->header('', '?err=' . $err);
    }
    private function saveProfile() {
        $suc = '';
        $err = '';
        if($this->main->checkToken) {
            $idprofile = isset($this->_POST['idprofile']) ? (int) $this->_POST['idprofile'] : 0;
            $profile = isset($this->_POST['profile']) ? $this->_POST['profile'] : '';
            if($idprofile > 0) {
                $status = isset($this->_POST['status']) ? (int) $this->_POST['status'] : 0;
                if($stmt = $this->mysqli->prepare("UPDATE profile SET profile = ? WHERE idprofile = ?")) {
                    $stmt->bind_param("si", $profile, $idprofile);
                    $stmt->execute();
                } else {
                    $err .= html_entity_decode($this->mysqli->error);
                }
                $suc = 'Se ha editado el perfil.';
            } else {
                if($stmt = $this->mysqli->prepare("INSERT INTO profile(profile) VALUES (?)")) {
                    $stmt->bind_param("s", $profile);
                    $stmt->execute();
                    $idprofile = $stmt->insert_id;
                } else {
                    $err .= html_entity_decode($this->mysqli->error);
                }
                $suc = 'Se ha creado el perfil.';
            }
            if($idprofile > 0) {

                    $idusercont = isset($this->_POST['idusercont']) ? (int) $this->_POST['idusercont'] : 0;
                    for($cont=1; $cont<=$idusercont; $cont++) {
                        $iduser = isset($this->_POST['iduser' . $cont]) ? (int) $this->_POST['iduser' . $cont] : 0;
                        if($iduser > 0) {
                            if($stmt = $this->mysqli->prepare('UPDATE user SET idprofile = ? WHERE iduser = ?')) {
                                $stmt->bind_param('ii', $idprofile, $iduser);
                                $stmt->execute();
                                $stmt->store_result();
                            } else {
                                $err .= html_entity_decode($this->mysqli->error);
                            }
                        }
                    }
                    
                
            }
            $this->main->header('', '?suc=' . $suc);
        } else {
            $err .= 'La validación del formulario no ha sido exitosa. Intente de nuevo.';
        }
        $this->main->header('', '?err=' . $err);
    }
    public function saveSubjectDocument() {
        $err = '';
        $suc = '';
        $idsubject = isset($this->_POST['idsubject']) ? (int) $this->_POST['idsubject'] : 0;
        $idsubjectdocument = isset($this->_POST['idsubjectdocument']) ? (int) $this->_POST['idsubjectdocument'] : 0 ;
        $title = isset($this->_POST['title']) ? $this->_POST['title'] : '';
        $description = isset($this->_POST['description']) ? $this->_POST['description'] : '';
        $typepath = isset($this->_POST['typepath']) ? $this->_POST['typepath'] : '';
        $path = '';
        $private = isset($this->_POST['private']) ? (int) $this->_POST['private'] : 0;
        if($typepath == 'url') {
            $path = isset($this->_POST['pathurl']) ? $this->_POST['pathurl'] : '';
        } else if($typepath == 'file') {
            $pathfileCheck = isset($_FILES['pathfile']) ? true : '';
            $pathfile = '';
            if($pathfileCheck === true && isset($_FILES["pathfile"]["name"]) && $_FILES["pathfile"]["name"] != '') {
                $pathfile_origen = basename($_FILES["pathfile"]["name"]);
                $pathfile_extension = strtolower(pathinfo($pathfile_origen,PATHINFO_EXTENSION));
                $pathfile_destino = $this->main->documentsPath . date('YmdHis') . mt_rand(1000000000, 9999999999) . '.' . $pathfile_extension;
                if(move_uploaded_file($_FILES["pathfile"]["tmp_name"], $pathfile_destino)) {
                     $path = $pathfile_destino;
                }
            }
        }
        if($idsubject > 0) {
            if($idsubjectdocument > 0) {
                if($stmt = $this->mysqli->prepare('UPDATE subjectdocument SET idsubject = ?, iduser = ?, title = ?, description = ?, private = ? WHERE idsubjectdocument = ?')) {
                    $stmt->bind_param('iissii', $idsubject, $this->_SESSION['iduser'], $title, $description, $private, $idsubjectdocument);
                    $stmt->execute();
                    $stmt->store_result();
                    if($path != '') {
                        if($stmt = $this->mysqli->prepare('UPDATE subjectdocument SET path = ?, typepath = ? WHERE idsubjectdocument = ?')) {
                            $stmt->bind_param('ssi', $path, $typepath, $idsubjectdocument);
                            $stmt->execute();
                            $stmt->store_result();
                        } else {
                            $err .= html_entity_decode($this->mysqli->error);
                        }
                    }
                    $suc = 'Se ha editado el documento';
                } else {
                    $err .= html_entity_decode($this->mysqli->error);
                }
            } else {
                if($path != '') {
                    if($stmt = $this->mysqli->prepare('INSERT INTO subjectdocument(idsubject, iduser, title, description, path, typepath, private) VALUES(?, ?, ?, ?, ?, ?, ?)')) {
                        $stmt->bind_param('iissssi', $idsubject, $this->_SESSION['iduser'], $title, $description, $path, $typepath, $private);
                        $stmt->execute();
                        $stmt->store_result();
                        $suc = 'Se ha cargado el documento';
                    } else {
                        $err .= html_entity_decode($this->mysqli->error);
                    }
                } else {
                    $err .= 'Error guardando el documento.';
                }
            }
        }
        if($err == '') {
            $this->main->header('', '?idsubject='.$idsubject.'&suc=' . $suc);
        } else {
            $this->main->header('', '?idsubject='.$idsubject.'&err=' . $err);
        }
    }
}
$administration = new administration($main);