<?php
require __DIR__ . '/config.php';
$in = json_input();
$email = trim($in['email'] ?? '');
$password = (string)($in['password'] ?? '');
if ($email === '' || $password === '') {
  respond(['error'=>'VALIDATION','message'=>'Email dan password wajib diisi'], 422);
}
try {
  $stmt = $pdo->prepare('SELECT id,name,email,password_hash,role FROM users WHERE email = ? LIMIT 1');
  $stmt->execute([$email]);
  $u = $stmt->fetch();
  if (!$u) respond(['error'=>'NOT_FOUND','message'=>'User tidak ditemukan'], 404);
  if (!$u['password_hash'] || !password_verify($password, $u['password_hash'])) {
    respond(['error'=>'BAD_CREDENTIALS','message'=>'Password salah'], 401);
  }
  $_SESSION['uid'] = (int)$u['id']; $_SESSION['role'] = $u['role'];
  respond(['id'=>(int)$u['id'],'name'=>$u['name'],'email'=>$u['email'],'role'=>$u['role']]);
} catch (Throwable $e) {
  respond(['error'=>'LOGIN_FAILED','message'=>$e->getMessage()], 500);
}
