<?php
session_start();

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

$current_password = "";
$new_password = "";

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

    if ((!empty($_POST['current_password'])) && (!empty($_POST['new_password']))) {

        if ($conn) {
            try {

                $current_password = $_POST['current_password'];
                $new_password = $_POST['new_password'];
                $accountId = $_SESSION['usr_accountId'];

                $usr_sql = "SELECT * FROM users WHERE accountId =? LIMIT 1";
                $usr_sth = $conn->prepare($usr_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                $usr_sth->execute([$accountId]);
                $users = $usr_sth->fetchAll();

                if (count($users) > 0) {

                    foreach ($users as $key => $value) {

                        $acc_password = $value['password'];

                        if (password_verify($current_password, $acc_password)) {
                            change_password();
                        } else {
                            die("Invalid credentials. Please check and try again.");
                        }
                    }
                } else {
                    die('An unexpected error occurred. Connection failed');
                }
            } 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 $current_password, $new_password, $accountId, $conn;

    $hashedPassword = password_hash($new_password, PASSWORD_BCRYPT);

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

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

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