<?php
/**
 * admin_list_transactions.php
 * Admin endpoint to list transactions with filters and pagination
 */

// JSON + caching headers
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

// Dynamic CORS with credentials
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (!empty($origin)) {
    header('Access-Control-Allow-Origin: ' . $origin);
} else {
    $scheme = $_SERVER['REQUEST_SCHEME'] ?? 'https';
    $host = $_SERVER['HTTP_HOST'] ?? '';
    if (!empty($host)) {
        header('Access-Control-Allow-Origin: ' . $scheme . '://' . $host);
    }
}
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

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

// Helpers
function jerr($msg, $code = 400) { http_response_code($code); echo json_encode(['success' => false, 'message' => $msg]); exit; }

try {
    // Detect created_at and optional text columns for filters
    $hasCreated = false; $hasDetails = false; $hasReference = false;
    try {
        $c0 = $pdo->query("SHOW COLUMNS FROM transactions LIKE 'created_at'");
        $hasCreated = $c0 && $c0->rowCount() > 0;
    } catch (Exception $ignore) {}
    try {
        $c1 = $pdo->query("SHOW COLUMNS FROM transactions LIKE 'details'");
        $hasDetails = $c1 && $c1->rowCount() > 0;
    } catch (Exception $ignore) {}
    try {
        $c2 = $pdo->query("SHOW COLUMNS FROM transactions LIKE 'reference'");
        $hasReference = $c2 && $c2->rowCount() > 0;
    } catch (Exception $ignore) {}

    // Params
    $type = isset($_GET['type']) ? strtolower(trim($_GET['type'])) : '';
    $status = isset($_GET['status']) ? strtolower(trim($_GET['status'])) : '';
    $userId = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $perPage = isset($_GET['per_page']) ? intval($_GET['per_page']) : 20;
    if ($perPage <= 0) $perPage = 20; if ($perPage > 100) $perPage = 100;
    $offset = ($page - 1) * $perPage;
    $dateFrom = isset($_GET['date_from']) ? trim($_GET['date_from']) : '';
    $dateTo = isset($_GET['date_to']) ? trim($_GET['date_to']) : '';

    $where = [];
    $params = [];

    if ($type === 'deposit' || $type === 'withdrawal') {
        $where[] = 't.type = ?';
        $params[] = $type;
    }
    if (in_array($status, ['pending','completed','rejected','failed'])) {
        $where[] = 't.status = ?';
        $params[] = $status;
    }
    if ($userId > 0) {
        $where[] = 't.user_id = ?';
        $params[] = $userId;
    }
    if ($search !== '') {
        $like = '%' . $search . '%';
        $parts = [];
        if ($hasReference) { $parts[] = 't.reference LIKE ?'; }
        if ($hasDetails) { $parts[] = 't.details LIKE ?'; }
        $parts[] = 'u.username LIKE ?';
        $parts[] = 'u.email LIKE ?';
        $where[] = '(' . implode(' OR ', $parts) . ')';
        // Bind in the same order
        if ($hasReference) { $params[] = $like; }
        if ($hasDetails) { $params[] = $like; }
        array_push($params, $like, $like);
    }
    if ($hasCreated && $dateFrom !== '') {
        $where[] = 'DATE(t.created_at) >= ?';
        $params[] = $dateFrom;
    }
    if ($hasCreated && $dateTo !== '') {
        $where[] = 'DATE(t.created_at) <= ?';
        $params[] = $dateTo;
    }

    $whereSql = count($where) ? (' WHERE ' . implode(' AND ', $where)) : '';

    // Determine order column
    $order = $hasCreated ? 't.created_at DESC' : 't.id DESC';

    // Count total
    $countSql = "SELECT COUNT(*) AS cnt FROM transactions t LEFT JOIN users u ON t.user_id = u.id" . $whereSql;
    $countStmt = $pdo->prepare($countSql);
    $countStmt->execute($params);
    $total = (int)($countStmt->fetchColumn() ?: 0);

    // Fetch page
    $sql = "SELECT t.*, u.username, u.email FROM transactions t LEFT JOIN users u ON t.user_id = u.id" . $whereSql . " ORDER BY $order LIMIT $perPage OFFSET $offset";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

    echo json_encode([
        'success' => true,
        'transactions' => $rows,
        'pagination' => [
            'page' => $page,
            'per_page' => $perPage,
            'total' => $total,
            'pages' => $perPage > 0 ? (int)ceil($total / $perPage) : 1
        ]
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Failed to list transactions: ' . $e->getMessage()]);
}
