<?php
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();
requireAdmin();

$orders = readJson(ORDERS_FILE);
$users = readJson(USERS_FILE);
$usersById = [];
foreach ($users as $u) {
    $usersById[$u['id']] = $u;
}

$search = trim($_GET['search'] ?? '');
$status = trim($_GET['status'] ?? '');
$type = trim($_GET['type'] ?? '');
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;

$sorted = array_reverse($orders);

$filtered = [];
foreach ($sorted as $o) {
    $u = !empty($o['user_id']) ? ($usersById[$o['user_id']] ?? null) : null;
    $email = $u ? ($u['email'] ?? '') : '';
    $oid = $o['order_id'] ?? '';
    $utr = $o['utr'] ?? '';
    $oStatus = $o['status'] ?? '';
    $oType = $o['type'] ?? '';

    if ($status !== '' && $oStatus !== $status) continue;
    if ($type !== '' && $oType !== $type) continue;
    if ($search !== '' && stripos($oid, $search) === false && stripos($email, $search) === false && stripos($utr, $search) === false) continue;

    $filtered[] = [
        'order_id' => $oid,
        'user' => $email,
        'type' => $oType,
        'amount' => number_format(floatval($o['amount'] ?? 0), 2),
        'amount_raw' => floatval($o['amount'] ?? 0),
        'status' => $oStatus,
        'utr' => $utr,
        'created_at' => $o['created_at'] ?? ''
    ];
}

$total = count($filtered);
$totalPages = max(1, ceil($total / $perPage));
$page = min($page, $totalPages);
$start = ($page - 1) * $perPage;
$pageItems = array_slice($filtered, $start, $perPage);

jsonResponse([
    'status' => 'success',
    'total' => $total,
    'page' => $page,
    'total_pages' => $totalPages,
    'per_page' => $perPage,
    'transactions' => $pageItems
]);
