<?php
header("Content-Type: application/json"); // Set response header for JSON output
require('config.php'); // Database configuration file

// Initialize response array
$response = array("error" => false, "message" => "", "data" => array());

try {
    // Check if userCredentials is posted and decode the JSON data
    if (!isset($_POST['userCredentials'])) {
        throw new Exception("userCredentials are required.");
    }

    // Decode the JSON data from userCredentials
    $credentials = json_decode($_POST['userCredentials'], true);
    
    // Check if data is valid and contains name and password
    if (empty($credentials) || !isset($credentials[0]['name']) || !isset($credentials[0]['password'])) {
        throw new Exception("Invalid data format or missing name and password.");
    }

    // Sanitize and assign name and password from the decoded JSON
    $name = mysqli_real_escape_string($connect, $credentials[0]['name']);
    $password = $credentials[0]['password']; // Password posted by the user

    // Query to retrieve user data based on name
    $sql = "SELECT * FROM users WHERE name = '$name'"; // Only check by name for security
    $statement = $connect->query($sql);

    // Check for query execution error
    if (!$statement) {
        throw new Exception("Error executing query: " . $connect->error);
    }

    // Fetch user data
    if ($statement->num_rows > 0) {
        $response['message'] = "User found.";
        $row = $statement->fetch_assoc();

        // Verify if the hashed password matches
        if (password_verify($password, $row['password'])) {
            // Prepare user data to return
            $userData = [
                'id' => $row['id'],
                'name' => $row['name'],
                'email' => $row['email'],
                'phone' => $row['phone'],
                'role' => $row['role'],
                'dateCreated' => $row['dateCreated'],
                'createdBy' => $row['createdBy']
            ];
            $response["data"] = $userData;
        } else {
            $response["error"] = true;
            $response["message"] = "Invalid password.";
        }
    } else {
        $response["error"] = true;
        $response["message"] = "No user found with the provided name.";
    }
} catch (Exception $e) {
    // Handle any exceptions and set error in the response
    $response["error"] = true;
    $response["message"] = $e->getMessage();
}

// Output the JSON response
echo json_encode($response);

// Close the database connection
$connect->close();
?>
