<?php
// register.php
header("Content-Type: application/json; charset=UTF-8");

// Inklusi file keamanan dan logger
require 'security.php';
require 'logger.php';
require 'rate_limit.php';

// Inklusi file koneksi database
require 'db.php';

// Cek metode request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    log_activity("Method Not Allowed on register.php from IP: " . $_SERVER['REMOTE_ADDR']);
    exit;
}

// Terapkan rate limiting spesifik endpoint
$identifier = $_SERVER['REMOTE_ADDR'] . ':' . $_SERVER['REQUEST_URI'];
rate_limit($pdo, 50, 60, $identifier); // Misalnya, maksimal 50 permintaan per menit

// Ambil dan sanitasi input
$input = json_decode(file_get_contents('php://input'), true);
$input = sanitize_input($input);

// Validasi input
$required_fields = ['name', 'email', 'password', 'phone'];
foreach ($required_fields as $field) {
    if (empty($input[$field])) {
        http_response_code(400);
        echo json_encode(['error' => "$field is required"]);
        log_activity("Missing $field in registration from IP: " . $_SERVER['REMOTE_ADDR']);
        exit;
    }
}

$name = $input['name'];
$email = $input['email'];
$password = $input['password'];
$phone = $input['phone'];

// Validasi email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid email format']);
    log_activity("Invalid email format '$email' in registration.");
    exit;
}

// Validasi password (misalnya minimal 8 karakter)
if (strlen($password) < 8) {
    http_response_code(400);
    echo json_encode(['error' => 'Password must be at least 8 characters']);
    log_activity("Weak password attempt during registration.");
    exit;
}

// Hash password
$hashed_password = password_hash($password, PASSWORD_BCRYPT);

// Insert pengguna ke database
try {
    // Cek apakah email sudah terdaftar
    $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$email]);
    if ($stmt->fetch()) {
        http_response_code(409); // Conflict
        echo json_encode(['error' => 'Email already registered']);
        log_activity("Email '$email' already registered.");
        exit;
    }

    // Insert pengguna baru
    $stmt = $pdo->prepare("INSERT INTO users (name, email, password, phone) VALUES (?, ?, ?, ?)");
    $stmt->execute([$name, $email, $hashed_password, $phone]);

    http_response_code(201); // Created
    echo json_encode(['message' => 'User registered successfully']);
    log_activity("New user registered: '$email' from IP: " . $_SERVER['REMOTE_ADDR']);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
    log_activity("register.php server error: " . $e->getMessage());
    exit;
}
?>
