<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../includes/functions.php';

requireLogin();

// Check if user is admin
$currentUser = getCurrentUser();
if ($currentUser['role'] !== 'admin') {
    header('Location: dashboard.php');
    exit;
}

$db = getDB();

// Get filter parameters
$status = $_GET['status'] ?? '';
$gateway = $_GET['gateway'] ?? '';
$user = $_GET['user'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;

// Build query
$query = "
    SELECT pt.*, u.username, u.email, up.first_name, up.last_name,
           c.title as course_title, e.title as exam_title
    FROM payment_transactions pt
    JOIN users u ON pt.user_id = u.id
    LEFT JOIN user_profiles up ON u.id = up.user_id
    LEFT JOIN courses c ON pt.item_type = 'course' AND pt.item_id = c.id
    LEFT JOIN exams e ON pt.item_type = 'exam' AND pt.item_id = e.id
    WHERE 1=1
";

$params = [];

if (!empty($status)) {
    $query .= " AND pt.status = ?";
    $params[] = $status;
}

if (!empty($gateway)) {
    $query .= " AND pt.gateway_name = ?";
    $params[] = $gateway;
}

if (!empty($user)) {
    $query .= " AND (u.username LIKE ? OR u.email LIKE ? OR CONCAT(up.first_name, ' ', up.last_name) LIKE ?)";
    $searchTerm = "%$user%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

if (!empty($date_from)) {
    $query .= " AND DATE(pt.created_at) >= ?";
    $params[] = $date_from;
}

if (!empty($date_to)) {
    $query .= " AND DATE(pt.created_at) <= ?";
    $params[] = $date_to;
}

$query .= " ORDER BY pt.created_at DESC";

// Get total count for pagination
$countQuery = str_replace("SELECT pt.*, u.username, u.email, up.first_name, up.last_name,
           c.title as course_title, e.title as exam_title", "SELECT COUNT(*) as total", $query);

$stmt = $db->prepare($countQuery);
$stmt->execute($params);
$totalTransactions = $stmt->fetch()['total'];
$totalPages = ceil($totalTransactions / $perPage);

// Add pagination
$offset = ($page - 1) * $perPage;
$query .= " LIMIT ? OFFSET ?";

// Execute main query
$stmt = $db->prepare($query);

// Bind existing parameters
foreach ($params as $index => $param) {
    $stmt->bindValue($index + 1, $param);
}

// Bind LIMIT and OFFSET as integers
$stmt->bindValue(count($params) + 1, $perPage, PDO::PARAM_INT);
$stmt->bindValue(count($params) + 2, $offset, PDO::PARAM_INT);

$stmt->execute();
$transactions = $stmt->fetchAll();

// Get summary statistics
$stats = $db->query("
    SELECT
        COUNT(*) as total_transactions,
        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as successful_transactions,
        SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed_transactions,
        SUM(CASE WHEN status = 'completed' THEN final_amount ELSE 0 END) as total_revenue,
        AVG(CASE WHEN status = 'completed' THEN final_amount ELSE NULL END) as avg_transaction
    FROM payment_transactions
    WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
")->fetch();

// Get gateway breakdown
$gatewayStats = $db->query("
    SELECT gateway_name, status, COUNT(*) as count, SUM(final_amount) as amount
    FROM payment_transactions
    WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    GROUP BY gateway_name, status
    ORDER BY gateway_name, status
")->fetchAll();

$page_title = 'Payment History & Transactions';
include 'includes/admin_header.php';
?>

<div class="payment-history-section">
    <h2>Payment History & Transactions</h2>
    <p class="settings-description">View and manage all payment transactions, track revenue, and monitor payment gateway performance.</p>

    <!-- Statistics Cards -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-credit-card"></i>
            </div>
            <div class="stat-info">
                <h3><?php echo number_format($stats['total_transactions']); ?></h3>
                <p>Total Transactions (30d)</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon success">
                <i class="fas fa-check-circle"></i>
            </div>
            <div class="stat-info">
                <h3><?php echo number_format($stats['successful_transactions']); ?></h3>
                <p>Successful Payments</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon error">
                <i class="fas fa-times-circle"></i>
            </div>
            <div class="stat-info">
                <h3><?php echo number_format($stats['failed_transactions']); ?></h3>
                <p>Failed Payments</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon revenue">
                <i class="fas fa-dollar-sign"></i>
            </div>
            <div class="stat-info">
                <h3>$<?php echo number_format($stats['total_revenue'], 2); ?></h3>
                <p>Total Revenue (30d)</p>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="settings-card">
        <h3>Filter Transactions</h3>
        <form method="GET" class="filters-form">
            <div class="row">
                <div class="col-md-2">
                    <label class="form-label">Status</label>
                    <select name="status" class="form-select">
                        <option value="">All Status</option>
                        <option value="pending" <?php echo $status === 'pending' ? 'selected' : ''; ?>>Pending</option>
                        <option value="processing" <?php echo $status === 'processing' ? 'selected' : ''; ?>>Processing</option>
                        <option value="completed" <?php echo $status === 'completed' ? 'selected' : ''; ?>>Completed</option>
                        <option value="failed" <?php echo $status === 'failed' ? 'selected' : ''; ?>>Failed</option>
                        <option value="cancelled" <?php echo $status === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                        <option value="refunded" <?php echo $status === 'refunded' ? 'selected' : ''; ?>>Refunded</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Gateway</label>
                    <select name="gateway" class="form-select">
                        <option value="">All Gateways</option>
                        <option value="paypal" <?php echo $gateway === 'paypal' ? 'selected' : ''; ?>>PayPal</option>
                        <option value="paynow" <?php echo $gateway === 'paynow' ? 'selected' : ''; ?>>Paynow</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">User Search</label>
                    <input type="text" name="user" class="form-control" placeholder="Username, email, or name" value="<?php echo htmlspecialchars($user); ?>">
                </div>
                <div class="col-md-2">
                    <label class="form-label">From Date</label>
                    <input type="date" name="date_from" class="form-control" value="<?php echo $date_from; ?>">
                </div>
                <div class="col-md-2">
                    <label class="form-label">To Date</label>
                    <input type="date" name="date_to" class="form-control" value="<?php echo $date_to; ?>">
                </div>
                <div class="col-md-1">
                    <label class="form-label">&nbsp;</label>
                    <button type="submit" class="btn btn-primary w-100">Filter</button>
                </div>
            </div>
        </form>
    </div>

    <!-- Transactions Table -->
    <div class="settings-card">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h3>Transaction History</h3>
            <span class="text-muted">Showing <?php echo count($transactions); ?> of <?php echo $totalTransactions; ?> transactions</span>
        </div>

        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Transaction ID</th>
                        <th>User</th>
                        <th>Item</th>
                        <th>Gateway</th>
                        <th>Amount</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($transactions)): ?>
                        <tr>
                            <td colspan="8" class="text-center py-4">
                                <i class="fas fa-search fa-3x text-muted mb-3"></i>
                                <p class="text-muted">No transactions found matching your criteria.</p>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($transactions as $transaction): ?>
                            <tr>
                                <td>
                                    <code><?php echo htmlspecialchars(substr($transaction['transaction_id'], 0, 12)); ?>...</code>
                                    <br>
                                    <small class="text-muted"><?php echo htmlspecialchars($transaction['reference_number']); ?></small>
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($transaction['first_name'] && $transaction['last_name'] ? $transaction['first_name'] . ' ' . $transaction['last_name'] : $transaction['username']); ?></strong>
                                    <br>
                                    <small class="text-muted"><?php echo htmlspecialchars($transaction['email']); ?></small>
                                </td>
                                <td>
                                    <?php if ($transaction['item_type'] === 'course'): ?>
                                        <i class="fas fa-graduation-cap text-primary me-1"></i>
                                        <?php echo htmlspecialchars(substr($transaction['course_title'], 0, 30)); ?>...
                                    <?php elseif ($transaction['item_type'] === 'exam'): ?>
                                        <i class="fas fa-file-alt text-warning me-1"></i>
                                        <?php echo htmlspecialchars(substr($transaction['exam_title'], 0, 30)); ?>...
                                    <?php else: ?>
                                        <i class="fas fa-question-circle text-muted me-1"></i>
                                        <?php echo htmlspecialchars($transaction['item_type']); ?>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge bg-secondary"><?php echo ucfirst(htmlspecialchars($transaction['gateway_name'])); ?></span>
                                    <br>
                                    <small class="text-muted"><?php echo ucfirst(htmlspecialchars($transaction['gateway_type'])); ?></small>
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($transaction['currency']); ?> <?php echo number_format($transaction['final_amount'], 2); ?></strong>
                                    <?php if ($transaction['discount_amount'] > 0): ?>
                                        <br>
                                        <small class="text-success">Discount: -<?php echo htmlspecialchars($transaction['currency']); ?> <?php echo number_format($transaction['discount_amount'], 2); ?></small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge status-<?php echo $transaction['status']; ?>">
                                        <?php echo ucfirst(str_replace('_', ' ', $transaction['status'])); ?>
                                    </span>
                                </td>
                                <td>
                                    <?php echo date('M j, Y H:i', strtotime($transaction['created_at'])); ?>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary" onclick="viewTransactionDetails(<?php echo htmlspecialchars(json_encode($transaction)); ?>)">
                                        <i class="fas fa-eye"></i> Details
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($totalPages > 1): ?>
            <nav aria-label="Transaction pagination" class="mt-4">
                <ul class="pagination justify-content-center">
                    <?php if ($page > 1): ?>
                        <li class="page-item">
                            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">Previous</a>
                        </li>
                    <?php endif; ?>

                    <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                        <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>

                    <?php if ($page < $totalPages): ?>
                        <li class="page-item">
                            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">Next</a>
                        </li>
                    <?php endif; ?>
                </ul>
            </nav>
        <?php endif; ?>
    </div>

    <!-- Gateway Performance -->
    <div class="settings-card">
        <h3>Gateway Performance (Last 30 Days)</h3>
        <div class="gateway-stats">
            <?php
            $gatewayData = [];
            foreach ($gatewayStats as $stat) {
                $gatewayData[$stat['gateway_name']][$stat['status']] = $stat;
            }

            foreach ($gatewayData as $gwName => $statuses):
            ?>
                <div class="gateway-stat-card">
                    <h4><?php echo ucfirst($gwName); ?></h4>
                    <div class="stat-metrics">
                        <?php
                        $total = array_sum(array_column($statuses, 'count'));
                        $successful = $statuses['completed']['count'] ?? 0;
                        $failed = ($statuses['failed']['count'] ?? 0) + ($statuses['cancelled']['count'] ?? 0);
                        $revenue = $statuses['completed']['amount'] ?? 0;
                        ?>
                        <div class="metric">
                            <span class="metric-value"><?php echo $total; ?></span>
                            <span class="metric-label">Total</span>
                        </div>
                        <div class="metric">
                            <span class="metric-value text-success"><?php echo $successful; ?></span>
                            <span class="metric-label">Success</span>
                        </div>
                        <div class="metric">
                            <span class="metric-value text-danger"><?php echo $failed; ?></span>
                            <span class="metric-label">Failed</span>
                        </div>
                        <div class="metric">
                            <span class="metric-value">$<?php echo number_format($revenue, 2); ?></span>
                            <span class="metric-label">Revenue</span>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- Transaction Details Modal -->
<div class="modal fade" id="transactionModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Transaction Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="transactionDetails">
                <!-- Transaction details will be loaded here -->
            </div>
        </div>
    </div>
</div>

<style>
.payment-history-section {
    max-width: 1400px;
}

.settings-description {
    color: #64748b;
    margin-bottom: 2rem;
    font-size: 0.875rem;
}

.settings-card {
    background: white;
    padding: 2rem;
    border-radius: 0.75rem;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 2rem;
}

.settings-card h3 {
    font-size: 1.25rem;
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 1.5rem;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 1rem;
    margin-bottom: 2rem;
}

.stat-card {
    background: white;
    padding: 1.5rem;
    border-radius: 0.75rem;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    gap: 1rem;
}

.stat-icon {
    width: 3rem;
    height: 3rem;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #e5e7eb;
    color: #6b7280;
    font-size: 1.25rem;
}

.stat-icon.success {
    background-color: #d1fae5;
    color: #10b981;
}

.stat-icon.error {
    background-color: #fee2e2;
    color: #dc2626;
}

.stat-icon.revenue {
    background-color: #fef3c7;
    color: #f59e0b;
}

.stat-info h3 {
    font-size: 1.875rem;
    font-weight: 700;
    color: #1f2937;
    margin: 0;
}

.stat-info p {
    color: #6b7280;
    font-size: 0.875rem;
    margin: 0.25rem 0 0 0;
}

.filters-form .form-label {
    font-weight: 600;
    color: #374151;
    margin-bottom: 0.5rem;
}

.filters-form .form-select,
.filters-form .form-control {
    padding: 0.5rem;
    border: 1px solid #d1d5db;
    border-radius: 0.375rem;
    font-size: 0.875rem;
}

.table {
    margin-bottom: 0;
}

.table th {
    background-color: #f8f9fa;
    font-weight: 600;
    color: #374151;
    border-top: none;
    padding: 1rem;
}

.table td {
    padding: 1rem;
    vertical-align: middle;
}

.badge {
    display: inline-block;
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
    font-weight: 600;
    border-radius: 0.25rem;
}

.status-pending {
    background-color: #fef3c7;
    color: #f59e0b;
}

.status-processing {
    background-color: #dbeafe;
    color: #2563eb;
}

.status-completed {
    background-color: #d1fae5;
    color: #10b981;
}

.status-failed {
    background-color: #fee2e2;
    color: #dc2626;
}

.status-cancelled {
    background-color: #f3f4f6;
    color: #6b7280;
}

.status-refunded {
    background-color: #fef3c7;
    color: #f59e0b;
}

.btn {
    padding: 0.375rem 0.75rem;
    font-size: 0.875rem;
    border-radius: 0.375rem;
    border: 1px solid transparent;
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
}

.btn-outline-primary {
    color: #2563eb;
    border-color: #2563eb;
    background-color: transparent;
}

.btn-outline-primary:hover {
    background-color: #2563eb;
    color: white;
}

.btn-sm {
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
}

.pagination {
    margin-bottom: 0;
}

.page-link {
    color: #2563eb;
    border-color: #d1d5db;
}

.page-link:hover {
    color: #1d4ed8;
    background-color: #f3f4f6;
}

.page-item.active .page-link {
    background-color: #2563eb;
    border-color: #2563eb;
}

.gateway-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 1rem;
}

.gateway-stat-card {
    background: #f8f9fa;
    padding: 1.5rem;
    border-radius: 0.5rem;
    border: 1px solid #e5e7eb;
}

.gateway-stat-card h4 {
    font-size: 1.125rem;
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 1rem;
}

.stat-metrics {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 1rem;
}

.metric {
    text-align: center;
}

.metric-value {
    display: block;
    font-size: 1.5rem;
    font-weight: 700;
    color: #1f2937;
}

.metric-label {
    display: block;
    font-size: 0.75rem;
    color: #6b7280;
    margin-top: 0.25rem;
}

@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }

    .filters-form .row {
        flex-direction: column;
    }

    .filters-form .col-md-2,
    .filters-form .col-md-3,
    .filters-form .col-md-1 {
        margin-bottom: 1rem;
    }

    .stat-metrics {
        grid-template-columns: repeat(2, 1fr);
    }
}
</style>

<script>
function viewTransactionDetails(transaction) {
    const details = `
        <div class="transaction-details">
            <div class="row mb-3">
                <div class="col-md-6">
                    <h6>Transaction Information</h6>
                    <table class="table table-sm">
                        <tr><td><strong>Transaction ID:</strong></td><td><code>${transaction.transaction_id}</code></td></tr>
                        <tr><td><strong>Reference:</strong></td><td>${transaction.reference_number}</td></tr>
                        <tr><td><strong>Status:</strong></td><td><span class="badge status-${transaction.status}">${transaction.status.charAt(0).toUpperCase() + transaction.status.slice(1)}</span></td></tr>
                        <tr><td><strong>Gateway:</strong></td><td>${transaction.gateway_name.charAt(0).toUpperCase() + transaction.gateway_name.slice(1)} (${transaction.gateway_type})</td></tr>
                        <tr><td><strong>Created:</strong></td><td>${new Date(transaction.created_at).toLocaleString()}</td></tr>
                        ${transaction.processed_at ? `<tr><td><strong>Processed:</strong></td><td>${new Date(transaction.processed_at).toLocaleString()}</td></tr>` : ''}
                    </table>
                </div>
                <div class="col-md-6">
                    <h6>Payment Details</h6>
                    <table class="table table-sm">
                        <tr><td><strong>Amount:</strong></td><td>${transaction.currency} ${parseFloat(transaction.amount).toFixed(2)}</td></tr>
                        ${transaction.discount_amount > 0 ? `<tr><td><strong>Discount:</strong></td><td>-${transaction.currency} ${parseFloat(transaction.discount_amount).toFixed(2)}</td></tr>` : ''}
                        ${transaction.tax_amount > 0 ? `<tr><td><strong>Tax:</strong></td><td>${transaction.currency} ${parseFloat(transaction.tax_amount).toFixed(2)}</td></tr>` : ''}
                        <tr><td><strong>Final Amount:</strong></td><td><strong>${transaction.currency} ${parseFloat(transaction.final_amount).toFixed(2)}</strong></td></tr>
                        ${transaction.discount_code ? `<tr><td><strong>Discount Code:</strong></td><td><code>${transaction.discount_code}</code></td></tr>` : ''}
                        <tr><td><strong>Payment Method:</strong></td><td>${transaction.payment_method || 'N/A'}</td></tr>
                    </table>
                </div>
            </div>

            <div class="row mb-3">
                <div class="col-md-6">
                    <h6>User Information</h6>
                    <table class="table table-sm">
                        <tr><td><strong>Name:</strong></td><td>${transaction.first_name && transaction.last_name ? transaction.first_name + ' ' + transaction.last_name : transaction.username}</td></tr>
                        <tr><td><strong>Email:</strong></td><td>${transaction.email}</td></tr>
                        <tr><td><strong>User ID:</strong></td><td>${transaction.user_id}</td></tr>
                    </table>
                </div>
                <div class="col-md-6">
                    <h6>Item Information</h6>
                    <table class="table table-sm">
                        <tr><td><strong>Type:</strong></td><td>${transaction.item_type.charAt(0).toUpperCase() + transaction.item_type.slice(1)}</td></tr>
                        <tr><td><strong>Item ID:</strong></td><td>${transaction.item_id}</td></tr>
                        ${transaction.course_title ? `<tr><td><strong>Title:</strong></td><td>${transaction.course_title}</td></tr>` : ''}
                        ${transaction.exam_title ? `<tr><td><strong>Title:</strong></td><td>${transaction.exam_title}</td></tr>` : ''}
                    </table>
                </div>
            </div>

            ${transaction.notes ? `
                <div class="mb-3">
                    <h6>Notes</h6>
                    <p class="text-muted">${transaction.notes}</p>
                </div>
            ` : ''}

            ${transaction.gateway_response ? `
                <div class="mb-3">
                    <h6>Gateway Response</h6>
                    <pre class="bg-light p-2 rounded"><code>${JSON.stringify(JSON.parse(transaction.gateway_response), null, 2)}</code></pre>
                </div>
            ` : ''}
        </div>
    `;

    document.getElementById('transactionDetails').innerHTML = details;
    const modal = new bootstrap.Modal(document.getElementById('transactionModal'));
    modal.show();
}
</script>

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