<?php
// Path to users.json
$usersFilePath = __DIR__ . '/../database/users.json';

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

// Required fields
if (
    isset($_POST['userName'], $_POST['userPhone'], $_POST['userEmail'], $_POST['userRole'])
) {
    $email = trim($_POST['userEmail']);

    // Load users
    $jsonData = file_get_contents($usersFilePath);
    $users = json_decode($jsonData, true) ?: [];

    $userFound = false;

    foreach ($users as $index => $user) {
        if ($user['email'] === $email) {
            // Update fields
            $users[$index]['name'] = $_POST['userName'];
            $users[$index]['phone'] = $_POST['userPhone'];
            $users[$index]['role'] = $_POST['userRole'];

            // Update password if provided
            if (!empty($_POST['userPassword'])) {
                $users[$index]['password'] = $_POST['userPassword'];
            }

            $userFound = true;
            break;
        }
    }

    if ($userFound) {
        // Save updated list
        if (file_put_contents($usersFilePath, json_encode($users, JSON_PRETTY_PRINT)) !== false) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to save changes.']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'User not found.']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Missing required fields.']);
}
?>
