<?php
include '../auth.php';
include '../../koneksi.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $id = $_POST['id'];
    $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']);

    // Simpan input lama jika terjadi error
    $_SESSION['old_input'] = $_POST;

    // Cek apakah email sudah digunakan oleh user lain
    $checkEmail = "SELECT id_user FROM users WHERE email = '$email' AND id_user != '$id'";
    $resultEmail = mysqli_query($conn, $checkEmail);
    if (mysqli_num_rows($resultEmail) > 0) {
        $_SESSION['error'] = "Email sudah digunakan oleh pengguna lain!";
        header("Location: ../pengguna/update.php?id=$id");
        exit();
    }

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

    // Validasi Password (jika diisi, minimal 8 karakter)
    if (!empty($_POST['password']) && strlen($_POST['password']) < 8) {
        $_SESSION['error'] = "Password harus memiliki minimal 8 karakter!";
        header("Location: ../pengguna/update.php?id=$id");
        exit();
    }

    // Query awal tanpa status, role, dan password
    $query = "UPDATE users SET 
                nama_lengkap = '$nama_lengkap', 
                email = '$email', 
                no_hp = '$no_wa'";

    // Jika role diisi, update
    if (!empty($_POST['role'])) {
        $role = mysqli_real_escape_string($conn, $_POST['role']);
        $query .= ", role = '$role'";
    }

    // Jika status diisi, update
    if (!empty($_POST['status'])) {
        $status = mysqli_real_escape_string($conn, $_POST['status']);
        $query .= ", status = '$status'";
    }

    // Jika password diisi, update dengan hash
    if (!empty($_POST['password'])) {
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $query .= ", password = '$password'";
    }

    $query .= " WHERE id_user = '$id'";

    // Eksekusi query
    if (mysqli_query($conn, $query)) {
        $_SESSION['success'] = "Data pengguna berhasil diperbarui!";
        unset($_SESSION['old_input']); // Hapus old input setelah sukses
    } else {
        $_SESSION['error'] = "Gagal memperbarui data: " . mysqli_error($conn);
    }

    // Redirect kembali ke halaman pengguna
    header("Location: ../pengguna/");
    exit;
}
?>
