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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Tangkap data dari form dan filter input
    $full_name = trim(htmlspecialchars($_POST['full_name']));
    $email = trim(filter_var($_POST['email'], FILTER_SANITIZE_EMAIL));
    $phone = trim(htmlspecialchars($_POST['phone']));
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];

    // Simpan input sebelumnya di session, kecuali password
    $_SESSION['old_input'] = [
        'nama_lengkap' => $full_name,
        'email' => $email,
        'no_hp' => $phone,
    ];

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

    if (!preg_match("/^[0-9]{10,13}$/", $phone)) { // Minimal 10 dan maksimal 13 angka
        $_SESSION['error'] = "Nomor WhatsApp harus berupa angka dan 10-13 digit!";
        header("Location: ../register");
        exit();
    }

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

    if ($password !== $confirm_password) {
        $_SESSION['error'] = "Password dan Konfirmasi Password tidak cocok!";
        header("Location: ../register");
        exit();
    }

    // Cek apakah email sudah terdaftar
    $check_email_stmt = $conn->prepare("SELECT id_user FROM users WHERE email = ?");
    $check_email_stmt->bind_param("s", $email);
    $check_email_stmt->execute();
    $check_email_stmt->store_result();

    if ($check_email_stmt->num_rows > 0) {
        $_SESSION['error'] = "Email sudah digunakan, silakan gunakan email lain.";
        header("Location: ../register");
        exit();
    }
    $check_email_stmt->close();

    // Hash password sebelum disimpan ke database
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // Insert data jika koneksi tersedia
    if ($conn) {
        $stmt = $conn->prepare("INSERT INTO users (nama_lengkap, email, no_hp, password) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("ssss", $full_name, $email, $phone, $hashed_password);

        if ($stmt->execute()) {
            $_SESSION['success'] = "Registrasi berhasil! Silakan login.";
            header("Location: ../login");
            unset($_SESSION['old_input']); // Hapus data lama setelah berhasil registrasi
            exit();
        } else {
            $_SESSION['error'] = "Gagal mendaftar: " . $stmt->error;
        }

        $stmt->close();
    } else {
        $_SESSION['error'] = "Koneksi database tidak tersedia.";
    }

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

    header("Location: ../register");
    exit();
}
?>
