<?php
require_once __DIR__ . '/../server/db.php';
require_once __DIR__ . '/../server/auth.php';
require_once __DIR__ . '/../server/config.php';
require_admin();

$admin_id = admin_id();
$name = trim($_POST['name'] ?? '');
if ($name === '') { http_response_code(400); exit("Missing organization name."); }

function make_code(): string {
  $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  $out = '';
  for ($i=0; $i<8; $i++) $out .= $chars[random_int(0, strlen($chars)-1)];
  return $out;
}

$code = make_code();

// Ensure uniqueness
for ($i=0; $i<5; $i++) {
  $stmt = $conn->prepare("SELECT id FROM organizations WHERE share_code = ? LIMIT 1");
  $stmt->bind_param("s", $code);
  $stmt->execute();
  $exists = $stmt->get_result()->fetch_assoc();
  $stmt->close();
  if (!$exists) break;
  $code = make_code();
}

$stmt = $conn->prepare("INSERT INTO organizations (admin_id, name, share_code) VALUES (?, ?, ?)");
$stmt->bind_param("iss", $admin_id, $name, $code);
$stmt->execute();
$stmt->close();

header("Location: " . APP_BASE . "admin/dashboard.php");
exit;
