<?php
/*
* Edited by:     Nermin Jukan, 63150367
* Date:          21. 05. 2018
* Modifications: Added a delete user function on lines 83-92.
*/

include_once("config.php");
require_once "DBconnect.php";

function errlog($message){
    error_log($message."\n", 3, "error.log");
}

/*function getDialects(){
    $query = ("SELECT `id`, `dialect_key`, `location_name`, `location_label`, `audio`, `location_latitude`, `location_longitude`, `metadata` FROM `dialect_entries`");
    $result = mysqli_query($mysqli, $query);
    $dialects = [];
    while($res = mysqli_fetch_object($result)) { 
        $dialects[] = $res;
    }
    return $dialects;
}*/

function getDialects(){
    $db = DBconnect::getInstance();

    $stmt = $db->prepare("SELECT `id`, `dialect_key`, `location_name`, `location_label`, `audio`, `location_latitude`, `location_longitude`, `metadata` FROM `dialect_entries`");

    $stmt->execute();

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    return $result;
}

/*function getDialect($mysqli, $id){
    $id = mysqli_real_escape_string($mysqli, $id);
    $query = "SELECT * FROM `dialect_entries` WHERE `id` = '$id'";
    $result = mysqli_query($mysqli, $query);
    $dialect = mysqli_fetch_object($result);
    return $dialect;
}*/

function getDialect($id){
    $db = DBconnect::getInstance();

    $stmt = $db->prepare("SELECT * FROM `dialect_entries` WHERE `id` = :id");

    $stmt->bindParam(":id", $id);

    $stmt->execute();

    $data = $stmt->fetch(PDO::FETCH_ASSOC);

    return $data;



}

/*function getAnalysis($mysqli, $id){
    $id = mysqli_real_escape_string($mysqli, $id);
    $query = "SELECT * FROM `analysis_items` WHERE `dialect_entry_id` = '$id'";
    $result = mysqli_query($mysqli, $query);
    $analysis = [];
    while($res = mysqli_fetch_object($result)) { 
        $analysis[] = $res;
    }
    return $analysis;
}*/

function getAnalysis($id){
    $db = DBconnect::getInstance();

    $stmt = $db->prepare("SELECT `id`, `dialect_entry_id`, `section`, `maintext`, `examples` FROM `analysis_items` WHERE `dialect_entry_id` = :id");

    $stmt->bindParam(":id", $id);

    $stmt->execute();

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    return $result;
}

/*function createAnalysisItem($mysqli, $dialect_id, $section_id){
    $stmt = mysqli_prepare($mysqli, "INSERT INTO `analysis_items` (`id`, `dialect_entry_id`, `section`, `maintext`, `examples`) VALUES (null, ?, ?, '', '')");
    mysqli_stmt_bind_param($stmt, 'ii', $dialect_id_b, $section_id_b);
    $dialect_id_b = mysqli_real_escape_string($mysqli, $dialect_id);
    $section_id_b = mysqli_real_escape_string($mysqli, $section_id);
    $result = mysqli_stmt_execute($stmt);
    if($result){
        $insert_id = mysqli_insert_id($mysqli);
        //errlog('Created new analysis item with id: ' . $insert_id);
        return array('success' => true, 'id' => $insert_id);
    } else {
        errlog('Failed creating analysis item! Err: ' . mysqli_error($mysqli) );
        return array('success' => false);
    }
}*/

function createAnalysisItem($dialect_id, $section_id){
    $db = DBconnect::getInstance();

    $stmt = $db->prepare("INSERT INTO `analysis_items` (`id`, `dialect_entry_id`, `section`, `maintext`, `examples`) VALUES (:id, :dial_id, :section, :main_text, :examples)");

    $stmt->bindParam(":id", $id);
    $stmt->bindParam(":dial_id", $dialect_id);
    $stmt->bindParam(":section", $section_id);
    $stmt->bindParam(":main_text", $main_text);
    $stmt->bindParam(":examples", $examples);

    $id = null;
    $main_text = '';
    $examples = '';

    $result = $stmt->execute();

    if($result){
        $insert_id = $db->lastInsertId();
        return array('success' => true, 'id' => $insert_id);
    }
    else{
        errlog('Failed creating analysis item! Err: ' . $db->errorInfo());
        return array('success' => false);
    }
}

