<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/database.php';

$response = ['success' => false, 'message' => ''];

try {
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Invalid input data');
    }
    
    // Validate required fields
    $required = ['full_name', 'email', 'username', 'password', 'role', 'status'];
    foreach ($required as $field) {
        if (empty($input[$field])) {
            throw new Exception("Missing required field: $field");
        }
    }
    
    $pdo = Database::getInstance()->getConnection();
    
    // Check if username or email already exists
    $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
    $stmt->execute([$input['username'], $input['email']]);
    
    if ($stmt->fetch()) {
        throw new Exception('Username or email already exists');
    }
    
    // Hash password
    $hashedPassword = password_hash($input['password'], PASSWORD_DEFAULT);
    
    // Insert user - using your actual table column names
    $stmt = $pdo->prepare("INSERT INTO users (full_name, email, username, password, role, status, department) 
                          VALUES (?, ?, ?, ?, ?, ?, ?)");
    
    $success = $stmt->execute([
        $input['full_name'],
        $input['email'], 
        $input['username'],
        $hashedPassword,
        $input['role'],
        $input['status'],
        $input['unit_name'] ?? null  // Map unit_name to department column
    ]);
    
    if ($success) {
        $response['success'] = true;
        $response['message'] = 'User created successfully';
    } else {
        throw new Exception('Failed to create user');
    }
    
} catch (Exception $e) {
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
?>