<?php
// Define TONSUI_LOADED constant to prevent direct access to session_init.php
if (!defined('TONSUI_LOADED')) {
  define('TONSUI_LOADED', true);
}
require_once __DIR__ . '/session_init.php';
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/auth.php';

header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (!empty($origin)) {
  header('Access-Control-Allow-Origin: ' . $origin);
} else if (!empty($_SERVER['HTTP_HOST'])) {
  $scheme = $_SERVER['REQUEST_SCHEME'] ?? 'https';
  header('Access-Control-Allow-Origin: ' . $scheme . '://' . $_SERVER['HTTP_HOST']);
}
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

// Admin only
requireAdmin(true);

try {
  // Check column exists
  $hasAcc = false;
  try {
    $c1 = $pdo->query("SHOW COLUMNS FROM users LIKE 'account_number'");
    $hasAcc = $c1 && $c1->rowCount() > 0;
  } catch (Exception $e) {}
  if (!$hasAcc) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Account number column not found']);
    exit;
  }
  // Generate unique 12-digit number
  $attempts = 0; $candidate = null; $exists = true;
  do {
    $candidate = str_pad((string)random_int(0, 999999999999), 12, '0', STR_PAD_LEFT);
    $chk = $pdo->prepare('SELECT id FROM users WHERE account_number = ? LIMIT 1');
    $chk->execute([$candidate]);
    $exists = (bool)$chk->fetch(PDO::FETCH_ASSOC);
    $attempts++;
  } while ($exists && $attempts < 20);
  if ($exists) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Failed to generate unique account number']);
    exit;
  }
  echo json_encode(['success' => true, 'account_number' => $candidate]);
} catch (Exception $e) {
  http_response_code(500);
  echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