/*function deleteAnalysisItem($mysqli, $analysis_id){
    $stmt = mysqli_prepare($mysqli, "DELETE FROM `analysis_items` WHERE id = ?");
    mysqli_stmt_bind_param($stmt, 'i', $id);
    $id = mysqli_real_escape_string($mysqli, $analysis_id);
    $result = mysqli_stmt_execute($stmt);
    if($result){
        return array('success' => true, 'id' => $id); 
    } else {
        return array('success' => false);
    }
}*/

function deleteAnalysisItem($analysis_id){
    $db = DBconnect::getInstance();

    $stmt = $db->prepare("DELETE FROM `analysis_items` WHERE `id` = :id");

    $stmt->bindParam(":id", $analysis_id);

    $result = $stmt->execute();

    if($result){
        return array('success' => true, 'id' => $analysis_id);
    } else {
        return array('success' => false);
    }
}

/*function deleteDialect($mysqli, $dialect_id){
    $dialect_id = mysqli_real_escape_string($mysqli, $dialect_id);
    $query = "DELETE FROM dialect_entries WHERE id = $dialect_id";
    $result = mysqli_query($mysqli, $query);
    if($result){
        return array('success' => true, 'id' => $dialect_id);
    } else {
        return array('success' => false);
    }
}*/

function deleteDialect($dialect_id){
    $db = DBconnect::getInstance();

    $stmt = $db->prepare("DELETE FROM dialect_entries WHERE `id` = :id");

    $stmt->bindParam(":id", $dialect_id);

    $result = $stmt->execute();

    if($result){
        return array('success' => true, 'id' => $dialect_id);
    } else {
        return array('success' => false);
    }
}

/*function deleteUser($mysqli, $user_id){
    $user_id = mysqli_real_escape_string($mysqli, $user_id);
    $query = "DELETE FROM `users` WHERE `id` = '$user_id'";
    $result = mysqli_query($mysqli, $query);
    if($result){
        return array('success' => true, 'id' => $user_id);
    } else {
        return array('success' => false);
    }
}*/

function deleteUser($user_id){
    $db = DBconnect::getInstance();

    $stmt = $db->prepare("DELETE FROM `users` WHERE `id` = :id");

    $stmt->bindParam(":id", $user_id);

    $result = $stmt->execute();

    if($result){
        return array('success' => true, 'id' => $user_id);
    } else {
        return array('success' => false);
    }
}

