<?php
defined($security_key) or exit;

//------------------------------------------
// identity
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);

//CONTENT FROM API (POST)
$post_content = json_decode($input,true);

//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}

//default whereclause
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'');

//SET PARAMETERS FOR QUERY
$id = (isset($post_content['userkey'])) ? $post_content['userkey']: ''; //check for rowID
$command = ($id == '')? 'insert' : 'update';  //IF rowID = empty then INSERT
if (isset($post_content['delete'])){$command = 'delete';} //change command to delete
if (isset($post_content['reset'])){$command = 'reset';} //change command to reset
if (isset($post_content['login'], $post_content['email'], $post_content['password'])){$command = 'login';}//change command to login
$date = date('Y-m-d H:i:s');

//CREATE EMPTY STRINGS
$clause = '';
$clause_insert ='';
$input_insert = '';

//BUILD UP PARTNERHIERARCHY FROM INTERFACE USER
$partner_product = json_encode(array("salesid"=>$partner->salesid,"soldto"=>$partner->soldto), JSON_UNESCAPED_UNICODE);

//FIXED VARIABLES
$post_content['updatedby'] = $userrname; //initial = interface user
$post_content['accounthierarchy'] = $partner_product; // related to interface user
//Create or update resetkey
$headers = array('alg'=>'HS256','typ'=>'JWT');
$payload = array('key'=> bin2hex(random_bytes(25)), 'exp'=>(time() + 1800));
$resetkey = generate_jwt($headers, $payload);

//GET EXISTING CONSUMER DATA
if ($id != '' && $command == 'reset'){

    //STEP 1 - Get username
    $stmt = $pdo->prepare('SELECT * FROM identity WHERE userkey = ?');
    $stmt->execute([$id]);
    $consumer_data = $stmt->fetch();

    //STEP 2- Store resetkey
    $sql = 'UPDATE identity SET resetkey = ?, updatedby = ? WHERE userkey = ? '.$whereclause.'';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$resetkey,$post_content['updatedby'],$id]);
    
    //STEP 3 - Send DATA BACK TO FRONT_END
    $messages = json_encode(array('identity'=> $consumer_data['email'], "resetkey" => $resetkey), JSON_UNESCAPED_UNICODE);
    //Send results
    echo $messages;
    exit;
}

//ADD STANDARD PARAMETERS TO ARRAY BASED ON INSERT OR UPDATE
if ($command == 'update'){ 
    //Define Query
    $stmt = $pdo->prepare('SELECT * FROM identity WHERE userkey = ?');
    $stmt->execute([$id]);
    $consumer_data = $stmt->fetch();
    
    $post_content['updatedby'] = $consumer_data['email'];

    if (isset($post_content['password'])){ 
        $post_content['password'] = password_hash($post_content['password'], PASSWORD_DEFAULT);
    }
 
}
elseif ($command == 'insert'){
    $post_content['password'] = password_hash($post_content['password'], PASSWORD_DEFAULT);; //generate initial password
    $post_content['language'] = isset($post_content['language']) ? $post_content['language'] : 'US';
    $post_content['profile'] = 0;
    $post_content['isverified'] = 0;
    $post_content['userkey'] = bin2hex(random_bytes(25)); 
    $post_content['createdby'] = $username;
    $post_content['updatedby'] = $username;
}
elseif ($command == 'login'){

    //SETUP SQL FOR LOGIN_COUNT
    $sql_login = 'UPDATE identity SET login_count = ?, lastlogin = ? WHERE id = ?';
    $lastlogin = date('Y-m-d H:i:s');
    
    // Check if the account exists
    $stmt = $pdo->prepare('SELECT * FROM identity WHERE email = ?');
    $stmt->execute([ $post_content['email'] ]);
    $account = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (count($account) != 0){

        //CHECK NUMBER OF LOGIN ATTEMPTS IS BELOW 5
        if($account['login_count'] < 5 || $account['isverified'] == 0 ){
            // If account exists verify password
            if ($account && password_verify($post_content['password'], $account['password'])) {
            
                //CONSUMER LOGIN CORRECT RETURN DATA
                $consumer = array(
                    'accountID' => $account['userkey'],
                    'profile' => $account['profile'],
                    'language' =>$account['language']
                );

                //Reset login count after succesfull attempt
                $login_attempt = 0;
                
                $stmt_login = $pdo->prepare($sql_login);
                $stmt_login->execute([$login_attempt,$lastlogin, $account['id']]);

                //Encrypt results
                $messages = json_encode($consumer, JSON_UNESCAPED_UNICODE);
                //Send results
                echo $messages; 
                exit;
            } 
            else {
                //Update Login count with failed attempt
                $login_attempt = $account['login_count'] + 1;
                $stmt_login = $pdo->prepare($sql_login);
                $stmt_login->execute([$login_attempt,$lastlogin, $account['id']]);
                //Send Response
                http_response_code(403); //Not authorized
                exit;
            }
        }
        else {
            //User is blocked & send error
            $messages = ($account['isverified'] == 0)? 0 : 1; //0 = not verified 1=blocked

            //------------------------------------------
            //Send results
            //------------------------------------------
            echo $messages; 
            exit;
        }
    }
}
else {
    //do nothing
}

