<?php
session_start();

require("../includes/db_connect.php");

$password = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if ((isset($_POST['password']) && !empty($_POST['password']))) {

        if ($conn) {
            try {

                $password = $_POST['password'];

                change_password();
            } catch (PDOException $e) {
                die('An unexpected error occurred. Connection failed');
            }
        } else {
            die('An unexpected error occurred. Connection failed.');
        }
    } else {
        die('Invalid user information.');
    }
} else {
    die('Invalid request.');
}

function change_password()
{

    global $password, $conn;

    $email = $_SESSION['usr_rs_email'];

    $hashedPassword = password_hash($password, PASSWORD_BCRYPT);

    $user_sql = "UPDATE users SET password=? WHERE email=?";

    $update_pswd = $conn->prepare($user_sql)->execute([$hashedPassword, $email]);

    if ($update_pswd) {

        $pswdrst_sql = "UPDATE password_reset SET token=?, email_confirmation=? WHERE email=?";

        $update_pswdrst = $conn->prepare($pswdrst_sql)->execute([0, 1, $email]);

        if ($update_pswdrst) {

            session_destroy();
            die("success");
        } else {
            die("An unexpected error occurred. Please try again");
        }
    } else {
        die("An unexpected error occurred. Please try again.");
    }
}