<?php
/*
  THIS IS THE USER ENTRY POINT API
 */
require '../../backend.php';
require '../backend_defines.php';
//var_dump($mermsemr->cfgReadChar("database.host"));
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    $headers = getallheaders();
    header('Access-Control-Allow-Origin: ' . (isset($headers["Origin"]) ? $headers["Origin"] : '*'));
    header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
    header('Access-Control-Allow-Headers: access-control-allow-methods,access-control-allow-origin,content-type');
    //header('Access-Control-Max-Age: 1728000');
    header('Content-Length: 0');
    header('Content-Type: text/plain');
    die();
}
header('Access-Control-Allow-Headers: access-control-allow-methods,access-control-allow-origin,content-type');
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

$endpoints = array(
    'createuser' => array('POST'),
    'login' => array('POST'),
    'userlogin' => array('POST'),
    'getprofile' => array('POST'),
    'setprofile' => array('POST'),
    'userstask' => array('POST'),
    'createtask' => array('POST'),
    'deletetask' => array('POST'),
    'getpractice' => array('POST'),
    'userencounter' => array('POST')
);
/*
  header("Access-Control-Allow-Origin: *");
  header("Access-Control-Expose-Headers: Access-Control-Allow-Origin");
  header("Access-Control-Allow-Headers: Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
  header("Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS");
  header('Content-type: application/json');
 */
$endpoint = strtolower(str_replace('/api/users/', '', strtok($_SERVER['REQUEST_URI'], '?')));

if (!isset($endpoints[$endpoint])) {
    header('HTTP/1.1 400 Bad Request');
    header('Status: 400 Bad Request');
    echo "{\"status\":\"Invalid endpoint url\"}";
    exit();
}

$methods = $endpoints[$endpoint];

if (array_search($_SERVER['REQUEST_METHOD'], $methods) === false) {
    header('HTTP/1.1 405 Method Not Allowed');
    header('Status: 405 Method Not Allowed');
    echo "{\"status\":\"Invalid request method\"}";
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if ($endpoint == "uploadfile") {
        upload_file_call();
        exit();
    } else {
        $raw_json = file_get_contents("php://input");
        $raw_array = json_decode($raw_json, true);
        $in = flatten($raw_array);
    }
}
// $in["action"] = MERMS_USER_CREATEACCOUNT;
$in["loc"] = $_SERVER["REMOTE_ADDR"];



switch ($endpoint) {
    case 'userlogin':
    case 'login':
        $in["action"] = MERMS_USER_LOGIN;
        //$in["account_no"] = "7702222222";
        //$in["password"] = "1234";
        break;
    case 'createuser':
        $in["action"] = MERMS_USER_CREATEACCOUNT;
        //$in["action_recieved"] = MERMS_USER_CREATEACCOUNT;
        break;

    case 'userstask':
        $in["action"] = MERMS_USER_REMINDERS;
        $in["task_mode"] = USER_LOADTASK;
        break;
    case 'createtask':
        $in["action"] = MERMS_USER_REMINDERS;
        $in["task_mode"] = USER_CREATETASK;
        break;

    case 'getprofile':
        $in["action"] = MERMS_USER_LOADPROFILE;
        $in["task_mode"] = MODE_GETVALUE;
        break;
    case 'setprofile':
        $in["action"] = MERMS_USER_UPDATEPROFILE;
        $in["task_mode"] = MODE_SETVALUE;
        break;
    case 'deletetask':
        $in["action"] = MERMS_USER_REMINDERS;
        $in["task_mode"] = USER_DELETETASK;
        break;
    case 'getpractice':
        $in["action"] = MERMS_USER_PRACTICES;
        $in["task_mode"] = MODE_GETVALUE;
        break;
    case 'userencounter':
        $in["action"] = MERMS_USER_REMINDERS;
        $in["task_mode"] = USER_LOADTASK;
        break;
}


$out = $in;

switch ($in["action"]) {
    case 100:
        $out["return"] = "REACH AND BACK";
        $out["retrun_number"] = rand(1000, 9999);
        $out["endpoint"] = $endpoint;
        break;
    case MERMS_USER_BEFORESESSION:

        break;
    case MERMS_USER_CREATEACCOUNT:
        // start account
        // complete account

        $out["return"] = "REACH AND BACK CREATE ACCOUNT";
        $out["retrun_number"] = rand(1000, 9999);
        $out["endpoint"] = $endpoint;

        break;
    case MERMS_USER_RESETPASSWORD:
        // start reset
        // complete reset
        // resend reset

        break;
    case MERMS_USER_LOGIN:

        break;
    case MERMS_USER_DASHLOAD:

        break;
    case MERMS_USER_LOADPROFILE:

        break;
    case MERMS_USER_UPDATEPROFILE:

        break;
    case MERMS_USER_REMINDERS:
        // configure
        // update
        // delete/stop
        break;
}

// calling the backend
$out["internal_return"] = $mermsemr->mermsemr_api($in, $out);

header("HTTP/1.1 200 OK");
header("Status: 200 OK");
echo json_encode(processOutJson($in, $out));
exit();

function flatten($data, $parentkey = "") {
    $result = array();
    foreach ($data as $key => $val) {
        if (is_array($val)) {
            $result = array_merge($result, flatten($val, $parentkey . $key . "_"));
        } else {
            $result[$parentkey . $key] = $val;
        }
    }
    return $result;
}

function processOutJson($in, &$out) {

    switch ($in["action"]) {
        case MERMS_USER_PRACTICES:
            if ($in["task_mode"] == MODE_GETVALUE) {
                $total = $out["total_record"];
                $res = array(
                    "status" => $out["status"],
                    "total_record" => ($total),
                    "internal_return" => $out["internal_return"],
                    "result_list" => array(),
                );
                for ($i = 0; $i < $total; $i++) {
                    $key = sprintf("%05d", $i);
                    $res["result_list"][] = array(
                        "id" => $out["id_${key}"],
                        "patient_id" => $out["patient_id_${key}"],
                        "name" => $out["name_${key}"],
                        "long_id" => $out["long_id_${key}"],
                        "patient_added" => $out["patient_added_${key}"],
                        "added_by" => $out["added_by_${key}"],
                        "patient_status" => $out["patient_status_${key}"]
                    );
                } //  "request_id"
            }
            break;

        case MERMS_USER_REMINDERS:
            if ($in["task_mode"] == USER_LOADTASK) {
                $total = $out["total_record"];
                $res = array(
                    "status" => $out["status"],
                    "total_record" => ($total),
                    "internal_return" => $out["internal_return"],
                    "result_list" => array(),
                );
                for ($i = 0; $i < $total; $i++) {
                    $key = sprintf("%05d", $i);
                    $res["result_list"][] = array(
                        "id" => $out["id_${key}"],
                        "description" => $out["description_${key}"],
                        "reminder" => $out["reminder_${key}"],
                        "start_date" => $out["start_date_${key}"],
                        "end_date" => $out["end_date_${key}"],
                        "reminder_text" => $out["reminder_text_${key}"]
                    );
                } //  "request_id"
            }

            break;




        default:
            return $out;
    }

    return $res;
}

?>
