<?php
// Path to the users.json file
$ordersFilePath = __DIR__ . '/../database/users.json';

// Check if the file exists
if (!file_exists($ordersFilePath)) {
    // Return error message as JSON if the file doesn't exist
    header('Content-Type: application/json');
    echo json_encode(['error' => 'File not found']);
    exit;
}

// Read the contents of the users.json file
$jsonData = file_get_contents($ordersFilePath);

// Decode the JSON data into an associative array
$data = json_decode($jsonData, true);

// Check for JSON decoding errors
if ($data === null) {
    // Return error message if JSON decoding fails
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Failed to decode JSON']);
    exit;
}

// Check if an email parameter is provided in the GET request
if (isset($_GET['email'])) {
    $email = $_GET['email'];
    
    // Search for the user by email
    $userFound = null;
    foreach ($data as $user) {
        if ($user['email'] === $email) {
            $userFound = $user;
            break;
        }
    }

    // If a user is found, return the user data, otherwise return an error
    if ($userFound) {
        header('Content-Type: application/json');
        echo json_encode($userFound, JSON_PRETTY_PRINT);
    } else {
        header('Content-Type: application/json');
        echo json_encode(['error' => 'User not found']);
    }
} else {
    // Return error if no email parameter is provided
    header('Content-Type: application/json');
    echo json_encode(['error' => 'No email parameter provided']);
}
?>
