<?php
// Admin: List user applications
header('Content-Type: application/json');
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

define('TONSUI_LOADED', true);
require_once __DIR__ . '/session_init.php';
requireAdmin(true);
require_once __DIR__ . '/db.php';

// lightweight logger
function applog($message, $data = []) {
  try {
    $logDir = realpath(__DIR__ . '/..') . '/logs';
    if (!is_dir($logDir)) { @mkdir($logDir, 0755, true); }
    $line = '['.date('Y-m-d H:i:s')."] get_applications - " . $message;
    if (!empty($data)) { $line .= ' | ' . json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE); }
    $line .= "\n";
    @error_log($line, 3, $logDir . '/admin_applications.log');
  } catch (Throwable $e) { /* ignore */ }
}

try {
  // Ensure table exists (tolerant)
  $pdo->exec("CREATE TABLE IF NOT EXISTS user_applications (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    status VARCHAR(32) NOT NULL DEFAULT 'submitted',
    password_plain TEXT NULL,
    submission_json LONGTEXT NULL,
    admin_notes TEXT NULL,
    reviewed_at DATETIME NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX (user_id), INDEX (status)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

  $backendUrl = (isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . '/auth-backend';
  $hasUserProfiles = false;
  try {
    $t = $pdo->query("SHOW TABLES LIKE 'user_profiles'");
    $hasUserProfiles = $t && $t->rowCount() > 0;
  } catch (Exception $e) { $hasUserProfiles = false; }

  if ($hasUserProfiles) {
    $stmt = $pdo->query("SELECT a.*, u.username, u.email, u.name, u.account_number, u.balance,
        (SELECT account_photo_path FROM user_profiles WHERE user_id=a.user_id ORDER BY id DESC LIMIT 1) AS account_photo_path
      FROM user_applications a
      JOIN users u ON a.user_id = u.id
      ORDER BY a.created_at DESC");
  } else {
    $stmt = $pdo->query("SELECT a.*, u.username, u.email, u.name, u.account_number, u.balance,
        NULL AS account_photo_path
      FROM user_applications a
      JOIN users u ON a.user_id = u.id
      ORDER BY a.created_at DESC");
  }
  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  applog('fetch', ['count'=>count($rows)]);
  foreach ($rows as &$r) {
    $snap = [];
    if (!empty($r['submission_json'])) {
      $snap = json_decode($r['submission_json'], true);
      if (!is_array($snap)) $snap = [];
    }
    $r['snapshot'] = $snap;
    if (!empty($r['account_photo_path']) && !preg_match('~^https?://~', $r['account_photo_path'])) {
      $r['account_photo_path'] = $backendUrl . $r['account_photo_path'];
    }
  }
  unset($r);
  echo json_encode(['success' => true, 'applications' => $rows]);
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