/*function updateDialect($mysqli, $resource_id, $put_data){
    // save dialect with prepared statements
    if(!is_null($resource_id) && $resource_id > 0 && isset($put_data) && isset($put_data->dialectData)){
        $query_dialect = "UPDATE dialect_entries SET dialect_key = ?, location_name = ?, location_label = ?, audio = ?, location_latitude = ?, location_longitude = ?, metadata = ?, transcription = ?, standard_slovene = ?, analysis1 = ?, analysis2 = ?, analysis3 = ?, analysis4 = ?, analysis5 = ?, analysis6 = ?, analysis7 = ?, modified = ?, modified_by = ? WHERE id = ?;";
        $stmt_dialect = mysqli_prepare($mysqli, $query_dialect);
        mysqli_stmt_bind_param($stmt_dialect, 'sssssssssssssssssii', $dialect_key, $location_name, $location_label, $audio, $location_latitude, $location_longitude, $metadata, $transcription, $standard_slovene, $analysis1, $analysis2, $analysis3, $analysis4, $analysis5, $analysis6, $analysis7, $modified, $modified_by, $id);
    
        $dialect_key = $put_data->dialectData->dialect_key ?: '';
        $location_name = $put_data->dialectData->location_name ?: '';
        $location_label = $put_data->dialectData->location_label ?: '';
        $audio = $put_data->dialectData->audio ?: '';
        $location_latitude = $put_data->dialectData->location_latitude ?: '0';
        $location_longitude = $put_data->dialectData->location_longitude ?: '0';
        $metadata = $put_data->dialectData->metadata ?: '/';
        $transcription = $put_data->dialectData->transcription ?: '';
        $standard_slovene = $put_data->dialectData->standard_slovene ?: '';
        $analysis1 = $put_data->dialectData->analysis1 ?: '';
        $analysis2 = $put_data->dialectData->analysis2 ?: '';
        $analysis3 = $put_data->dialectData->analysis3 ?: '';
        $analysis4 = $put_data->dialectData->analysis4 ?: '';
        $analysis5 = $put_data->dialectData->analysis5 ?: '';
        $analysis6 = $put_data->dialectData->analysis6 ?: '';
        $analysis7 = $put_data->dialectData->analysis7 ?: '';
        $modified = date('Y-m-d H:i:s');
        $modified_by = 1;
        $id = $resource_id;
        $result = mysqli_stmt_execute($stmt_dialect);

        if( mysqli_error($mysqli) ){
            errlog( mysqli_error($mysqli) );
        }

    } else {
        return array('success' => false, 'message' => 'Missing ID or PUT data');
    }
    
    $query_analysis = "UPDATE analysis_items SET dialect_entry_id = ?, section = ?, maintext = ?, examples = ? WHERE id = ?";
    $stmt_analysis = mysqli_prepare($mysqli, $query_analysis);
    mysqli_stmt_bind_param($stmt_analysis, 'iissi', $dialect_entry_id, $section, $maintext, $examples, $analysis_id);

    if( mysqli_error($mysqli) ){
        errlog( mysqli_error($mysqli) );
    }

    // fill analysis data
    $result_analysis = [];
    $SECTION_COUNT = 7;
    for($i=1; $i <= $SECTION_COUNT; $i++){
        if(isset($put_data->analysisData[$i])){
            $ITEM_COUNT = count($put_data->analysisData[$i]);
            for($j = 0; $j < $ITEM_COUNT; $j++){
                $dialect_entry_id = $resource_id;
                $section = $i;
                $maintext = $put_data->analysisData[$i][$j]->maintext;
                $examples = $put_data->analysisData[$i][$j]->examples;
                $analysis_id = $put_data->analysisData[$i][$j]->id;
                //errlog("Vse OK: $i,$j:" . json_encode($put_data->analysisData[$i][$j]));
                $result_analysis[] = mysqli_stmt_execute($stmt_analysis);
                if( mysqli_error($mysqli) ){
                    errlog( mysqli_error($mysqli) );
                }
            }
        }
    }

    if( mysqli_error($mysqli) ){
        return array('success' => false, 'message' => mysqli_error($mysqli));
    }
    return array('success' => $result);
}*/

