<?php
session_start();
if (!isset($_SESSION['admin_id']) && $_SESSION['role'] != 'admin') {
    header("Location: login.php");
    exit();
}
include '../include/config.php';

// Get payment statistics
$total_transactions = $conn->query("SELECT COUNT(*) as cnt FROM transactions")->fetch_assoc()['cnt'] ?? 0;
$successful_payments = $conn->query("SELECT COUNT(*) as cnt FROM transactions WHERE status = 'completed'")->fetch_assoc()['cnt'] ?? 0;
$total_amount = $conn->query("SELECT SUM(amount) as total FROM transactions WHERE status = 'completed'")->fetch_assoc()['total'] ?? 0;
$pending_payments = $conn->query("SELECT COUNT(*) as cnt FROM transactions WHERE status = 'pending'")->fetch_assoc()['cnt'] ?? 0;

// Get payment by type
$hps_payments = $conn->query("SELECT SUM(amount) as total FROM transactions WHERE payment_type LIKE 'hps%' AND status = 'completed'")->fetch_assoc()['total'] ?? 0;
$consultation_payments = $conn->query("SELECT SUM(amount) as total FROM transactions WHERE payment_type = 'consultation' AND status = 'completed'")->fetch_assoc()['total'] ?? 0;
$wallet_deposits = $conn->query("SELECT SUM(amount) as total FROM transactions WHERE payment_type = 'wallet_deposit' AND status = 'completed'")->fetch_assoc()['total'] ?? 0;

