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

// Get the user ID from session
$user_id = $_SESSION['user_id'];

// Initialize variables with default values
$nama_lengkap = $no_hp = $email = "";

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get and sanitize the input data
    $nama_lengkap = htmlspecialchars(trim($_POST['nama_lengkap']));
    $no_hp = htmlspecialchars(trim($_POST['no_hp']));
    $email = htmlspecialchars(trim($_POST['email']));

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

    // Validasi No. WhatsApp (harus 10-15 digit angka)
    if (!preg_match("/^\d{10,15}$/", $no_hp)) {
        $_SESSION['error'] = "Nomor WhatsApp harus berupa angka dan 10-15 digit!";
        header("Location: ./");
        exit();
    }

    // Validasi email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $_SESSION['error'] = "Format email tidak valid!";
        header("Location: ./");
        exit();
    }

    // Cek apakah email sudah digunakan oleh user lain
    $checkEmail = "SELECT id_user FROM users WHERE email = ? AND id_user != ?";
    $stmt = $conn->prepare($checkEmail);
    $stmt->bind_param("si", $email, $user_id);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $_SESSION['error'] = "Email sudah digunakan oleh pengguna lain!";
        header("Location: ./");
        exit();
    }
    $stmt->close();

    // Update data jika validasi lolos
    $sql = "UPDATE users SET nama_lengkap = ?, no_hp = ?, email = ? WHERE id_user = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sssi", $nama_lengkap, $no_hp, $email, $user_id);

    // Eksekusi update
    if ($stmt->execute()) {
        $_SESSION['success'] = "Data berhasil diperbarui!";
        unset($_SESSION['old_input']); // Hapus old input setelah sukses
        header("Location: ./");
        exit();
    } else {
        $_SESSION['error'] = "Terjadi kesalahan saat memperbarui data!";
        header("Location: ./");
        exit();
    }

    // Tutup statement
    $stmt->close();
}

// Tutup koneksi database
$conn->close();
?>
