<?php
include("../config.php");
include("../mail/email.php");
header('Content-Type: application/json');

$postData = json_decode(file_get_contents('php://input'), true); 

if (!$db) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}

// Validate incoming data
$requiredFields = ['firstName', 'lastName', 'email', 'phoneNumber', 'roles'];
foreach ($requiredFields as $field) {
    if (!isset($postData[$field]) || empty($postData[$field])) {
        echo json_encode(['status' => 'error', 'message' => "$field is required"]);
        exit;
    }
}

// Check if user is logged in
if (!isset($_SESSION['client_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'User not authenticated']);
    exit;
}

$client_id = $_SESSION['client_id']; 
$firstName = mysqli_real_escape_string($db, $postData['firstName']); 
$lastName = mysqli_real_escape_string($db, $postData['lastName']);
$email = mysqli_real_escape_string($db, $postData['email']); 
$phone = mysqli_real_escape_string($db, $postData['phoneNumber']); // Fix phoneNumber

// Concatenate first name and last name
$fullName = mysqli_real_escape_string($db, trim($firstName . ' ' . $lastName));

// Ensure roles is an array
if (!isset($postData['roles']) || !is_array($postData['roles'])) {
    echo json_encode(['status' => 'error', 'message' => 'Roles should be an array']);
    exit;
}

// Convert roles array into a comma-separated string
$rolesString = mysqli_real_escape_string($db, implode(',', $postData['roles']));

// **Check if email already exists**
$checkEmailQuery = "SELECT id FROM users WHERE email = '$email'";
$result = mysqli_query($db, $checkEmailQuery);

if ($result && mysqli_num_rows($result) > 0) {
    echo json_encode(['status' => 'error', 'message' => 'Email already exists']);
    exit;
}

// Insert data into the database
$query = "INSERT INTO users (client_id, name, email, phone, role) 
          VALUES ('$client_id', '$fullName', '$email', '$phone', '$rolesString')";

if (mysqli_query($db, $query)) {
    setPassword($email, $fullName);
    echo json_encode(['status' => 'success', 'message' => 'User added successfully']);


} else {
    echo json_encode(['status' => 'error', 'message' => 'Failed to add user', 'error' => mysqli_error($db)]);
}
?>
