<?php

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

$response = ['success' => false, 'errors' => ['general' => 'Terjadi kesalahan server awal.']];

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

if (!isset($pdo) || !$pdo instanceof PDO) {
    http_response_code(500);
    error_log("FATAL Error in register_handler.php: PDO object not available or invalid. Check include order and DB connection in index.php/db_connect.php.");
    $response['errors']['general'] = 'Koneksi database tidak siap.';
    echo json_encode($response);
    exit;
}

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

try {
    $fullName = sanitize_input($_POST['full_name'] ?? null);
    $username = sanitize_input($_POST['username'] ?? '');
    $email = sanitize_input($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';

    $errors = [];
    if (empty($username)) { $errors['username'] = "Username wajib diisi."; }
    elseif (strlen($username) < 4 || strlen($username) > 50) { $errors['username'] = "Username harus antara 4 dan 50 karakter."; }
    elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) { $errors['username'] = "Username hanya boleh berisi huruf, angka, dan underscore (_)."; }
    if (empty($email)) { $errors['email'] = "Email wajib diisi."; }
    elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors['email'] = "Format email tidak valid."; }
    if (empty($password)) { $errors['password'] = "Password wajib diisi."; }
    elseif (strlen($password) < 6) { $errors['password'] = "Password minimal harus 6 karakter."; }
    if (empty($confirmPassword)) { $errors['confirm_password'] = "Konfirmasi password wajib diisi."; }
    elseif ($password !== $confirmPassword) { $errors['confirm_password'] = "Password dan konfirmasi password tidak cocok."; }

    if (!empty($errors)) {
        $response['errors'] = $errors;
        echo json_encode($response);
        exit;
    }

    $auth = new Auth($pdo);
    if ($auth->isUsernameTaken($username)) { $errors['username'] = "Username '" . htmlspecialchars($username) . "' sudah digunakan."; }
    if ($auth->isEmailTaken($email)) { $errors['email'] = "Email '" . htmlspecialchars($email) . "' sudah terdaftar."; }

    if (!empty($errors)) {
        $response['errors'] = $errors;
        echo json_encode($response);
        exit;
    }

    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
    if ($hashedPassword === false) {
         throw new \RuntimeException("Password hashing failed.", 500);
    }

    $userData = [
        'username' => $username,
        'email' => $email,
        'password' => $hashedPassword,
        'full_name' => !empty($fullName) ? $fullName : null,
    ];

    $registrationResult = $auth->register($userData);

    if ($registrationResult) {
        $response = [
            'success' => true,
            'message' => 'Registrasi berhasil! Anda akan dialihkan ke halaman login.',
            'redirectUrl' => base_url('login') 
        ];
    } else {
        $response['errors']['general'] = "Registrasi gagal karena kesalahan database. Silakan coba lagi nanti.";
        if (defined('DEBUG_MODE') && DEBUG_MODE === true) {
         }
    }

} catch (\Throwable $e) { 
    error_log("AJAX Register Handler Exception: " . $e->getMessage() . " | Code: " . $e->getCode());
    $response['errors']['general'] = "Terjadi kesalahan tak terduga saat registrasi.";
     if (defined('DEBUG_MODE') && DEBUG_MODE === true) {
         $response['errors']['debug'] = $e->getMessage();
    }
    http_response_code(500); 
}

echo json_encode($response);
exit; 
?>
