<?php
require __DIR__ . '/config.php';

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

$conn = getDbConnection();
$data = json_decode(file_get_contents("php://input"), true);

// Check if required fields are provided
if (!isset($data['real_name'], $data['username'], $data['password'], $data['org_id'], $data['is_active'])) {
    echo json_encode(["success" => false, "status" => "error", "message" => "Invalid input"]);
    exit();
}

$real_name = trim($data['real_name']);
$username = trim($data['username']);
$password = password_hash($data['password'], PASSWORD_BCRYPT);
$org_id = intval($data['org_id']);
$is_active = $data['is_active'] ? 1 : 0;
$token = bin2hex(random_bytes(32)); // Generate a secure token

// ✅ Step 1: Check if org_id exists in organizations
$checkOrgStmt = $conn->prepare("SELECT org_id FROM organizations WHERE org_id = ?");
$checkOrgStmt->bind_param("i", $org_id);
$checkOrgStmt->execute();
$orgResult = $checkOrgStmt->get_result();

if ($orgResult->num_rows == 0) {
    echo json_encode(["success" => false, "status" => "error", "message" => "Invalid organization ID"]);
    exit();
}

// ✅ Step 2: Insert user if org_id exists
$stmt = $conn->prepare("INSERT INTO users (real_name, username, password, token, org_id, is_active) VALUES (?, ?, ?, ?, ?, ?)");
if (!$stmt) {
    echo json_encode(["success" => false, "status" => "error", "message" => "Database error: " . $conn->error]);
    exit();
}

$stmt->bind_param("ssssii", $real_name, $username, $password, $token, $org_id, $is_active);

if ($stmt->execute()) {
    echo json_encode(["success" => true, "status" => "success", "message" => "User registered", "token" => $token]);
} else {
    echo json_encode(["success" => false, "status" => "error", "message" => "Failed to register user: " . $stmt->error]);
}

$stmt->close();
$conn->close();
?>
