<?php

header('Content-Type: application/json');

// Function to check if the email and password match a user in the JSON file
function checkLogin($email, $password) {
    // Path to the JSON file
    $loginDataPath = '../../../database/users.json';

    // Check if the file exists
    if (!file_exists($loginDataPath)) {
        http_response_code(500);
        return json_encode(array('success' => false, 'message' => 'Login data file not found.'));
    }

    // Read the JSON file
    $jsonData = file_get_contents($loginDataPath);

    // Decode the JSON data into a PHP array
    $users = json_decode($jsonData, true);

    // Check if decoding was successful and the data is an array
    if ($users === null || !is_array($users)) {
        http_response_code(500);
        return json_encode(array('success' => false, 'message' => 'Invalid data format in users file.'));
    }

    // Iterate through the users to find a match
    foreach ($users as $user) {
        if (
            isset($user['email']) && isset($user['password']) &&
            $user['email'] === $email && $user['password'] === $password
        ) {
            // Found a match, return full user info (but don't include password!)
            return json_encode(array(
                'success' => true,
                'message' => 'Login successful!',
                'name' => $user['name'],
                'email' => $user['email'],
                'role' => $user['role'],
                'phone' => $user['phone']
            ));
        }
    }

    // No matching user found
    http_response_code(401);
    return json_encode(array('success' => false, 'message' => 'Invalid email or password.'));
}

// Get email and password from the POST request (assuming JSON)
$requestData = json_decode(file_get_contents('php://input'), true);

// Check if email and password are provided
if (isset($requestData['email']) && isset($requestData['password'])) {
    // Call the checkLogin function
    echo checkLogin($requestData['email'], $requestData['password']);
} else {
    // Missing required data in the request
    http_response_code(400);
    echo json_encode(array('success' => false, 'message' => 'Please provide both email and password.'));
}

?>
