<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    exit;
}

require "../../config/database.php";
require "../../helpers/response.php";

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

$username = trim($input["username"] ?? "");
$nama = trim($input["nama"] ?? "");
$email = trim($input["email"] ?? "");
$password = trim($input["password"] ?? "");
$role = trim($input["role"] ?? "sppg");
$status = trim($input["status"] ?? "Aktif");

if ($username === "" || $nama === "" || $email === "" || $password === "") {
    response(false, "Username, nama, email, dan password wajib diisi", null);
}

$checkSql = "SELECT id FROM users WHERE username = ? OR email = ? LIMIT 1";
$checkStmt = $conn->prepare($checkSql);
$checkStmt->bind_param("ss", $username, $email);
$checkStmt->execute();
$checkResult = $checkStmt->get_result();

if ($checkResult->num_rows > 0) {
    response(false, "Username atau email sudah digunakan", null);
}

$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

$sql = "
    INSERT INTO users
    (
        username,
        nama,
        email,
        password,
        role,
        status
    )
    VALUES (?, ?, ?, ?, ?, ?)
";

$stmt = $conn->prepare($sql);
$stmt->bind_param("ssssss", $username, $nama, $email, $hashedPassword, $role, $status);

if ($stmt->execute()) {
    response(true, "User berhasil ditambahkan", [
        "id" => $stmt->insert_id
    ]);
}

response(false, "Gagal menambahkan user", null);

?>