<?php
// api/register.php
session_start();
include '../config/database.php';

// 1. Ambil data dari form (email, username, password)
$email    = mysqli_real_escape_string($conn, $_POST['email'] ?? '');
$username = mysqli_real_escape_string($conn, $_POST['username'] ?? '');
$password = $_POST['password'] ?? '';

// 2. Enkripsi Password
$hashed_password = password_hash($password, PASSWORD_DEFAULT);

// 3. Cek apakah Username atau Email sudah pernah didaftarkan
$cek_query = mysqli_query($conn, "SELECT id FROM users WHERE username = '$username' OR email_guru = '$email'");
if (mysqli_num_rows($cek_query) > 0) {
    echo "<script>alert('Username atau Email sudah terdaftar!'); window.location.href='../auth/register_page.php';</script>";
    exit;
}

// 4. Masukkan data ke Database (KOLOM 'nama' SUDAH DIHAPUS DARI SINI)
$query_insert = "INSERT INTO users (username, password, role, status_broadcast, email_guru, status_akun, kuota_harian) 
                 VALUES ('$username', '$hashed_password', 'siswa', 'none', '$email', 'free', 10)";

if (mysqli_query($conn, $query_insert)) {
    // Jika sukses, arahkan ke halaman login
    echo "<script>alert('Pendaftaran berhasil! Silakan login.'); window.location.href='../auth/login_page.php';</script>";
} else {
    // Jika gagal, tampilkan error SQL-nya
    echo "Error Database: " . mysqli_error($conn);
}
?>