<?php
    declare(strict_types=1);
    header('Access-Control-Allow-Origin: *');
 
    $vars = json_decode(file_get_contents("php://input"));
    if(!isset($vars->password)){
        die(json_encode(array("status"=>false,"message"=>"New Password Not Found")));
    }if(empty($vars->password)){
        die(json_encode(array("status"=>false,"message"=>"New Password Empty")));
    }if(!isset($vars->confirmPassword)){
        die(json_encode(array("status"=>false,"message"=>"Confirm New Password Not Found")));
    }if(empty($vars->confirmPassword)){
        die(json_encode(array("status"=>false,"message"=>"Confirm New Password Empty")));
    }
    if(!isset($vars->code)){
        die(json_encode(array("status"=>false,"message"=>"Token Not Found")));
    }if(empty($vars->code)){
        die(json_encode(array("status"=>false,"message"=>"Token Not Found")));
    }
    $code = $vars->code;
    include "konnection.php";

    $check = mysqli_query($conn, "SELECT * FROM reset_tokens WHERE reset = '$code'");
    if(mysqli_num_rows($check) > 0){
        $r=mysqli_fetch_array($check);
        $uid = $r["user"];
        $q = mysqli_query($conn, "SELECT * FROM users WHERE uid = '$uid'");
        $user = mysqli_fetch_assoc($q);
        if(!is_array($user)){
            die(json_encode(array("status"=>false,"message"=>"Something went wrong")));
        }
        if(isset($user["password"])){
                if($vars->password == $vars->confirmPassword){
                   $up = mysqli_query($conn, "UPDATE users SET password = '$vars->password' WHERE uid = '$uid'"); 
                   if($up){
                       mysqli_query($conn, "DELETE FROM reset_tokens WHERE user = '$uid'"); 
                       die(json_encode(array("status"=>true,"message"=>"Password changed!")));
                   }else{
                       die(json_encode(array("status"=>false,"message"=>"Try Later")));
                   }
                }else{
                    die(json_encode(array("status"=>false,"message"=>"Password and Confirm doesn't matched")));
                }
        }else{
            die(json_encode(array("status"=>false,"message"=>"Authorization Not FOund")));
        }
    }else{
      die(json_encode(array("status"=>false,"message"=>"Invalid Token, Re initiate please!")));
    }
    
    
     ?>