<?php
include('include/session.php');
include('include/navigation.php');
include('connection.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $current_password = $_POST['current_password'];
    $new_password = $_POST['password'];
    $verify_password = $_POST['verify_password'];

    // Validate input
    if (empty($current_password) || empty($new_password) || empty($verify_password)) {
        echo "<script> alert('All fields are required'); window.location.href = 'resetPassword.php'; </script>";
        exit();
    }

    if ($new_password !== $verify_password) {
        echo "<script> alert('New passwords do not match'); window.location.href = 'resetPassword.php'; </script>";
        exit();
    }

    if (strlen($new_password) < 8 || strlen($new_password) > 20 || strpos($new_password, ' ') !== false) {
        echo "<script> alert('Password must be 8-20 characters long and must not contain spaces'); window.location.href = 'resetPassword.php'; </script>";
        exit();
    }

    $dbConnection = new DbConnection();
    $connection = $dbConnection->connection;

    // Correctly access the user ID from session
    $user_id = $_SESSION['user']['id'];
    
    // Fetch the user's current hashed password from the database
    $stmt = $connection->prepare("SELECT password FROM users WHERE id = ?");
    if (!$stmt) {
        die('Prepare failed: ' . htmlspecialchars($connection->error));
    }

    $stmt->bind_param("i", $user_id);
    if (!$stmt->execute()) {
        die('Execute failed: ' . htmlspecialchars($stmt->error));
    }

    $stmt->bind_result($hashed_password);
    $stmt->fetch();
    $stmt->close();

    // Check if a password was retrieved
    if ($hashed_password === null) {
        echo "<script> alert('No password found for user with ID: " . htmlspecialchars($user_id) . "'); window.location.href = 'resetPassword.php'; </script>";
        exit();
    }

    // Verify the current password using MD5
    if (md5($current_password) !== $hashed_password) {
        echo "<script> alert('Current password is incorrect'); window.location.href = 'resetPassword.php'; </script>";
        exit();
    }

    // Hash the new password using MD5
    $new_hashed_password = md5($new_password);

    // Update the new password in the database
    $stmt = $connection->prepare("UPDATE users SET password = ? WHERE id = ?");
    if (!$stmt) {
        die('Prepare failed: ' . htmlspecialchars($connection->error));
    }

    $stmt->bind_param("si", $new_hashed_password, $user_id);
    if ($stmt->execute()) {
        echo "<script> alert('Password updated successfully'); window.location.href = 'resetPassword.php'; </script>";
    } else {
        echo "<script> alert('Failed to update password'); window.location.href = 'resetPassword.php'; </script>";
    }
    $stmt->close();
}
?>
<html lang="en">
<head>
    <link rel="stylesheet" href="assets/css/style.css">
    <?php include('include/header_links.php'); ?>
</head>
<body>
    <form action="resetPassword.php" method="POST">
        <div class="container_main">
            <div class="card card-outline-secondary">
                <div class="card-header">
                    <h3 class="mb-0">Reset Your Password</h3>
                </div>
                <div class="card-body">
                    <div class="form">
                        <div class="form-group">
                            <label for="inputPasswordOld">Current Password</label>
                            <input type="password" class="form-control" id="inputPasswordOld" name="current_password" required="">
                        </div>
                        <div class="form-group">
                            <label for="inputPasswordNew">New Password</label>
                            <input type="password" class="form-control" id="inputPasswordNew" name="password" required="">
                            <span class="form-text small text-muted">
                                The password must be 8-20 characters and must <em>not</em> contain spaces.
                            </span>
                        </div>
                        <div class="form-group">
                            <label for="inputPasswordNewVerify">Verify</label>
                            <input type="password" class="form-control" id="inputPasswordNewVerify" name="verify_password" required="">
                            <span class="form-text small text-muted">
                                To confirm, type the new password again.
                            </span>
                        </div>
                        <div class="form-group">
                            <button type="submit" class="btn btn-success btn-lg float-right">Save</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</body>
</html>
