<?php
// ✅ Set timezone Indonesia (WIB)
date_default_timezone_set('Asia/Jakarta');

// ✅ CORS Headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Max-Age: 86400');
header('Content-Type: application/json');

// ✅ Handle preflight OPTIONS
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

include 'Connection.php';

// ✅ Handle input
$input = json_decode(file_get_contents('php://input'), true);
$username = trim($input['username'] ?? $_POST['username'] ?? '');
$password = $input['password'] ?? $_POST['password'] ?? '';

// ✅ Validasi input kosong
if (empty($username) || empty($password)) {
    echo json_encode([
        "status" => "error", 
        "message" => "Username dan password wajib diisi"
    ]);
    exit;
}

// ✅ Validasi panjang password
if (strlen($password) < 6) {
    echo json_encode([
        "status" => "error", 
        "message" => "Password minimal 6 karakter"
    ]);
    exit;
}

// ✅ Validasi format username
if (!preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username)) {
    echo json_encode([
        "status" => "error", 
        "message" => "Username hanya boleh huruf, angka, underscore (3-20 karakter)"
    ]);
    exit;
}

// ✅ Cek apakah username sudah ada
$check = $conn->prepare("SELECT id FROM users WHERE username = ?");
$check->bind_param("s", $username);
$check->execute();
$check->store_result();

if ($check->num_rows > 0) {
    echo json_encode([
        "status" => "error", 
        "message" => "Username sudah digunakan"
    ]);
    $check->close();
    $conn->close();
    exit;
}
$check->close();

// ✅ Hash password dan insert ke database
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$created_at = date("Y-m-d H:i:s"); 

$stmt = $conn->prepare("INSERT INTO users (username, password, created_at) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $hashedPassword, $created_at);

if ($stmt->execute()) {
    // 🔥 PERBAIKAN UTAMA DI SINI (AUTO-LOGIN) 🔥
    $new_user_id = $stmt->insert_id; // Ambil ID user baru
    
    session_start();
    $_SESSION['user_id'] = $new_user_id; // Set Session ID
    $_SESSION['username'] = $username;   // Set Session Username

    echo json_encode([
        "status" => "success", 
        "message" => "Pendaftaran berhasil & Auto-login",
        "registered_at" => $created_at
    ]);
} else {
    echo json_encode([
        "status" => "error", 
        "message" => "Gagal mendaftar: " . $conn->error
    ]);
}

$stmt->close();
$conn->close();
?>