<?php
session_start();
include 'koneksi.php';

$nik = $_POST['nik'];
$nama = $_POST['nama'];
$username = $_POST['username'];
$password = $_POST['password'];
$role = $_POST['role'];

// Validasi NIK harus 16 digit
if (strlen($nik) != 16) {
    $alert = "NIK harus 16 digit!";
    header("location: daftar.php?alert=invalid_nik&message=" . urlencode($alert));
    exit();
}

if ($role == 'pelanggan') {
    $check_query = "SELECT * FROM tbl_pelanggan WHERE nik = '$nik'";
    $insert_query = "INSERT INTO tbl_pelanggan (nik, nama_pelanggan, username, password) VALUES ('$nik', '$nama', '$username', '$password')";
} elseif ($role == 'kurir') {
    $check_query = "SELECT * FROM tbl_kurir WHERE nik = '$nik'";
    $insert_query = "INSERT INTO tbl_kurir (nik, nama_kurir, username, password) VALUES ('$nik', '$nama', '$username', '$password')";
} else {
    $alert = "Role tidak valid!";
    header("location: daftar.php?alert=role_invalid&message=" . urlencode($alert));
    exit();
}

$result = mysqli_query($koneksi, $check_query);

if (mysqli_num_rows($result) > 0) {
    $alert = "NIK sudah digunakan!";
    header("location: daftar.php?alert=nik_terdaftar&message=" . urlencode($alert));
} else {
    if (mysqli_query($koneksi, $insert_query)) {
        $alert = "Akun berhasil terdaftar!";
        header("location: login.php?alert=daftar_sukses&message=" . urlencode($alert));
    } else {
        header("location: daftar.php?alert=daftar_gagal");
    }
}
?>
