<?php
require_once __DIR__ . '/../../config/session.php';
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../../config/response.php';

require_login();

$raw = json_decode(file_get_contents('php://input'), true);
$name     = trim($raw['name'] ?? '');
$email    = trim($raw['email'] ?? '');
$password = trim($raw['password'] ?? '');
$role     = trim($raw['role'] ?? 'staff');

if (!$name || !$email || !$password) {
    jsonResponse(['success' => false, 'message' => 'নাম, ইমেইল ও পাসওয়ার্ড দিন'], 422);
}

$check = $pdo->prepare("SELECT id FROM users WHERE email = ?");
$check->execute([$email]);
if ($check->fetch()) {
    jsonResponse(['success' => false, 'message' => 'এই ইমেইল আগে থেকে আছে'], 409);
}

$hashed = password_hash($password, PASSWORD_BCRYPT);
$stmt = $pdo->prepare("INSERT INTO users (name, email, password, role, status) VALUES (?, ?, ?, ?, 'active')");
$stmt->execute([$name, $email, $hashed, $role]);

jsonResponse(['success' => true, 'message' => 'ইউজার তৈরি হয়েছে', 'data' => ['id' => $pdo->lastInsertId()]]);