//CREAT NEW ARRAY AND MAP TO CLAUSE
if(isset($post_content) && $post_content!=''){   
    foreach ($post_content as $key => $var){
        if ($key == 'submit' || $key == 'id'){
            //do nothing
        }
        else {
            $criterias[$key] = $var;
            $clause .= ' , '.$key.' = ?';
            $clause_insert .= ' , '.$key.'';
            $input_insert .= ', ?'; // ? for each insert item
            $execute_input[]= $var; // Build array for input
        }
    }
}

//CLEAN UP INPUT
$clause = substr($clause, 2); //Clean clause - remove first comma
$clause_insert = substr($clause_insert, 2); //Clean clause - remove first comma
$input_insert = substr($input_insert, 1); //Clean clause - remove first comma

//QUERY AND VERIFY ALLOWED
if ($command == 'update' && (isAllowed('identity',$profile,$permission,'U') === 1)){
    $sql = 'UPDATE identity SET '.$clause.' WHERE userkey = ? '.$whereclause.'';

    $execute_input[] = $id;
    $stmt = $pdo->prepare($sql);
    $stmt->execute($execute_input);

     //STEP 2- Send to user
     $messages = json_encode(array('accountID' => $id,'status' => 'updated'), JSON_UNESCAPED_UNICODE);
     //Send results
     echo $messages;
     exit;
} 
elseif ($command == 'insert' && isAllowed('',$profile,$permission,'C') === 1){
    
    //check if identity exists
    $stmt = $pdo->prepare('SELECT * FROM identity WHERE email = ?');
    $stmt->execute([$post_content['email']]);
    $consumer_exist = $stmt->fetch();

    $exists = (isset($consumer_exist['email']))? 1 : 0;
    if($consumer_exist == 0 ){
        $sql = 'INSERT INTO identity ('.$clause_insert.') VALUES ('.$input_insert.')';
        $stmt = $pdo->prepare($sql);
        $stmt->execute($execute_input);

        //STEP 2- Send to user
        $messages = json_encode(array('identity'=> $post_content['email'],'accountID' => $post_content['userkey'],'profile' => $post_content['profile'], 'resetkey' => $resetkey, 'language' =>$post_content['language']), JSON_UNESCAPED_UNICODE);
        //Send results
        echo $messages;
        exit;
    } else {
        //------------------------------------------
        //JSON_ENCODE
        //------------------------------------------
        $messages = json_encode($exists, JSON_UNESCAPED_UNICODE);

        //Send results
        echo $messages;            
    }
}
elseif ($command == 'delete' && isAllowed('identity',$profile,$permission,'D') === 1){
    //delete equipment
    $stmt = $pdo->prepare('DELETE FROM identity WHERE userkey = ? '.$whereclause.'');
    $stmt->execute([ $id ]);

    //Add deletion to changelog
    changelog($dbname,'identity',$id,'Delete','Delete',$consumername);
} else
{
    //do nothing
}


?>