<?php
session_start();
include '../../koneksi.php'; // Koneksi ke database

if (!isset($_SESSION['user_id'])) {
    header("Location: ../../login/"); // Redirect ke login jika belum login
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $nama_lengkap = mysqli_real_escape_string($conn, $_POST['namalengkap']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $no_wa = mysqli_real_escape_string($conn, $_POST['no_wa']);
    $password = $_POST['password'];
    $status = "active";
    $role = "user";

    $_SESSION['old_input'] = [
        'namalengkap' => $nama_lengkap,
        'email' => $email,
        'no_wa' => $no_wa,
    ]; 

    // Validasi jika email sudah terdaftar
    $checkEmail = "SELECT * FROM users WHERE email = '$email'";
    $result = mysqli_query($conn, $checkEmail);

    if (mysqli_num_rows($result) > 0) {
        $_SESSION['error'] = "Email sudah terdaftar!";
        header("Location: ../pengguna/tambah.php");
        exit();
    }

    // Validasi Nomor WhatsApp (harus angka dan panjang 10-15 karakter)
    if (!preg_match('/^[0-9]{10,15}$/', $no_wa)) {
        $_SESSION['error'] = "Nomor WhatsApp harus terdiri dari 10-15 digit angka!";
        header("Location: ../pengguna/tambah.php");
        exit();
    }

    // Validasi Password (minimal 8 karakter)
    if (strlen($password) < 8) {
        $_SESSION['error'] = "Password harus memiliki minimal 8 karakter!";
        header("Location: ../pengguna/tambah.php");
        exit();
    }

    // Hash password untuk keamanan
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // Insert ke database
    $query = "INSERT INTO users (nama_lengkap, email, no_hp, password, status, role) 
              VALUES ('$nama_lengkap', '$email', '$no_wa', '$hashed_password', '$status', '$role')";

    if (mysqli_query($conn, $query)) {
        $_SESSION['success'] = "Data User berhasil ditambahkan!";
          unset($_SESSION['old_input']);
    } else {
        $_SESSION['error'] = "Gagal menambahkan user!";
    }

    header("Location: ../pengguna/");
    exit();
} else {
    $_SESSION['error'] = "Akses tidak diizinkan!";
    header("Location: ../pengguna/");
    exit();
}
?>
