<?php
header('Content-Type: application/json');
include '../config/koneksi.php';
include '../config/id_generator.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $nama = $_POST['lengkap_nm'] ?? '';
    $wa = $_POST['whatsapp_no'] ?? '';
    $email = $_POST['email_tx'] ?? '';
    $pass = $_POST['password_tx'] ?? '';

    // Cek Unik
    $stmtCheck = $conn->prepare("SELECT user_id FROM mst_user WHERE email_tx = ? OR whatsapp_no = ?");
    $stmtCheck->bind_param("ss", $email, $wa);
    $stmtCheck->execute();
    if ($stmtCheck->get_result()->num_rows > 0) {
        echo json_encode(["status" => "gagal", "pesan" => "Email atau WA sudah terdaftar!", "data" => []]);
        exit;
    }

    $user_id = generateUserId($conn);
    $hashedPass = password_hash($pass, PASSWORD_DEFAULT);
    $stmt = $conn->prepare("INSERT INTO mst_user (user_id, lengkap_nm, whatsapp_no, email_tx, password_tx, role_nm) VALUES (?, ?, ?, ?, ?, 'Pelanggan')");
    $stmt->bind_param("sssss", $user_id, $nama, $wa, $email, $hashedPass);
    
    if ($stmt->execute()) {
        echo json_encode(["status" => "sukses", "pesan" => "Pendaftaran berhasil!", "data" => []]);
    } else {
        echo json_encode(["status" => "gagal", "pesan" => "Gagal mendaftar", "data" => []]);
    }
}
?>