<?php

require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../config/helpers.php';
require_once __DIR__ . '/../../../middleware/admin.php';
require_once __DIR__ . '/UserRepository.php';

if (getMethod() !== 'POST') {
    jsonResponse(false, 'Method not allowed', null, 405);
}

global $pdo;
requireAdmin();
$repo = new UserRepository($pdo);
$input = getJsonInput();

$name = trim($input['name'] ?? '');
$email = strtolower(trim($input['email'] ?? ''));
$password = (string)($input['password'] ?? '');
$phone = trim($input['phone'] ?? '');
$avatar = trim($input['avatar'] ?? '');
$country = trim($input['country'] ?? '');
$role = trim($input['role'] ?? 'user');
$isActive = isset($input['is_active']) ? (int)(bool)$input['is_active'] : 1;

if ($name === '' || $email === '' || $password === '') {
    jsonResponse(false, 'Name, email and password are required', null, 422);
}

if ($repo->findByEmail($email)) {
    jsonResponse(false, 'Email already exists', null, 409);
}

$userId = $repo->create([
    'name' => $name,
    'email' => $email,
    'password' => password_hash($password, PASSWORD_DEFAULT),
    'phone' => $phone !== '' ? $phone : null,
    'avatar' => $avatar !== '' ? $avatar : null,
    'country' => $country !== '' ? $country : null,
    'agent' => getUserAgent(),
    'ip' => getClientIp(),
    'is_active' => $isActive,
    'role' => in_array($role, ['admin', 'user'], true) ? $role : 'user',
]);

jsonResponse(true, 'User created successfully', $repo->findById($userId), 201);
