<?php
require_once 'init.php';

// Set content type to JSON
header('Content-Type: application/json');

// Check if user is logged in
if (!is_logged_in()) {
    echo json_encode(['success' => false, 'message' => 'Authentication required.']);
    exit();
}

// Check if password is provided
if (!isset($_POST['password'])) {
    echo json_encode(['success' => false, 'message' => 'Password not provided.']);
    exit();
}

$password = $_POST['password'];
$user_id = $_SESSION['user_id'];

// Fetch the user's password hash from the database
$stmt = $conn->prepare("SELECT password_hash FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'User not found.']);
    exit();
}

$user = $result->fetch_assoc();
$stmt->close();

// Verify the provided password against the stored hash
if (password_verify($password, $user['password_hash'])) {
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'message' => 'Incorrect password.']);
}

exit();
?>