// Get recent transactions
$recent_transactions = $conn->query("
    SELECT t.*, 
           CASE 
               WHEN t.user_id IN (SELECT patient_id FROM patients) THEN (SELECT CONCAT(first_name, ' ', last_name) FROM patients WHERE patient_id = t.user_id)
               ELSE 'Guest'
           END as user_name
    FROM transactions t
    ORDER BY t.created_at DESC LIMIT 30
");

$page_title = 'Payment Management | Admin';
include '../include/header.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Management - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <style>
        body { background: #f0f2f5; font-family: 'Segoe UI', sans-serif; }
        .stat-card { background: white; border-radius: 20px; padding: 20px; text-align: center; transition: 0.3s; box-shadow: 0 2px 10px rgba(0,0,0,0.05); border-bottom: 3px solid #d4a017; }
        .stat-card:hover { transform: translateY(-5px); }
        .stat-number { font-size: 1.8rem; font-weight: 800; color: #0a3d2f; }
        .status-badge { padding: 4px 12px; border-radius: 20px; font-size: 0.7rem; font-weight: 600; }
        .status-completed { background: #28a745; color: white; }
        .status-pending { background: #ffc107; color: #856404; }
        .status-failed { background: #dc3545; color: white; }
        .transaction-row:hover { background: #f8f9fa; cursor: pointer; }
    </style>
</head>
<body>

<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2><i class="fas fa-credit-card me-2" style="color: #d4a017;"></i> Payment Management</h2>
            <p class="text-muted">Track all transactions, manage payments, and view financial reports</p>
        </div>
        <div>
            <a href="payment_settings.php" class="btn btn-primary rounded-pill">
                <i class="fas fa-cog me-2"></i> Payment Settings
            </a>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="row g-3 mb-4">
        <div class="col-md-3 col-6">
            <div class="stat-card">
                <i class="fas fa-chart-line fa-2x mb-2" style="color: #d4a017;"></i>
                <div class="stat-number">₦<?= number_format($total_amount, 2) ?></div>
                <p>Total Revenue</p>
            </div>
        </div>
        <div class="col-md-3 col-6">
            <div class="stat-card">
                <i class="fas fa-check-circle fa-2x mb-2 text-success"></i>
                <div class="stat-number"><?= $successful_payments ?></div>
                <p>Successful Payments</p>
            </div>
        </div>
        <div class="col-md-3 col-6">
            <div class="stat-card">
                <i class="fas fa-clock fa-2x mb-2 text-warning"></i>
                <div class="stat-number"><?= $pending_payments ?></div>
                <p>Pending Payments</p>
            </div>
        </div>
        <div class="col-md-3 col-6">
            <div class="stat-card">
                <i class="fas fa-exchange-alt fa-2x mb-2 text-info"></i>
                <div class="stat-number"><?= $total_transactions ?></div>
                <p>Total Transactions</p>
            </div>
        </div>
    </div>

    <!-- Revenue Breakdown -->
    <div class="row g-3 mb-4">
        <div class="col-md-4">
            <div class="card shadow-sm border-0 rounded-4">
                <div class="card-header bg-white border-0 pt-3">
                    <h5><i class="fas fa-shield-alt me-2" style="color: #d4a017;"></i> HPS Insurance</h5>
                </div>
                <div class="card-body text-center">
                    <h3 class="text-success">₦<?= number_format($hps_payments, 2) ?></h3>
                    <p class="text-muted">HPS Single, Family & Associates</p>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card shadow-sm border-0 rounded-4">
                <div class="card-header bg-white border-0 pt-3">
                    <h5><i class="fas fa-chart-line me-2" style="color: #d4a017;"></i> HPS Invest</h5>
                </div>
                <div class="card-body text-center">
                    <h3 class="text-success">₦<?= number_format($conn->query("SELECT SUM(amount_invested) as total FROM hps_user_investments")->fetch_assoc()['total'] ?? 0, 2) ?></h3>
                    <p class="text-muted">Equipment Investments</p>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card shadow-sm border-0 rounded-4">
                <div class="card-header bg-white border-0 pt-3">
                    <h5><i class="fas fa-wallet me-2" style="color: #d4a017;"></i> Wallet Deposits</h5>
                </div>
                <div class="card-body text-center">
                    <h3 class="text-success">₦<?= number_format($wallet_deposits, 2) ?></h3>
                    <p class="text-muted">User Wallet Top-ups</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Recent Transactions -->
    <div class="card shadow-sm border-0 rounded-4">
        <div class="card-header bg-white border-0 pt-3">
            <h5><i class="fas fa-history me-2"></i> Recent Transactions</h5>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr><th>ID</th><th>User</th><th>Amount</th><th>Payment Type</th><th>Reference</th><th>Status</th><th>Date</th><th>Action</th></tr>
                    </thead>
                    <tbody>
                        <?php if($recent_transactions && $recent_transactions->num_rows > 0): ?>
                            <?php while($tx = $recent_transactions->fetch_assoc()): ?>
                                <tr class="transaction-row" onclick="viewTransaction(<?= $tx['id'] ?>)">
                                    <td><?= $tx['id'] ?></td>
                                    <td><?= htmlspecialchars($tx['user_name'] ?? 'User ' . $tx['user_id']) ?></td
                                    <td class="fw-bold">₦<?= number_format($tx['amount'], 2) ?></td
                                    <td><?= str_replace('_', ' ', ucfirst($tx['payment_type'] ?? 'N/A')) ?></td
                                    <td><small><?= substr($tx['tx_ref'] ?? '', 0, 15) ?>...</small></td
                                    <td>
                                        <span class="status-badge status-<?= $tx['status'] ?>">
                                            <?= ucfirst($tx['status']) ?>
                                        </span>
                                     </td
                                    <td><?= date('M d, Y', strtotime($tx['created_at'])) ?></td
                                    <td>
                                        <button class="btn btn-sm btn-info" onclick="event.stopPropagation(); viewTransactionDetails(<?= $tx['id'] ?>)">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                        <?php if($tx['status'] == 'pending'): ?>
                                            <button class="btn btn-sm btn-success" onclick="event.stopPropagation(); verifyPayment('<?= $tx['tx_ref'] ?>')">
                                                <i class="fas fa-check"></i>
                                            </button>
                                        <?php endif; ?>
                                     </td
                                  </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr><td colspan="8" class="text-center text-muted py-4">No transactions found</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
function viewTransaction(id) {
    window.location.href = 'view_transaction.php?id=' + id;
}

function viewTransactionDetails(id) {
    window.location.href = 'view_transaction.php?id=' + id;
}

function verifyPayment(txRef) {
    if(confirm('Verify this payment with Flutterwave?')) {
        fetch(`../payment/verify.php?ref=${txRef}`)
            .then(response => response.json())
            .then(data => {
                if(data.success) {
                    alert('Payment verified successfully!');
                    location.reload();
                } else {
                    alert('Verification failed: ' + data.message);
                }
            });
    }
}
</script>

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