<?php
header('Content-Type: application/json');
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/admin_auth.php';

if (!isAdminLoggedIn()) {
  echo json_encode(['success' => false, 'error' => 'Not authorized']);
  exit;
}

try {
  $pdo = getDB();
  $status = isset($_GET['status']) ? $_GET['status'] : null;
  if ($status) {
    $stmt = $pdo->prepare("SELECT l.*, u.username, u.email FROM loans l JOIN users u ON u.id = l.user_id WHERE l.status = :status ORDER BY l.created_at DESC");
    $stmt->execute([':status' => $status]);
  } else {
    $stmt = $pdo->query("SELECT l.*, u.username, u.email FROM loans l JOIN users u ON u.id = l.user_id ORDER BY l.created_at DESC");
  }
  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  echo json_encode(['success' => true, 'data' => $rows]);
} catch (Throwable $e) {
  echo json_encode(['success' => false, 'error' => 'Server error']);
}
