<?php
session_start();

// Ensure user is logged in
if (!isset($_SESSION['email'])) {
    die("Not authenticated");
}

$email = $_SESSION['email'];
$newPassword = $_POST['newPassword'] ?? '';
$confirmPassword = $_POST['confirmPassword'] ?? '';

if (empty($newPassword) || empty($confirmPassword)) {
    die("Please fill in all fields.");
}
if ($newPassword !== $confirmPassword) {
    die("Passwords do not match.");
}

// Hash new password
$hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);

// Database connection
$host = "localhost";
$dbname = "gobolcha_gobolchain";
$username = "gobolcha_gobolchain";
$password = "@Jibala1997";

$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed");
}

// Update password
$stmt = $conn->prepare("UPDATE users SET password = ? WHERE email = ?");
$stmt->bind_param("ss", $hashedPassword, $email);
if ($stmt->execute()) {
    echo "success";
} else {
    echo "Failed to update password.";
}

$stmt->close();
$conn->close();