<?php
// Set headers for JSON response
header('Access-Control-Allow-Origin: *'); // In production, restrict this to your frontend domain
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');

// Bootstrap the application
require_once '../../../core/bootstrap.php';

// Instantiate User model
$user = new User();

// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); // Method Not Allowed
    echo json_encode(['message' => 'Method Not Allowed']);
    exit();
}

// Get raw posted data from the request body
$data = json_decode(file_get_contents("php://input"));

// --- Basic Validation ---
$errors = [];
if (empty($data->username)) {
    $errors[] = 'Username is required.';
}
if (empty($data->email) || !filter_var($data->email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = 'A valid email is required.';
}
if (empty($data->password) || strlen($data->password) < 6) {
    $errors[] = 'Password is required and must be at least 6 characters.';
}
if (empty($data->first_name)) {
    $errors[] = 'First name is required.';
}
if (empty($data->last_name)) {
    $errors[] = 'Last name is required.';
}

if (!empty($errors)) {
    http_response_code(400); // Bad Request
    echo json_encode(['errors' => $errors]);
    exit();
}

// --- Check for existing user ---
if ($user->findByEmail($data->email)) {
    http_response_code(409); // Conflict
    echo json_encode(['message' => 'Email is already taken.']);
    exit();
}

if ($user->findByUsername($data->username)) {
    http_response_code(409); // Conflict
    echo json_encode(['message' => 'Username is already taken.']);
    exit();
}

// --- Create User ---
// Hash password for security
$hashed_password = password_hash($data->password, PASSWORD_DEFAULT);

$userData = [
    'username' => htmlspecialchars(strip_tags($data->username)),
    'email' => htmlspecialchars(strip_tags($data->email)),
    'password_hash' => $hashed_password,
    'first_name' => htmlspecialchars(strip_tags($data->first_name)),
    'last_name' => htmlspecialchars(strip_tags($data->last_name))
];

if ($user->register($userData)) {
    http_response_code(201); // Created
    echo json_encode(['message' => 'User registered successfully.']);
} else {
    http_response_code(500); // Internal Server Error
    echo json_encode(['message' => 'User could not be registered.']);
}
?>