<?php
session_start();
include 'layouts/dbconn.php';

// Check if the user is logged in
if (isset($_SESSION['user_id'])) {
    // Handle form submission for unlocking the screen
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $password = $_POST['password'];

        // Validate the password
        if (validatePassword($password)) {
            // Password is correct, send a success response
            echo json_encode(['success' => true]);
            exit;
        } else {
            // Password is incorrect, send an error response
            echo json_encode(['success' => false, 'message' => 'Invalid password. Please try again.']);
            exit;
        }
    } else {
        // Invalid request method, send an error response
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid request.']);
        exit;
    }
} else {
    // User is not logged in, send an error response
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'User is not authenticated.']);
    exit;
}

function validatePassword($password) {
    // Include your database connection file
    include 'layouts/dbconn.php';

    // Prepare the SQL query to fetch the user's hashed password
    $sql = "SELECT password FROM users WHERE user_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $_SESSION['user_id']);

    if (!$stmt->execute()) {
        // Error executing the SQL query
        error_log("Error executing SQL query: " . $stmt->error);
        return false;
    }

    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        $hashed_password = $user['password'];

        // Verify the entered password with the hashed password from the database
        if (password_verify($password, $hashed_password)) {
            // Password is correct
            return true;
        } else {
            // Invalid password
            return false;
        }
    } else {
        // User not found
        return false;
    }

    // Close the database connection
    $stmt->close();
    $conn->close();
}
?>