<?php
$pageTitle = 'Payment Gateway Logs';
include 'includes/header.php';

// --- Admin Check ---
if (!in_array($_SESSION['admin_user_role'] ?? '', ['admin', 'super_admin'])) {
    header('Location: dashboard.php');
    exit();
}

$db = new Database();
$settingModel = new Setting();

// Pagination
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT) ?: 1;
$limit = 20;
$offset = ($page - 1) * $limit;

// Fetch Payments
$db->query("SELECT COUNT(*) as count FROM payments");
$total_logs = $db->single()->count;
$total_pages = ceil($total_logs / $limit);

$db->query("
    SELECT p.*, u.username, u.email 
    FROM payments p 
    LEFT JOIN users u ON p.user_id = u.id 
    ORDER BY p.created_at DESC 
    LIMIT :limit OFFSET :offset
");
$db->bind(':limit', $limit);
$db->bind(':offset', $offset);
$logs = $db->resultSet();

// Get currency symbol
$settings = $settingModel->getAll();
$currency_symbol = ($settings['system_currency'] ?? 'USD') === 'ZMW' ? 'K' : '$';

include 'includes/sidebar.php';
?>

<div class="page-content">
    <div class="matches-header">
        <h1>Payment Gateway Logs</h1>
    </div>

    <div class="dashboard-section">
        <div class="table-wrapper">
            <table class="styled-table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>User</th>
                        <th>Ref</th>
                        <th>Amount</th>
                        <th>Gateway</th>
                        <th>Status</th>
                        <th>Raw Data</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($logs)): ?>
                        <tr><td colspan="7" style="text-align:center;">No payment logs found.</td></tr>
                    <?php else: ?>
                        <?php foreach ($logs as $log): ?>
                            <tr>
                                <td><?php echo date('d M Y, H:i', strtotime($log->created_at)); ?></td>
                                <td>
                                    <?php echo htmlspecialchars($log->username ?? 'Unknown'); ?>
                                    <br><small class="text-muted"><?php echo htmlspecialchars($log->email ?? ''); ?></small>
                                </td>
                                <td><?php echo htmlspecialchars($log->transaction_ref); ?></td>
                                <td><?php echo $currency_symbol . number_format($log->amount, 2); ?></td>
                                <td><?php echo ucfirst($log->payment_gateway); ?></td>
                                <td>
                                    <span class="badge badge-<?php echo $log->status === 'successful' ? 'success' : ($log->status === 'failed' ? 'danger' : 'warning'); ?>">
                                        <?php echo ucfirst($log->status); ?>
                                    </span>
                                </td>
                                <td>
                                    <button class="btn-sm btn-secondary" onclick='viewRawData(<?php echo json_encode($log->metadata); ?>)'>
                                        <i class="fa-solid fa-code"></i> View
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
            <div class="pagination-controls">
                <?php if ($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>" class="btn-sm">Previous</a>
                <?php endif; ?>
                <span class="page-info">Page <?php echo $page; ?> of <?php echo $total_pages; ?></span>
                <?php if ($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>" class="btn-sm">Next</a>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Raw Data Modal -->
<div id="rawDataModal" class="modal">
    <div class="modal-content" style="max-width: 600px;">
        <div class="modal-header">
            <h3>Raw Gateway Response</h3>
            <button class="modal-close-btn" onclick="closeRawDataModal()">&times;</button>
        </div>
        <div class="modal-body">
            <pre id="json-container" style="background: #f4f4f4; padding: 15px; border-radius: 5px; overflow-x: auto; font-size: 0.85rem; color: #333;"></pre>
        </div>
    </div>
</div>

<script>
    const rawDataModal = document.getElementById('rawDataModal');
    const jsonContainer = document.getElementById('json-container');

    function viewRawData(jsonString) {
        try {
            const obj = JSON.parse(jsonString);
            jsonContainer.textContent = JSON.stringify(obj, null, 4);
        } catch (e) {
            jsonContainer.textContent = jsonString || 'No data available';
        }
        rawDataModal.classList.add('show');
    }

    function closeRawDataModal() {
        rawDataModal.classList.remove('show');
    }

    window.onclick = function(event) {
        if (event.target == rawDataModal) {
            closeRawDataModal();
        }
    }
</script>

<style>
.badge-success { background-color: #d4edda; color: #155724; padding: 4px 8px; border-radius: 4px; font-size: 0.8rem; }
.badge-danger { background-color: #f8d7da; color: #721c24; padding: 4px 8px; border-radius: 4px; font-size: 0.8rem; }
.badge-warning { background-color: #fff3cd; color: #856404; padding: 4px 8px; border-radius: 4px; font-size: 0.8rem; }
.text-muted { color: #6c757d; font-size: 0.85rem; }
.pagination-controls { display: flex; justify-content: center; gap: 10px; margin-top: 20px; align-items: center; }
</style>

<?php include 'includes/footer.php'; ?>