<?php
defined($security_key) or exit;

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

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

//SET PARAMETERS FOR QUERY
$id = $post_content['id'] ?? ''; //check for rowID
$command = ($post_content['reset'])? 'reset' : '';  // change command to reset

$post_content['updatedby'] = $username;

//GET EXISTING USER DATA
if ($id != ''){
//Define Query
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$id]);
$user_data = $stmt->fetch();
$owner_user = (($user_data['username'] == $username)? 1 : 0);


    if ($command != 'reset' && $owner_user === 1 && $post_content['language']){
        $sql = 'UPDATE users SET language = ?, updatedby = ? WHERE id = ? ';
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$post_content['language'],$username,$id]);
    }

    if ($command == 'reset' && $owner_user === 1){
        //STEP 1- create resetkey
        $headers = array('alg'=>'HS256','typ'=>'JWT');
        $payload = array('username'=>$user_data['username'], 'exp'=>(time() + 1800));
        $resetkey = generate_jwt($headers, $payload);
        //STEP 2- Store resetkey
        $sql = 'UPDATE users SET resetkey = ?, updatedby = ? WHERE id = ? ';
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$resetkey,$username,$id]);
        //STEP 3 - Send to user
        $mail_location = (file_exists($_SERVER['DOCUMENT_ROOT'].'/custom/'.$domain.'/mail/email_template_reset.php') ? $_SERVER['DOCUMENT_ROOT'].'/custom/'.$domain.'/mail/email_template_reset.php' : './assets/mail/email_template_reset.php');
        include_once $mail_location;
        send_mail($user_data['email'],$subject,$message,'','');
    }
}
