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

header('Content-Type: application/json');
header('Allow: HEAD, OPTIONS, GET, POST, PUT, DELETE');
header('Access-Control-Allow-Methods: HEAD, OPTIONS, GET, POST, PUT, DELETE');
include_once("model.php");

if (isset($_SERVER['ORIG_PATH_INFO'])){
    $_SERVER['PATH_INFO'] = $_SERVER['ORIG_PATH_INFO'];
}

if( !isset($_SERVER['PATH_INFO']) ){
    $info = array(
        "name" => "interaktivna-karta-slovenskih-narecnih-besedil",
        "version" => "0.10.0",
        /*"endpoints" => array(
            array(
                "action" => "GET Dialects",
                "route" => "/dialects",
                "example" => $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['SERVER_NAME']. "/api/dialects"
            ),
            array(
                "action" => "GET Dialect by Id",
                "route" => "/dialects/{:id}",
                "example" => $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['SERVER_NAME']."/api/dialects/1"
            ),
            array(
                "action" => "All the rest",
                "route" => "TODO",
                "example" => "SOON"
            )
        )*/
    );
    die( json_encode($info) );
}

$verb = $_SERVER['REQUEST_METHOD'];
$url_elements = explode('/', $_SERVER['PATH_INFO']);

$resource = isset($url_elements[1]) ? $url_elements[1] : false;
$resource_id = isset($url_elements[2]) ? intval($url_elements[2]) : false;
$resource2 = isset($url_elements[3]) ? $url_elements[3] : false;
$resource2_id = isset($url_elements[4]) ? intval($url_elements[4]) : false;


// authentication api calls
if($resource == 'authenticate'){
    $post_data = json_decode( file_get_contents("php://input") );
    if( isset($post_data->username) && isset($post_data->password) ){
        $result = checkCredentials($post_data->username, $post_data->password);
        if($result === true){
            die( json_encode( array( 'success' => true, 'message' => 'Prijava je bila uspešna.' ) ) );
        } else {
            die( json_encode( array( 'success' => false, 'message' => $result ) ) );
        }
    } else {
        die( json_encode( array( 'success' => false, 'message' => 'Vnesti morate uporabniško ime in geslo.' ) ) );
    }
} else if($resource != 'dialects' && $resource != 'changePassword' && $resource != 'users' && $resource != 'admin'){
    die( json_encode( array( 'success' => false, 'message' => 'Resource does not exist - no res.') ) );
}

if($verb === 'GET'){
    $return = array("error" => "Resource does not exist - not admin."); // default

    if($resource == 'dialects'){
        // get dialects list
        if(!$resource_id){ 
            $return = getDialects();
        }
        // get dialect by id
        if($resource_id > 0 && !$resource2){
            $return = getDialect($resource_id);
        }
        // get analysis list by dialect id
        if($resource_id > 0 && $resource2 === 'analysis'){
            $return = getAnalysis($resource_id);
        }

        echo json_encode($return);
        die(); // GET is publicly allowed. POST, PUT, DELETE below is only for admins, so we stop here
    }
}

$isAdmin = false;
$username = false;
$headers = apache_request_headers();
if(isset($headers['Authorization'])){
  $matches = array();
  preg_match('/Basic (.*)/', $headers['Authorization'], $matches);
  if(isset($matches[1])){
    $token = $matches[1];
    $credentials = explode(":", base64_decode($token));
    $username = $credentials[0];
    $password = $credentials[1];
    if(checkCredentials($username, $password) === true){
        $isAdmin = true;
    }
  }
}

// from here on only admins allowed
if($isAdmin !== true){
    die( json_encode( array( 'success' => false, 'message' => 'Authorised users only.' ) ) );
}

if($resource == 'users'){
    if($verb === 'GET'){
        $return = getUsers();
        die( json_encode($return) );
    } elseif($verb === 'POST'){
        $post_data = json_decode( file_get_contents("php://input") );
        $return = addUser($post_data);
        die( json_encode($return) );
    }
    elseif($verb === 'DELETE'){
        if($resource_id > 0){
            $return = deleteUser($resource_id);
            die( json_encode($return) );
        }
    }
}

if($resource == 'admin'){
    if($verb === 'POST'){
        $post_data = json_decode( file_get_contents("php://input") );
        $return = getAdmin($post_data->username);
        die( json_encode($return) );
    }
    else{
        return;
    }
}

// password change
if($resource == 'changePassword'){
    $post_data = json_decode( file_get_contents("php://input") );
    if( checkCredentials($username, $post_data->old_password) !== true ){
        die( json_encode( array( 'success' => false, 'message' => 'Staro geslo ni pravilno.' ) ) );
    }
    if($post_data->new_password !== $post_data->new_password_repeat){
        die( json_encode( array( 'success' => false, 'message' => 'Novi gesli se ne ujemata' ) ) );
    }
    if(strlen($post_data->new_password) < 8){
        die( json_encode( array( 'success' => false, 'message' => 'Novo geslo mora vsebovati vsaj 8 znakov.' ) ) );
    }
    if( changePassword($username, $post_data->new_password ) ){
        die( json_encode( array( 'success' => true, 'message' => 'Geslo je bilo uspešno spremenjeno.' ) ) );
    } else {
        die( json_encode( array( 'success' => false, 'message' => 'Sprememba gesla ni bila uspešna.' ) ) );
    }
}

if($verb === 'POST'){
    $post_data = json_decode( file_get_contents("php://input") );
    if($resource_id > 0 && $resource2 === 'analysis'){ // create empty analysis item
        if(isset($post_data->section_id) && $post_data->section_id > 0){ // create item
            $section_id = intval($post_data->section_id);
            $return = createAnalysisItem($resource_id, $section_id);
        } else {
            $return = array("error" => "Create operation requires section id.");
        }
    }
    if($resource_id > 0 && $resource2 === 'files'){
        $return = saveAudio($resource_id, $_FILES['file']);
    }
    if(!$resource_id){ // create new dialect
        $return = createDialect();
    }
}

if($verb === 'PUT'){
    if($resource_id > 0){ // update existing dialect
        $put_data = json_decode( file_get_contents("php://input") );
        $return = updateDialect($resource_id, $put_data);
    } else {
        $return = array("error" => "Update operation requires dialect ID.");
    }
}

if($verb === 'DELETE'){
    // delete analysis item
    if($resource_id > 0 && $resource2 === 'analysis' && $resource2_id > 0){
        $return = deleteAnalysisItem($resource2_id);
    }
    if($resource2 === 'audio' && $resource_id > 0){
        $return = deleteAudio($resource_id);
    }
    if($resource_id > 0 && !$resource2){
        deleteAudio($resource_id);
        $return = deleteDialect($resource_id);
    }

}
//die( json_encode( array('test' => $return ) ) );
echo json_encode($return);