<?php
require __DIR__ . '/config.php';
$in = json_input();
$name = trim($in['name'] ?? '');
$email = trim($in['email'] ?? '');
$password = (string)($in['password'] ?? '');
$role = $in['role'] ?? 'student';
if (!in_array($role, ['student','admin'])) $role = 'student';
if ($name === '' || $email === '' || $password === '') {
  respond(['error'=>'VALIDATION','message'=>'Nama, email, dan password wajib diisi'], 422);
}
try {
  $stmt = $pdo->prepare('SELECT id FROM users WHERE email = ? LIMIT 1');
  $stmt->execute([$email]);
  if ($stmt->fetch()) respond(['error'=>'EMAIL_EXISTS','message'=>'Email sudah terdaftar'], 409);
  $hash = password_hash($password, PASSWORD_BCRYPT);
  $stmt = $pdo->prepare('INSERT INTO users(name,email,password_hash,role) VALUES(?,?,?,?)');
  $stmt->execute([$name,$email,$hash,$role]);
  $id = (int)$pdo->lastInsertId();
  $_SESSION['uid'] = $id; $_SESSION['role'] = $role;
  respond(['id'=>$id,'name'=>$name,'email'=>$email,'role'=>$role]);
} catch (Throwable $e) {
  respond(['error'=>'REGISTER_FAILED','message'=>$e->getMessage()], 500);
}
