<?php

date_default_timezone_set('America/Chicago');

header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');

include('../process/functions.php');

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$checkin_time = date("Y-m-d H:i:s");
$checkin_time_epoch = time();

function createWaitingroom( $user_id = null, $guid = null, $checkin_time = null ){
    
    if( isset($user_id) || !empty($user_id) ){
        
        $conn = ddxrxDBConnect();
        
        $version = get_version();
        
        $returning = '1';
        
        $patient_name = getpatientInfo($user_id,'patient_fname').' '.getpatientInfo($user_id,'patient_lname');
        $patient_id = getpatientInfo($user_id,'patient_id');
        
        $insert_sql = "INSERT INTO waiting_room(waitingroom_guid, patient_id, patient_name, is_returning_patient, checkin_time, groupid) values('".$guid."', '".$patient_id."', '".$patient_name."', ".$returning.", '".$checkin_time."', '".$version."');";
        
        if ($conn->query($insert_sql) === TRUE) {
            
            $last_id = $conn->insert_id;
            
            $create_result = $last_id;
            
        } else {
            
            $create_result = FALSE;
            
        }
        
        // Close DB connection
        $conn->close();
        
    }else{
        
        $create_result = FALSE;
        
    }
    
    return $create_result;
    
}

if( isset($_POST['url']) && $_POST['url'] != '' ){
    $url = $_POST['url'];
}else{
    $url = get_version('url');
}

if( isset($_POST['username']) && $_POST['username'] != '' && isset($_POST['password']) && $_POST['password'] != '' ){
    
    $version = get_version();
    $username = $_POST['username'];
    $password = md5($_POST['password']);
    $pass_raw = $_POST['password'];
    $checkin_time = date("Y-m-d H:i:s");
    $returning = '1';
    
    // Store User data
    $userdata = array(
	    'username' => $username,
	    'password' => $password,
	    'group_id' => $version
	);
    
    // Store API object to variable	
	$authentication_data = sendtoAPI('https://ddxrx.ai/auth', $userdata);
	
	// Store Authentication tokken in session
    $tokken = $authentication_data->access_token;
    
    // Add token in database
    $add_tokken_sql = "UPDATE all_users SET access_token = '$tokken' WHERE username = '$username'";
    ddxrxDBConnect()->query($add_tokken_sql);
    
    $sql = "SELECT * FROM all_users LEFT JOIN patients ON all_users.userid = patients.user_id WHERE all_users.username = '$username' && all_users.password = '$password' AND all_users.groupid = '$version' LIMIT 1;";
    
    $result = ddxrxDBConnect()->query($sql);
    
    // Associative array
    $row = $result -> fetch_assoc();
    
    if( isset($row['username']) && $row['username'] != '' ){
        
        $currentUrl = $_SERVER['HTTP_HOST'];
        $user_id = $row['userid'];
        
        $currentTime = time();
        $expireTime = time()+31536000;
        
        $authKey = md5($password.$expireTime);
    
        $sqlins = "INSERT INTO app_login (user_id, auth_key, auth_time, validity) VALUES ('$user_id', '$authKey', '$currentTime', '$expireTime')";

        if (ddxrxDBConnect()->query($sqlins) === TRUE) {
            
            // Delete Data
            deleteinstant($user_id);
            
            // Create a waiting room
            $guid = md5( $checkin_time.$row['userid'] );
            $waitingroom = createWaitingroom( $row['userid'], $guid, $checkin_time );
            $waitingroom_parameter = '&idKey='.$guid.'&checkInTime='.$checkin_time_epoch.'&waitingroom_id='.$waitingroom;
            $fullname = $row['patient_fname'].' '.$row['patient_lname'];
            
            $args = array( 'username' => $row['username'] );

            $authresult = array(
                'result' => true,
                'result_type' => 'success',
                'desc' => 'Username and password have been authenticated and returned a valid credentials, you may now login.',
                'auth_key'  => $authKey,
                'user_id'   => $row['userid'],
                'patient_id' => $row['patient_id'],
                'username'  => $row['username'],
                'password'  => $row['password'],
                'fullname' => $fullname,
                'fname'  => $row['patient_fname'],
                'lname'  => $row['patient_lname'],
                'group_id'  => $row['groupid'],
                'user_type'  => $row['user_type'],
                'location' => $row['location'],
                'redirect_url' => 'https://'.$url.'/app-redirector.php?auth_key='.$authKey.'&user_id='.$row['userid'].'&username='.$row['username'].'&user_type='.$row['user_type'].'&password='.$pass_raw.'&email='.$row['email_address'].'&is_verified_email='.$row['is_verified_email'].'&version='.$version.$waitingroom_parameter,
                'text' => 'Hi, Your wish is my command, how may I help you?',
                'access_token' => json_decode(generateJWT($args)),
                'waitingroom_id' => $waitingroom,
            );
            
        }else{
            
            $authresult = array(
                'result' => false,
                'result_type' => 'server_error',
                'desc' => 'Internal server error, please contact the administrators.'
            );
        
        }
    
    }else{
        
        $authresult = array(
            'result' => false,
            'result_type' => 'auth_error',
            'desc' => 'Authentication failed, username and password does not match our database.',
            //'sql' => $sql
        );
        
    }
    
    // Free result set
    $result->free_result();
        
    ddxrxDBConnect()->close();
    
}else{
    
    $authresult = array(
        'result' => false,
        'result_type' => 'empty_field',
        'desc'  => 'Username and Password field cannot be empty'
    );
    
}



    echo json_encode($authresult);

?>