<?php
/**
 * ADMIN TRANSACTION HISTORY PAGE
 * File: admin/transactions.php
 * UPDATED WITH NEW WALLET SYSTEM - COMPLETELY NULL SAFE
 */

require_once '../app/Core/init.php';

// Check admin authentication
Auth::requireAdmin();

// Initialize models
$walletTransactionModel = new WalletTransaction();
$onlinePaymentModel = new OnlinePayment();

$page_title = "Transaction History";
$active_menu = "transactions";

// Get filter parameters
$transaction_type = $_GET['type'] ?? 'all';
$category = $_GET['category'] ?? 'all';
$user_type = $_GET['user_type'] ?? 'all';
$status = $_GET['status'] ?? 'all';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$search = $_GET['search'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 50;
$offset = ($page - 1) * $per_page;

// ============================================================
// DASHBOARD FILTER SUPPORT
// ============================================================
$dashboard_filter = $_GET['filter'] ?? '';

// Build filters
$filters = [];

// Apply dashboard filter first
if (!empty($dashboard_filter)) {
    switch ($dashboard_filter) {
        case 'current_rent_onhold':
        case 'current_rent':
            $filters['transaction_type'] = 'item_rental';
            break;
        case 'current_security':
            $filters['transaction_type'] = 'security_deposit_held';
            break;
        case 'total_withdrawn':
            $filters['transaction_type'] = 'withdrawal';
            break;
        case 'total_revenue':
            $filters['status'] = 'completed';
            break;
    }
}

if ($transaction_type !== 'all') {
    $filters['transaction_type'] = $transaction_type;
}

if ($category !== 'all') {
    $filters['category'] = $category;
}

if ($user_type !== 'all') {
    $filters['user_type'] = $user_type;
}

if ($status !== 'all') {
    $filters['status'] = $status;
}

if (!empty($date_from)) {
    $filters['date_from'] = $date_from;
}

if (!empty($date_to)) {
    $filters['date_to'] = $date_to;
}

if (!empty($search)) {
    $filters['search'] = $search;
}

// Get wallet transactions
$transactions = $walletTransactionModel->getAll($per_page, $offset, $filters);
$total_transactions = $walletTransactionModel->count($filters);
$total_pages = ceil($total_transactions / $per_page);

// Get transaction statistics - WITH COMPLETE NULL SAFETY
$stats_raw = $walletTransactionModel->getStats(null, $date_from && $date_to ? null : '30 days');
$stats = is_array($stats_raw) ? [
    'total_transactions' => isset($stats_raw['total_transactions']) ? (int)$stats_raw['total_transactions'] : 0,
    'total_credits' => isset($stats_raw['total_credits']) ? (float)$stats_raw['total_credits'] : 0.00,
    'total_debits' => isset($stats_raw['total_debits']) ? (float)$stats_raw['total_debits'] : 0.00,
    'credit_count' => isset($stats_raw['credit_count']) ? (int)$stats_raw['credit_count'] : 0,
    'debit_count' => isset($stats_raw['debit_count']) ? (int)$stats_raw['debit_count'] : 0,
    'earnings_count' => isset($stats_raw['earnings_count']) ? (int)$stats_raw['earnings_count'] : 0,
    'withdrawals_count' => isset($stats_raw['withdrawals_count']) ? (int)$stats_raw['withdrawals_count'] : 0,
    'refunds_count' => isset($stats_raw['refunds_count']) ? (int)$stats_raw['refunds_count'] : 0
] : [
    'total_transactions' => 0,
    'total_credits' => 0.00,
    'total_debits' => 0.00,
    'credit_count' => 0,
    'debit_count' => 0,
    'earnings_count' => 0,
    'withdrawals_count' => 0,
    'refunds_count' => 0
];

// Get online payment statistics - WITH COMPLETE NULL SAFETY
$payment_stats_raw = $onlinePaymentModel->getStats();
$payment_stats = is_array($payment_stats_raw) ? [
    'total_payments' => isset($payment_stats_raw['total_payments']) ? (int)$payment_stats_raw['total_payments'] : 0,
    'successful_payments' => isset($payment_stats_raw['successful_payments']) ? (int)$payment_stats_raw['successful_payments'] : 0,
    'failed_payments' => isset($payment_stats_raw['failed_payments']) ? (int)$payment_stats_raw['failed_payments'] : 0,
    'total_amount' => isset($payment_stats_raw['total_amount']) ? (float)$payment_stats_raw['total_amount'] : 0.00
] : [
    'total_payments' => 0,
    'successful_payments' => 0,
    'failed_payments' => 0,
    'total_amount' => 0.00
];

include '../templates/layouts/admin/head.php';
?>

<div class="main-content">
    <?php include '../templates/layouts/admin/header.php'; ?>

<div class="container-fluid">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-12">
            <h1 class="h3 mb-0">Transaction History</h1>
        </div>
    </div>

    <?php if (!empty($dashboard_filter)): ?>
    <!-- Dashboard Filter Active -->
    <div class="alert alert-info alert-dismissible fade show" role="alert">
        <strong><i class="fas fa-filter"></i> Dashboard Filter Active:</strong>
        <?php
        $filter_labels = [
            'current_rent_onhold' => '⏳ Current Rent Onhold',
            'current_security' => '🔒 Current Security Held',
            'total_withdrawn' => '💳 Total Withdrawn',
            'current_rent' => '💵 Current Rent',
            'total_revenue' => '💰 Total Revenue'
        ];
        echo $filter_labels[$dashboard_filter] ?? 'Custom Filter';
        ?>
        <a href="transactions.php" class="btn btn-sm btn-outline-primary ms-3">Clear Filter</a>
    </div>
    <?php endif; ?>

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted">Total Transactions</h6>
                    <h3><?php echo number_format($stats['total_transactions']); ?></h3>
                    <small class="text-muted">
                        <span class="text-success"><?php echo number_format($stats['credit_count']); ?> credits</span> | 
                        <span class="text-danger"><?php echo number_format($stats['debit_count']); ?> debits</span>
                    </small>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted">Total Credits</h6>
                    <h3 class="text-success"><?php echo WalletHelper::formatMoney($stats['total_credits']); ?></h3>
                    <small class="text-muted">Money added to wallets</small>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted">Total Debits</h6>
                    <h3 class="text-danger"><?php echo WalletHelper::formatMoney($stats['total_debits']); ?></h3>
                    <small class="text-muted">Money removed from wallets</small>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card bg-primary text-white">
                <div class="card-body">
                    <h6 class="mb-2">Platform Revenue</h6>
                    <h3><?php echo WalletHelper::formatMoney($payment_stats['total_amount']); ?></h3>
                    <small>All online payments</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Additional Stats Row -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted">Vendor Earnings</h6>
                    <h3><?php echo number_format($stats['earnings_count']); ?></h3>
                    <small class="text-muted">Completed transactions</small>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted">Withdrawals</h6>
                    <h3><?php echo number_format($stats['withdrawals_count']); ?></h3>
                    <small class="text-muted">Processed requests</small>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted">Refunds</h6>
                    <h3><?php echo number_format($stats['refunds_count']); ?></h3>
                    <small class="text-muted">Security deposit refunds</small>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted">Online Payments</h6>
                    <h3><?php echo number_format($payment_stats['total_payments']); ?></h3>
                    <small class="text-muted">
                        <span class="text-success"><?php echo number_format($payment_stats['successful_payments']); ?> success</span>
                    </small>
                </div>
            </div>
        </div>
    </div>

    <!-- Transaction List -->
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0">All Transactions</h5>
        </div>
        <div class="card-body">
            <!-- Filters -->
            <form method="GET" class="mb-4">
                <div class="row">
                    <div class="col-md-2">
                        <select name="type" class="form-control form-control-sm">
                            <option value="all">All Types</option>
                            <option value="vendor_earning" <?php echo $transaction_type === 'vendor_earning' ? 'selected' : ''; ?>>Vendor Earning</option>
                            <option value="security_refund" <?php echo $transaction_type === 'security_refund' ? 'selected' : ''; ?>>Security Refund</option>
                            <option value="commission" <?php echo $transaction_type === 'commission' ? 'selected' : ''; ?>>Commission</option>
                            <option value="withdrawal" <?php echo $transaction_type === 'withdrawal' ? 'selected' : ''; ?>>Withdrawal</option>
                            <option value="top_up" <?php echo $transaction_type === 'top_up' ? 'selected' : ''; ?>>Top Up</option>
                        </select>
                    </div>

                    <div class="col-md-2">
                        <select name="category" class="form-control form-control-sm">
                            <option value="all">All Categories</option>
                            <option value="credit" <?php echo $category === 'credit' ? 'selected' : ''; ?>>Credit</option>
                            <option value="debit" <?php echo $category === 'debit' ? 'selected' : ''; ?>>Debit</option>
                        </select>
                    </div>

                    <div class="col-md-2">
                        <select name="user_type" class="form-control form-control-sm">
                            <option value="all">All Users</option>
                            <option value="customer" <?php echo $user_type === 'customer' ? 'selected' : ''; ?>>Customers</option>
                            <option value="vendor" <?php echo $user_type === 'vendor' ? 'selected' : ''; ?>>Vendors</option>
                            <option value="admin" <?php echo $user_type === 'admin' ? 'selected' : ''; ?>>Admin</option>
                        </select>
                    </div>

                    <div class="col-md-2">
                        <input type="date" name="date_from" class="form-control form-control-sm" 
                               value="<?php echo htmlspecialchars($date_from); ?>">
                    </div>

                    <div class="col-md-2">
                        <input type="date" name="date_to" class="form-control form-control-sm" 
                               value="<?php echo htmlspecialchars($date_to); ?>">
                    </div>

                    <div class="col-md-2">
                        <button type="submit" class="btn btn-sm btn-primary btn-block">Filter</button>
                    </div>
                </div>

                <?php if ($transaction_type !== 'all' || $category !== 'all' || $user_type !== 'all' || $date_from || $date_to): ?>
                    <div class="row mt-2">
                        <div class="col-12">
                            <a href="transactions.php" class="btn btn-sm btn-outline-secondary">Clear Filters</a>
                        </div>
                    </div>
                <?php endif; ?>
            </form>

            <!-- Transactions Table -->
            <?php if (empty($transactions)): ?>
                <p class="text-muted text-center">No transactions found</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm table-hover">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Date & Time</th>
                                <th>User</th>
                                <th>Type</th>
                                <th>Description</th>
                                <th>Order</th>
                                <th>Amount</th>
                                <th>Balance After</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($transactions as $txn): ?>
                                <tr>
                                    <td><?php echo $txn['id']; ?></td>
                                    <td>
                                        <small>
                                            <?php echo date('M d, Y', strtotime($txn['created_at'] ?? 'now')); ?><br>
                                            <?php echo date('h:i A', strtotime($txn['created_at'] ?? 'now')); ?>
                                        </small>
                                    </td>
                                    <td>
                                        <strong><?php echo htmlspecialchars($txn['user_name'] ?? 'N/A'); ?></strong><br>
                                        <small class="text-muted"><?php echo ucfirst($txn['user_type'] ?? 'N/A'); ?></small>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php echo ($txn['category'] ?? 'credit') === 'credit' ? 'success' : 'warning'; ?>">
                                            <?php echo WalletHelper::getTransactionTypeLabel($txn['transaction_type'] ?? ''); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <small><?php echo htmlspecialchars(substr($txn['description'] ?? '', 0, 50)); ?></small>
                                    </td>
                                    <td>
                                        <?php if (!empty($txn['order_number'])): ?>
                                            <a href="../orders/view.php?order_number=<?php echo htmlspecialchars($txn['order_number']); ?>" target="_blank">
                                                <?php echo htmlspecialchars($txn['order_number']); ?>
                                            </a>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <strong class="<?php echo ($txn['category'] ?? 'credit') === 'credit' ? 'text-success' : 'text-danger'; ?>">
                                            <?php echo ($txn['category'] ?? 'credit') === 'credit' ? '+' : '-'; ?>
                                            <?php echo WalletHelper::formatMoney($txn['amount'] ?? 0); ?>
                                        </strong>
                                    </td>
                                    <td><?php echo WalletHelper::formatMoney($txn['balance_after'] ?? 0); ?></td>
                                    <td>
                                        <span class="badge bg-<?php echo WalletHelper::getStatusBadgeClass($txn['status'] ?? 'completed'); ?>">
                                            <?php echo ucfirst($txn['status'] ?? 'completed'); ?>
                                        </span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                    <?php
                    // Build pagination URL with all filters
                    $params = [];
                    if (!empty($dashboard_filter)) $params['filter'] = $dashboard_filter;
                    if ($transaction_type !== 'all') $params['type'] = $transaction_type;
                    if ($category !== 'all') $params['category'] = $category;
                    if ($user_type !== 'all') $params['user_type'] = $user_type;
                    if ($status !== 'all') $params['status'] = $status;
                    if (!empty($date_from)) $params['date_from'] = $date_from;
                    if (!empty($date_to)) $params['date_to'] = $date_to;
                    if (!empty($search)) $params['search'] = $search;
                    $base_url = 'transactions.php?' . http_build_query($params);
                    ?>
                    <nav>
                        <ul class="pagination justify-content-center">
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="<?= $base_url ?>&page=<?= $page - 1 ?>">Previous</a>
                                </li>
                            <?php endif; ?>

                            <?php 
                            $start_page = max(1, $page - 2);
                            $end_page = min($total_pages, $page + 2);
                            
                            for ($i = $start_page; $i <= $end_page; $i++): 
                            ?>
                                <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="<?= $base_url ?>&page=<?= $i ?>"><?= $i ?></a>
                                </li>
                            <?php endfor; ?>

                            <?php if ($page < $total_pages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="<?= $base_url ?>&page=<?= $page + 1 ?>">Next</a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php include '../templates/layouts/admin/footer.php'; ?>
</div>