<?php
session_start();
include '../includes/dbconn.php'; // Include your database connection

// Function to validate the password
function validatePassword($userId, $password) {
    global $conn; // Use the database connection

    $stmt = $conn->prepare("SELECT password_hash FROM users WHERE user_id = ?");
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        if (password_verify($password, $row['password_hash'])) {
            return true;
        }
    }
    $stmt->close();
    return false;
}

// Handle the form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_SESSION['user_id'])) {
    $password = $_POST['password'];

    if (validatePassword($_SESSION['user_id'], $password)) {
        // Redirect to the main page if the password is correct
        header('Location: index.php');
        exit();
    } else {
        // Set error message and redirect back to the lock screen if the password is incorrect
        $_SESSION['error'] = 'Incorrect password.';
        header('Location: auth-lock-screen.php');
        exit();
    }
} else {
    // Redirect to the login page if not logged in or if the form is not submitted
    header('Location: login.php');
    exit();
}
?>
