<?php
date_default_timezone_set('Asia/Jakarta'); // Set waktu WIB

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');

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

// Koneksi Database 
include 'Connection.php';

// Ambil Input
$input = json_decode(file_get_contents('php://input'), true);
$username = trim($input['username'] ?? $_POST['username'] ?? ''); // Username
$password = $input['password'] ?? $_POST['password'] ?? '';       // Password

// Validasi Kosong
if (empty($username) || empty($password)) {
    echo json_encode(["status" => "error", "message" => "Username and password are required"]);
    exit;
}

// Validasi Password 
if (strlen($password) < 6) {
    echo json_encode(["status" => "error", "message" => "Password must be at least 6 characters"]);
    exit;
}

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

// Cek Username
$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 already taken"]);
    $check->close();
    $conn->close();
    exit;
}
$check->close();

// Simpan User Baru
$hashedPassword = password_hash($password, PASSWORD_DEFAULT); // Hash password
$created_at = date("Y-m-d H:i:s"); // Waktu daftar

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

if ($stmt->execute()) {
    $new_user_id = $stmt->insert_id; // Ambil ID user baru

    session_start();                 // Mulai session
    $_SESSION['user_id'] = $new_user_id; // Set session ID
    $_SESSION['username'] = $username;   // Set session username

    echo json_encode([
        "status" => "success",
        "message" => "Registration successful",
        "registered_at" => $created_at
    ]);
} else {
    echo json_encode([
        "status" => "error",
        "message" => "Registration failed"
    ]);
}

$stmt->close(); // Tutup statement
$conn->close(); // Tutup DB
?>