<?php
session_start();

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

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

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

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

        if ($conn) {
            try {

                $password = $_POST['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($password, $acc_password)) {

                            $sql = 'DELETE FROM users WHERE  accountId = ?';
                            $stmt = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                            $stmt->execute([$accountId]);

                            session_destroy();
                            die("success");
                        } 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.');
}