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

$error = "";
$success = "";


function isValidFullname($name) {
    return !preg_match('/\d/', $name);
}

if ($_SERVER["REQUEST_METHOD"] === "POST") { 
    $fullname = trim($_POST['fullname']);
    $gender = $_POST['gender']; 
    $birthdate = $_POST['birthdate'];
    $email = trim($_POST['email']);
    $password = $_POST['password'];
    $confirm = $_POST['confirm'];

if (
        empty($fullname) && empty($gender) && empty($birthdate) &&
        empty($email) && empty($password) && empty($confirm)
    ) {
        $errors['all'] = "Semua field wajib diisi!";
    } else {
    if (empty($fullname)) {
        $error = "Mohon isi nama!";
    }
    elseif (!isValidFullname($fullname)) {
        $error = "Nama tidak boleh mengandung angka!";
    }
    elseif (empty($email)) {
        $error = "Mohon isi email!";
    }
    elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Format email tidak valid!";
    }
    elseif (empty($password)) {
        $error = "Mohon isi password!";
    }
    elseif (strlen($password) < 8) {
        $error = "Password harus minimal 8 karakter!";
    }
    elseif (!preg_match('/\d/', $password)) {
        $error = "Password harus mengandung angka!";
    }
    elseif (!preg_match('/[a-zA-Z]/', $password)) {
        $error = "Password harus mengandung huruf!";
    }
    elseif ($password !== $confirm) {
        $error = "Konfirmasi password tidak cocok!";
    }
    else {
        $check = $conn->prepare("SELECT * FROM members WHERE email = ?");
        $check->bind_param("s", $email);
        $check->execute();
        $result = $check->get_result();

        if ($result->num_rows > 0) {
            $error = "Email sudah digunakan. Silakan gunakan email lain.";
        } else {
            $jenis_kelamin = ($gender === 'Laki-laki') ? 'L' : 'P';
            $hashed_password = md5($password);

            $defaultFotoPath = __DIR__ . '/../img/user.jpeg';
            $fotoDefault = file_get_contents($defaultFotoPath);

            if ($fotoDefault === false) {
                $error = "Gagal membaca file gambar default.";
            } else {
                $stmt = $conn->prepare("INSERT INTO members (nama, email, password, jenis_kelamin, tanggal_lahir, foto_member) VALUES (?, ?, ?, ?, ?, ?)");
                
                $null = null;
                $stmt->bind_param("sssssb", $fullname, $email, $hashed_password, $jenis_kelamin, $birthdate, $null);
                $stmt->send_long_data(5, $fotoDefault);

                if ($stmt->execute()) {
                    $success = "Registrasi berhasil! Silakan login.";
                    header("Location: login.php");
                    exit();
                } else {
                    $error = "Gagal registrasi: " . $stmt->error;
                }
                $stmt->close();
            }
        }
        $check->close();
        $conn->close();
    }
}
}
?>
