<?php
session_start();
include 'layouts/dbconn.php';

// Check admin access
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Access denied']);
    exit;
}

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

try {
    // Validate required fields
    $required = ['username', 'full_name', 'email', 'password', 'role_id'];
    foreach ($required as $field) {
        if (empty($_POST[$field])) {
            throw new Exception("Missing required field: $field");
        }
    }

    // Check if username or email already exists
    $stmt = $conn->prepare("SELECT user_id FROM users WHERE username = ? OR email = ?");
    $stmt->bind_param("ss", $_POST['username'], $_POST['email']);
    $stmt->execute();
    if ($stmt->get_result()->num_rows > 0) {
        throw new Exception('Username or email already exists');
    }

    // Hash password
    $hashed_password = password_hash($_POST['password'], PASSWORD_DEFAULT);

    // Insert new user
    $stmt = $conn->prepare("INSERT INTO users (username, full_name, email, password, role_id, verified, created_at) VALUES (?, ?, ?, ?, ?, 1, NOW())");
    $stmt->bind_param("ssssi", 
        $_POST['username'],
        $_POST['full_name'],
        $_POST['email'],
        $hashed_password,
        $_POST['role_id']
    );

    if (!$stmt->execute()) {
        throw new Exception($conn->error);
    }

    echo json_encode([
        'success' => true,
        'message' => 'User created successfully'
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>