<?php
require_once '../config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Only POST method allowed', null, 405);
}

$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    $input = $_POST;
}

$name = sanitizeInput($input['name'] ?? '');
$email = sanitizeInput($input['email'] ?? '');
$password = $input['password'] ?? '';
$confirm_password = $input['confirm_password'] ?? '';

// Validation
if (empty($name) || empty($email) || empty($password) || empty($confirm_password)) {
    sendResponse(false, 'All fields are required', null, 400);
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    sendResponse(false, 'Invalid email format', null, 400);
}

if ($password !== $confirm_password) {
    sendResponse(false, 'Password and confirm password do not match', null, 400);
}

if (strlen($password) < 6) {
    sendResponse(false, 'Password must be at least 6 characters long', null, 400);
}

try {
    // Check if email already exists
    $stmt = $conn->prepare("SELECT id FROM users WHERE email=?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();
    
    if ($stmt->num_rows > 0) {
        sendResponse(false, 'Email already exists', null, 409);
    }
    
    // Hash password and generate token
    $hashedPassword = password_hash($password, PASSWORD_BCRYPT);
    $apiToken = generateToken();
    
    // Insert new user
    $insertStmt = $conn->prepare("INSERT INTO users (name, email, password, api_token) VALUES (?, ?, ?, ?)");
    $insertStmt->bind_param("ssss", $name, $email, $hashedPassword, $apiToken);
    
    if ($insertStmt->execute()) {
        $userId = $conn->insert_id;
        
        sendResponse(true, 'Registration successful', [
            'user' => [
                'id' => $userId,
                'name' => $name,
                'email' => $email,
                'api_token' => $apiToken
            ],
            'token' => $apiToken
        ]);
    } else {
        sendResponse(false, 'Registration failed: ' . $conn->error, null, 500);
    }
    
    $stmt->close();
    $insertStmt->close();
} catch (Exception $e) {
    sendResponse(false, 'Registration failed: ' . $e->getMessage(), null, 500);
}
?>
