<?php
require_once __DIR__ . '/../server/db.php';
require_once __DIR__ . '/../server/config.php';

if (session_status() !== PHP_SESSION_ACTIVE) session_start();

$email = trim($_POST['email'] ?? '');
$pass  = (string)($_POST['password'] ?? '');

if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  http_response_code(400);
  exit("Invalid email.");
}
if (strlen($pass) < 8) {
  http_response_code(400);
  exit("Password must be at least 8 characters.");
}

$hash = password_hash($pass, PASSWORD_DEFAULT);

$stmt = $conn->prepare("INSERT INTO admins (email, pass_hash) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $hash);

try {
  $stmt->execute();
  $_SESSION['admin_id'] = (int)$stmt->insert_id;
  header("Location: " . APP_BASE . "admin/dashboard.php");
  exit;
} catch (mysqli_sql_exception $e) {
  http_response_code(400);
  exit("Account already exists or cannot be created.");
}