function updateDialect($resource_id, $put_data){
    // save dialect with prepared statements
    if(!is_null($resource_id) && $resource_id > 0 && isset($put_data) && isset($put_data->dialectData)){

        $db = DBconnect::getInstance();

        $stmt = $db->prepare("UPDATE dialect_entries SET dialect_key = :d_key, location_name = :lo_name, location_label = :lo_label,
                                        audio = :audio, location_latitude = :lo_lat, location_longitude = :lo_lon, metadata = :meta,
                                        transcription = :trans, standard_slovene = :std_slo, analysis1 = :any1, analysis2 = :any2, analysis3 = :any3,
                                        analysis4 = :any4, analysis5 = :any5, analysis6 = :any6, analysis7 = :any7, modified = :mod, modified_by = :mod_by
                                        WHERE id = :id");

        $stmt->bindParam(":d_key", $dialect_key);
        $stmt->bindParam(":lo_name", $location_name);
        $stmt->bindParam(":lo_label", $location_label);
        $stmt->bindParam(":audio", $audio);
        $stmt->bindParam(":lo_lat", $location_latitude);
        $stmt->bindParam(":lo_lon", $location_longitude);
        $stmt->bindParam(":meta", $metadata);
        $stmt->bindParam(":trans", $transcription);
        $stmt->bindParam(":std_slo", $standard_slovene);
        $stmt->bindParam(":any1", $analysis1);
        $stmt->bindParam(":any2", $analysis2);
        $stmt->bindParam(":any3", $analysis3);
        $stmt->bindParam(":any4", $analysis4);
        $stmt->bindParam(":any5", $analysis5);
        $stmt->bindParam(":any6", $analysis6);
        $stmt->bindParam(":any7", $analysis7);
        $stmt->bindParam(":mod", $modified);
        $stmt->bindParam(":mod_by", $modified_by);
        $stmt->bindParam(":id", $id);

        $dialect_key = $put_data->dialectData->dialect_key ?: '';
        $location_name = $put_data->dialectData->location_name ?: '';
        $location_label = $put_data->dialectData->location_label ?: '';
        $audio = $put_data->dialectData->audio ?: '';
        $location_latitude = $put_data->dialectData->location_latitude ?: '0';
        $location_longitude = $put_data->dialectData->location_longitude ?: '0';
        $metadata = $put_data->dialectData->metadata ?: '';
        $transcription = $put_data->dialectData->transcription ?: '';
        $standard_slovene = $put_data->dialectData->standard_slovene ?: '';
        $analysis1 = $put_data->dialectData->analysis1 ?: '';
        $analysis2 = $put_data->dialectData->analysis2 ?: '';
        $analysis3 = $put_data->dialectData->analysis3 ?: '';
        $analysis4 = $put_data->dialectData->analysis4 ?: '';
        $analysis5 = $put_data->dialectData->analysis5 ?: '';
        $analysis6 = $put_data->dialectData->analysis6 ?: '';
        $analysis7 = $put_data->dialectData->analysis7 ?: '';
        $modified = date('Y-m-d H:i:s');
        $modified_by = 1;
        $id = $resource_id;

        $result = $stmt->execute();

        if( !$result ){
            errlog( $db->errorInfo() );
        }

    } else {
        return array('success' => false, 'message' => 'Missing ID or PUT data');
    }

    $stmt_analysis = $db->prepare("UPDATE analysis_items SET dialect_entry_id = :entry_id, section = :section, maintext = :maintext, examples = :examples WHERE id = :id");

    $stmt_analysis->bindParam(":entry_id", $dialect_entry_id);
    $stmt_analysis->bindParam(":section", $section);
    $stmt_analysis->bindParam(":maintext", $maintext);
    $stmt_analysis->bindParam(":examples", $examples);
    $stmt_analysis->bindParam(":id", $analysis_id);

    if( !$stmt_analysis ){
        errlog( $db->errorInfo() );
    }

    // fill analysis data
    $result_analysis = [];
    $SECTION_COUNT = 7;
    for($i=1; $i <= $SECTION_COUNT; $i++){
        if(isset($put_data->analysisData[$i])){
            $ITEM_COUNT = count($put_data->analysisData[$i]);
            for($j = 0; $j < $ITEM_COUNT; $j++){
                $dialect_entry_id = $resource_id;
                $section = $i;
                $maintext = $put_data->analysisData[$i][$j]->maintext;
                $examples = $put_data->analysisData[$i][$j]->examples;
                $analysis_id = $put_data->analysisData[$i][$j]->id;
                //errlog("Vse OK: $i,$j:" . json_encode($put_data->analysisData[$i][$j]));
                $result_analysis[] = $stmt_analysis->execute();
                if( !$result_analysis ){
                    errlog( $db->errorInfo() );
                }
            }
        }
    }

    if( !$result_analysis ){
        return array('success' => false, 'message' => $db->errorInfo());
    }
    return array('success' => $result);
}

/*function createDialect($mysqli){ // create empty entry
    $query = "INSERT INTO dialect_entries (metadata,transcription,standard_slovene,analysis1,analysis2,analysis3,analysis4,analysis5,analysis6,analysis7,created_by) VALUES ('','','','','','','','','', '', '1')";
    if (mysqli_query($mysqli, $query)) {
        $insert_id = mysqli_insert_id($mysqli);
        return array('success' => true, 'message' => 'New record created successfully', 'id' => $insert_id);
    } else {
        return array('success' => false, 'message' => mysqli_error($mysqli));
    }

}*/

function createDialect(){ // create empty entry
    $db = DBconnect::getInstance();

    $stmt = $db->prepare("INSERT INTO dialect_entries (metadata,transcription,standard_slovene,analysis1,analysis2,analysis3,analysis4,analysis5,analysis6,analysis7,created_by) VALUES (:meta, :transcript, :std_slo, :analy1, :analy2, :analy3, :analy4, :analy5, :analy6, :analy7, :created_by)");

    $stmt->bindParam(":meta", $meta);
    $stmt->bindParam(":transcript", $transcript);
    $stmt->bindParam(":std_slo", $std_slo);
    $stmt->bindParam(":analy1", $analy1);
    $stmt->bindParam(":analy2", $analy2);
    $stmt->bindParam(":analy3", $analy3);
    $stmt->bindParam(":analy4", $analy4);
    $stmt->bindParam(":analy5", $analy5);
    $stmt->bindParam(":analy6", $analy6);
    $stmt->bindParam(":analy7", $analy7);
    $stmt->bindParam(":created_by", $created_by);

    $meta = '';
    $transcript = '';
    $std_slo = '';
    $analy1 = '';
    $analy2 = '';
    $analy3 = '';
    $analy4 = '';
    $analy5 = '';
    $analy6 = '';
    $analy7 = '';
    $created_by = '1';

    $result = $stmt->execute();

    if($result){
        $insert_id = $db->lastInsertId();
        return array('success' => true, 'id' => $insert_id);
    }
    else{
        errlog('Failed creating dialect item! Err: ' . $db->errorInfo());
        return array('success' => false);
    }

}

/*function saveAudio($mysqli, $resource_id, $file){
    $upload_dir = '/resources/audio/';
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $file_name = $resource_id.'.'.$extension;
    $relative_path = $upload_dir . $file_name;
    $absolute_path = $_SERVER['DOCUMENT_ROOT'] . APP_PATH . $relative_path;

    if (move_uploaded_file($file['tmp_name'], $absolute_path)) {
        $query = "UPDATE dialect_entries SET audio = ? WHERE id = ?";
        $stmt_audio = mysqli_prepare($mysqli, $query);
        mysqli_stmt_bind_param($stmt_audio, 'si', $audio_path, $id);

        $audio_path = $relative_path;
        $id = $resource_id;

        $result = mysqli_stmt_execute($stmt_audio);
        if($result){
            return array('success' => true, 'message' => 'File uploaded and saved in database');
        } else {
            return array('success' => false, 'message' => 'Error saving audio in database');
        }
    } else {
        return array('success' => false, 'message' => 'Possible file upload attack!', 'info' =>  $file['error'], 'files' => $_FILES );
    }
}*/

function saveAudio($resource_id, $file){

    $rand = rand(1, 1000);

    $upload_dir = '/resources/audio/';
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $real_file_name = pathinfo($file['name'], PATHINFO_FILENAME);
    $file_name = $resource_id . '_' . $real_file_name . '.' . $extension;
    $relative_path = $upload_dir . $file_name;
    $absolute_path = $_SERVER['DOCUMENT_ROOT'] . APP_PATH . $relative_path;

    $db = DBconnect::getInstance();
    /*$stmt1 = $db->prepare("SELECT `audio` FROM `dialect_entries` WHERE `id` = :id");
    $stmt1->bindParam(":id", $resource_id);
    $stmt1->execute();
    $data = $stmt1->fetch(PDO::FETCH_NUM);

    if($data){
        if(file_exists($_SERVER['DOCUMENT_ROOT'] . APP_PATH . $data[0])){
            $exists = file_exists($_SERVER['DOCUMENT_ROOT'] . APP_PATH . $data[0]);//, $_SERVER['DOCUMENT_ROOT'] . APP_PATH . $data[0] . 'OLD');
            $rename = move_uploaded_file($_SERVER['DOCUMENT_ROOT'] . APP_PATH . $data[0], $_SERVER['DOCUMENT_ROOT'] . APP_PATH . $data[0] . 'OLD');
            $unlink = unlink($_SERVER['DOCUMENT_ROOT'] . APP_PATH . $data[0]);
        }
    }*/

    if (move_uploaded_file($file['tmp_name'], $absolute_path)) {

        $stmt2 = $db->prepare("UPDATE dialect_entries SET audio = :audio WHERE id = :id");
        $stmt2->bindParam(":audio", $audio_path);
        $stmt2->bindParam(":id", $id);

        $audio_path = $relative_path;
        $id = $resource_id;

        $result = $stmt2->execute();

        if($result){
            return array('success' => true, 'message' => 'Saved.');//, 'UNLINK' => $unlink);
        } else {
            return array('success' => false, 'message' => 'Error saving audio in database');
        }
    } else {
        return array('success' => false, 'message' => 'Possible file upload attack!', 'info' =>  $file['error'], 'files' => $_FILES );
    }
}

function deleteAudio($resource_id){
    $db = DBconnect::getInstance();

    $stmt = $db->prepare("SELECT `audio` FROM `dialect_entries` WHERE `id` = :id");

    $stmt->bindParam(":id", $resource_id);

    $stmt->execute();

    $data = $stmt->fetch();

    if(isset($data['audio']) && $data['audio'] !== ''){
        $absolute_path = $_SERVER['DOCUMENT_ROOT'] . APP_PATH . $data['audio'];
        if(file_exists($absolute_path)){
            $return = unlink($absolute_path);
        }
        else{
            return array('success' => true, 'message' => 'File does not exit, continue upload.');
        }
        if($return){
            $stmt2 = $db->prepare("UPDATE dialect_entries SET audio = :audio WHERE id = :id");

            $stmt2->bindParam(":id", $resource_id);
            $stmt2->bindParam(":audio", $audio);

            $audio = '';

            $result2= $stmt2->execute();

            if($result2){
                return array('success' => true, 'id' => $resource_id, 'data' => $data[0]);
            } else {
                $db = null;
                return array('success' => false, 'message' => 'DIR update failure');
            }
        } else {
            return array('success' => false, 'message' => 'Unlink failure.', 'link' => $absolute_path);
        }
    } else {
        return array('success' => false, 'message' => 'Fetching DIR from DB failure or no DIR.');
    }
}

/*function checkCredentials($mysqli, $username, $password){
    $username = mysqli_real_escape_string($mysqli, $username);
    $query = "SELECT `password` FROM `users` WHERE `username` = '$username'";
    $result = mysqli_query($mysqli, $query);
    $user = mysqli_fetch_object($result);
    if($user){
        $password_hash = $user->password;
        if(password_verify($password, $password_hash)){
            return true;
        } else {
            return "Staro geslo ni pravilno.";
        }
    } else {
        return "Uporabnik ne obstaja.";
    }
}*/

function checkCredentials($username, $password){
    $db = DBconnect::getInstance();

    $stmt = $db->prepare("SELECT COUNT(`password`) AS password FROM `users` WHERE `username` = :username");

    $stmt->bindParam(":username", $username);

    $stmt->execute();

    $num = $stmt->fetch(PDO::FETCH_NUM);

    if($num[0] == 1){
        $checkPass = $db->prepare("SELECT password FROM `users` WHERE `username` = :username");
        $checkPass->bindParam(":username", $username);
        $checkPass->execute();
        $result = $checkPass->fetch(PDO::FETCH_NUM);
        $password_hash = $result[0];

        if(password_verify($password, $password_hash)){
            return true;
        } else {
            return "Geslo ni pravilno.";
        }
    } else {
        return "Uporbnik ne obstaja.";
    }
}

function getAdmin($username){
    $db = DBconnect::getInstance();

    $stmt = $db->prepare("SELECT `is_admin` FROM `users` WHERE `username` = :username");

    $stmt->bindParam(":username", $username);

    $stmt->execute();

    $isAdmin = $stmt->fetch();

    return $isAdmin;

}

/*function changePassword( $mysqli, $username, $new_password ){
    $username = mysqli_real_escape_string($mysqli, $username);
    $new_password = password_hash( $new_password, PASSWORD_DEFAULT );
    $query = "UPDATE `users` SET `password` = '$new_password' WHERE `username` = '$username'";
    $result = mysqli_query($mysqli, $query);
    if($result === true){
        return true;
    }
    return false;
}*/

function changePassword($username, $new_password){
    $new_password = password_hash( $new_password, PASSWORD_DEFAULT );

    $db = DBconnect::getInstance();

    $stmt = $db->prepare("UPDATE `users` SET `password` = :newpassword WHERE `username` = :username");

    $stmt->bindParam("newpassword", $new_password);
    $stmt->bindParam("username", $username);

    $result = $stmt->execute();

    if($result){
        return true;
    }
    return false;
}

/*function getUsers($mysqli){
    $query = "SELECT `id`, `name`, `username`, `is_admin` FROM `users`";
    $result = mysqli_query($mysqli, $query);
    $users = [];
    while($res = mysqli_fetch_object($result)) { 
        $users[] = $res;
    }
    return $users;
}*/

function getUsers(){
    $db = DBconnect::getInstance();

    $stmt = $db->prepare("SELECT `id`, `name`, `username`, `is_admin` FROM `users`");

    $stmt->execute();

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    return $result;
}

/*function addUser($mysqli, $post_data){
    $name = mysqli_real_escape_string($mysqli, $post_data->name);
    $username = mysqli_real_escape_string($mysqli, $post_data->username);
    $is_admin = mysqli_real_escape_string($mysqli, $post_data->is_admin);
    $password = $post_data->password;
    $password_repeat = $post_data->password_repeat;

    //return array('success' => false, 'message' => $post_data);

    if($password != $password_repeat){
        return array('success' => false, 'message' => "Gesli se ne ujemata.");
    }

    

    if( strlen($name) < 3){
        return array('success' => false, 'message' => "Ime $name mora vsebovati vsaj 3 znake.");
    }
    if( strlen($username) < 3){
        return array('success' => false, 'message' => "Uporabniško ime mora vsebovati vsaj 3 znake.");
    }
    if( strlen($password) < 8){
        return array('success' => false, 'message' => "Geslo mora vsebovati vsaj 8 znakov.");
    }

    $password = password_hash($password, PASSWORD_DEFAULT);

    $query = "INSERT INTO `users` (`name`, `username`, `password`, `is_admin`) VALUES ('$name', '$username', '$password','$is_admin')";
    if (mysqli_query($mysqli, $query)) {
        $insert_id = mysqli_insert_id($mysqli);
        return array('success' => true, 'message' => "Uporabnik $username je bil uspešno ustvarjen.", 'id' => $insert_id);
    } else {
        return array('success' => false, 'message' => mysqli_error($mysqli));
    }

}*/

function addUser($post_data){
    $name = $post_data->name;
    $username = $post_data->username;
    $is_admin = $post_data->is_admin;
    $password = $post_data->password;
    $password_repeat = $post_data->password_repeat;

    if($password != $password_repeat){
        return array('success' => false, 'message' => "Gesli se ne ujemata.");
    }

    if( strlen($name) < 3){
        return array('success' => false, 'message' => "Ime $name mora vsebovati vsaj 3 znake.");
    }
    if( strlen($username) < 3){
        return array('success' => false, 'message' => "Uporabniško ime mora vsebovati vsaj 3 znake.");
    }
    if( strlen($password) < 8){
        return array('success' => false, 'message' => "Geslo mora vsebovati vsaj 8 znakov.");
    }

    $password = password_hash($password, PASSWORD_DEFAULT);

    $db = DBconnect::getInstance();

    $stmt = $db->prepare("INSERT INTO `users` (`name`, `username`, `password`, `is_admin`) VALUES (:name, :username, :password, :isadmin)");

    $stmt->bindParam("name", $name);
    $stmt->bindParam("username", $username);
    $stmt->bindParam("password", $password);
    $stmt->bindParam("isadmin", $is_admin);


    $result = $stmt->execute();
    if ($result) {
        $insert_id = $db->lastInsertId();
        return array('success' => true, 'message' => "Uporabnik $username je bil uspešno ustvarjen.", 'id' => $insert_id);
    } else {
        return array('success' => false, 'message' => $db->errorInfo());
    }

}
