<?php
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'Gagal menambahkan pengguna.', 'errors' => []];

require_once __DIR__ . '/../../../config/config.php';
require_once __DIR__ . '/../../../includes/session.php';
require_once __DIR__ . '/../../../lib/Auth.php';
require_once __DIR__ . '/../../../includes/functions.php';

if (!Auth::isLoggedIn() || $_SESSION['user_role'] !== 'admin') {
    http_response_code(403);
    $response['message'] = 'Akses ditolak.';
    echo json_encode($response);
    exit;
}

if (!isset($pdo) || !$pdo instanceof PDO) {
    http_response_code(500);
    error_log("PDO object not available in admin/add_user.php");
    $response['message'] = 'Koneksi database gagal.';
    echo json_encode($response);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    $response['message'] = 'Metode request tidak valid.';
    echo json_encode($response);
    exit;
}

try {
    $username = sanitize_input($_POST['username'] ?? '');
    $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    $password = $_POST['password'] ?? '';
    $fullName = sanitize_input($_POST['full_name'] ?? null);
    $phoneNumber = sanitize_input($_POST['phone_number'] ?? null);
    $balance = filter_input(INPUT_POST, 'balance', FILTER_VALIDATE_FLOAT, FILTER_NULL_ON_FAILURE);
    $role = sanitize_input($_POST['role'] ?? 'member');
    $status = sanitize_input($_POST['status'] ?? 'active');

    $errors = [];
    $auth = new Auth($pdo);

    if (empty($username)) {
        $errors['username'] = 'Username wajib diisi.';
    } elseif (strlen($username) < 3) {
        $errors['username'] = 'Username minimal 3 karakter.';
    } elseif ($auth->isUsernameTaken($username)) {
        $errors['username'] = 'Username sudah digunakan.';
    }

    if (empty($email)) {
        $errors['email'] = 'Email wajib diisi.';
    } elseif (!$email) {
        $errors['email'] = 'Format email tidak valid.';
    } elseif ($auth->isEmailTaken($email)) {
        $errors['email'] = 'Email sudah digunakan.';
    }

    if (empty($password)) {
        $errors['password'] = 'Password wajib diisi.';
    } elseif (strlen($password) < 6) {
        $errors['password'] = 'Password minimal 6 karakter.';
    }

    if ($phoneNumber !== null && $phoneNumber !== '' && !preg_match('/^[0-9]{10,15}$/', $phoneNumber)) {
        $errors['phone_number'] = 'Format nomor handphone tidak valid.';
    }
    if ($balance === null || $balance < 0) {
         $errors['balance'] = 'Saldo awal tidak valid.';
         $balance = 0;
    }
    if (!in_array($role, ['member', 'admin'])) {
        $errors['role'] = 'Peran tidak valid.';
    }
     if (!in_array($status, ['active', 'inactive', 'banned'])) {
        $errors['status'] = 'Status tidak valid.';
    }

    if (!empty($errors)) {
        http_response_code(400);
        $response['message'] = 'Periksa kembali input Anda.';
        $response['errors'] = $errors;
    } else {
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        if ($hashedPassword === false) {
            throw new RuntimeException('Gagal melakukan hashing password.');
        }

        $userData = [
            'username' => $username,
            'email' => $email,
            'password' => $hashedPassword,
            'full_name' => $fullName,
            'phone_number' => $phoneNumber,
            'balance' => $balance, 
            'role' => $role,
            'status' => $status,
        ];

        if ($auth->register($userData)) { 
            $response['success'] = true;
            $response['message'] = 'Pengguna baru berhasil ditambahkan.';
        } else {
            http_response_code(500);
            $response['message'] = 'Gagal menambahkan pengguna ke database.';
        }
    }

} catch (InvalidArgumentException $e) {
    http_response_code(400);
    $response['message'] = $e->getMessage();
} catch (\PDOException $e) {
    error_log("Admin Add User DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan database.";
    http_response_code(500);
} catch (\Throwable $e) {
    error_log("Admin Add User General Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan internal server.";
    if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_php'] = $e->getMessage(); }
    http_response_code(500);
}

echo json_encode($response);
exit;
?>
