<?php
header('Content-Type: application/json');
// CORS for credentialed requests
$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');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

define('TONSUI_LOADED', true);
require_once __DIR__ . '/session_init.php';
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }
requireLogin(true);
require_once __DIR__ . '/db.php';

try {
  $userId = $_SESSION['user_id'] ?? 0;
  if (!$userId) { echo json_encode(['success'=>false,'error'=>'Not authenticated']); exit; }

  // Get routing number from settings (fallback default)
  $routing = '110000000';
  try {
    $st = $pdo->query("SHOW TABLES LIKE 'settings'");
    if ($st && $st->rowCount() > 0) {
      $s2 = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key='routing_number' LIMIT 1");
      $s2->execute();
      $row = $s2->fetch(PDO::FETCH_ASSOC);
      if ($row && isset($row['setting_value']) && trim($row['setting_value']) !== '') {
        $routing = trim($row['setting_value']);
      }
    }
  } catch (Throwable $e) {}

  // Ensure account_number column presence and value (generate if missing)
  $hasAccountNumber = false; $hasProfilePicture = false;
  try {
    $cols = $pdo->query("SHOW COLUMNS FROM users");
    while ($c = $cols->fetch(PDO::FETCH_ASSOC)) {
      $f = strtolower($c['Field'] ?? '');
      if ($f === 'account_number') $hasAccountNumber = true;
      if ($f === 'profile_picture') $hasProfilePicture = true;
    }
  } catch (Throwable $e) {}

  if (!$hasAccountNumber) {
    // Try to add the column silently
    try { $pdo->exec("ALTER TABLE users ADD COLUMN account_number VARCHAR(20) NULL"); $hasAccountNumber = true; }
    catch (Throwable $e) { /* ignore if cannot add */ }
  }

  // Fetch current info
  $stmt = $pdo->prepare("SELECT id, username, name, email" . ($hasAccountNumber?", account_number":"") . ($hasProfilePicture?", profile_picture":"") . " FROM users WHERE id=? LIMIT 1");
  $stmt->execute([$userId]);
  $user = $stmt->fetch(PDO::FETCH_ASSOC);
  if (!$user) { echo json_encode(['success'=>false,'error'=>'User not found']); exit; }

  if (empty($user['account_number'])) {
    // Generate unique 12-digit number
    $attempt = 0; $acc = null;
    do {
      $acc = 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([$acc]);
      $exists = $chk->fetch(PDO::FETCH_ASSOC);
      $attempt++;
      if ($attempt > 10) break;
    } while($exists);
    if ($acc) {
      $upd = $pdo->prepare("UPDATE users SET account_number=? WHERE id=?");
      $upd->execute([$acc, $userId]);
      $user['account_number'] = $acc;
    }
  }

  echo json_encode([
    'success' => true,
    'data' => [
      'name' => $user['name'] ?? ($user['username'] ?? ''),
      'username' => $user['username'] ?? '',
      'profile_picture' => $user['profile_picture'] ?? null,
      'account_number' => $user['account_number'] ?? null,
      'routing_number' => $routing,
    ]
  ]);
} catch (Throwable $e) {
  echo json_encode(['success'=>false,'error'=>'Server error']);
}
