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

// Payment statistics
$total_revenue = $conn->query("SELECT SUM(amount) as total FROM transactions WHERE status = 'completed'")->fetch_assoc()['total'] ?? 0;
$this_month = $conn->query("SELECT SUM(amount) as total FROM transactions WHERE status = 'completed' AND MONTH(created_at) = MONTH(NOW())")->fetch_assoc()['total'] ?? 0;
$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;
$pending_payments = $conn->query("SELECT COUNT(*) as cnt FROM transactions WHERE status = 'pending'")->fetch_assoc()['cnt'] ?? 0;

// Revenue by type
$hps_revenue = $conn->query("SELECT SUM(amount) as total FROM transactions WHERE payment_type LIKE 'hps%' AND status = 'completed'")->fetch_assoc()['total'] ?? 0;
$consultation_revenue = $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;

// 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 15
");

$page_title = 'Payment Dashboard | 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 Dashboard - 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: linear-gradient(135deg, #0a3d2f, #064e3b); font-family: 'Segoe UI', sans-serif; min-height: 100vh; }
        
        .stat-card { background: rgba(255,255,255,0.12); backdrop-filter: blur(8px); border-radius: 20px; padding: 20px; text-align: center; color: white; transition: 0.3s; cursor: pointer; border: 1px solid rgba(255,255,255,0.1); }
        .stat-card:hover { transform: translateY(-5px); background: rgba(212,160,23,0.3); border-color: #d4a017; }
        .stat-number { font-size: 1.6rem; font-weight: 800; margin: 10px 0; }
        
        .section-title { color: white; font-size: 1.3rem; font-weight: 700; margin: 30px 0 20px; padding-bottom: 10px; border-bottom: 2px solid #d4a017; display: inline-block; }
        
        .revenue-card { background: rgba(255,255,255,0.1); border-radius: 16px; padding: 15px; text-align: center; color: white; }
        
        .transaction-row:hover { background: rgba(255,255,255,0.05); cursor: pointer; }
        .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; }
        
        .btn-outline-light { border-color: rgba(255,255,255,0.3); }
        .btn-outline-light:hover { background: #d4a017; border-color: #d4a017; color: #0a3d2f; }
    </style>
</head>
<body>

<div class="container mt-4">
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="text-white"><i class="fas fa-credit-card me-2" style="color: #d4a017;"></i> Payment Dashboard</h2>
            <p class="text-white-50">Manage transactions, track revenue, and monitor payments</p>
        </div>
        <a href="../dashboard.php" class="btn btn-outline-light rounded-pill">
            <i class="fas fa-arrow-left me-2"></i> Back to Admin
        </a>
    </div>

    <!-- Stats Row 1 -->
    <div class="row g-3 mb-4">
        <div class="col-md-3 col-6">
            <div class="stat-card" onclick="location.href='transactions.php'">
                <i class="fas fa-chart-line fa-2x mb-2" style="color: #d4a017;"></i>
                <div class="stat-number">₦<?= number_format($total_revenue, 2) ?></div>
                <p>Total Revenue</p>
            </div>
        </div>
        <div class="col-md-3 col-6">
            <div class="stat-card" onclick="location.href='transactions.php?filter=month'">
                <i class="fas fa-calendar-alt fa-2x mb-2 text-info"></i>
                <div class="stat-number">₦<?= number_format($this_month, 2) ?></div>
                <p>This Month</p>
            </div>
        </div>
        <div class="col-md-3 col-6">
            <div class="stat-card" onclick="location.href='transactions.php?status=completed'">
                <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" onclick="location.href='transactions.php?status=pending'">
                <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>

    <!-- Revenue Breakdown -->
    <h5 class="section-title"><i class="fas fa-chart-pie me-2"></i> Revenue Breakdown</h5>
    <div class="row g-3 mb-4">
        <div class="col-md-4">
            <div class="revenue-card">
                <i class="fas fa-shield-alt fa-2x mb-2" style="color: #d4a017;"></i>
                <h3 class="mb-0">₦<?= number_format($hps_revenue, 2) ?></h3>
                <small>HPS Insurance</small>
            </div>
        </div>
        <div class="col-md-4">
            <div class="revenue-card">
                <i class="fas fa-chart-line fa-2x mb-2" style="color: #28a745;"></i>
                <h3 class="mb-0">₦<?= number_format($conn->query("SELECT SUM(amount_invested) as total FROM hps_user_investments")->fetch_assoc()['total'] ?? 0, 2) ?></h3>
                <small>HPS Invest</small>
            </div>
        </div>
        <div class="col-md-4">
            <div class="revenue-card">
                <i class="fas fa-wallet fa-2x mb-2" style="color: #17a2b8;"></i>
                <h3 class="mb-0">₦<?= number_format($wallet_deposits, 2) ?></h3>
                <small>Wallet Deposits</small>
            </div>
        </div>
    </div>

    <!-- Navigation Cards -->
    <h5 class="section-title"><i class="fas fa-bolt me-2"></i> Quick Actions</h5>
    <div class="row g-3 mb-4">
        <div class="col-md-3 col-6">
            <div class="stat-card" onclick="location.href='transactions.php'">
                <i class="fas fa-list-alt fa-2x mb-2"></i>
                <h6 class="mb-0">All Transactions</h6>
                <small>View all payments</small>
            </div>
        </div>
        <div class="col-md-3 col-6">
            <div class="stat-card" onclick="location.href='../payment_settings.php'">
                <i class="fas fa-tags fa-2x mb-2"></i>
                <h6 class="mb-0">Price Settings</h6>
                <small>Set product prices</small>
            </div>
        </div>
        <div class="col-md-3 col-6">
            <div class="stat-card" onclick="location.href='../hps/withdrawals.php'">
                <i class="fas fa-hand-holding-usd fa-2x mb-2"></i>
                <h6 class="mb-0">Withdrawals</h6>
                <small>Manage payouts</small>
            </div>
        </div>
        <div class="col-md-3 col-6">
            <div class="stat-card" onclick="location.href='../payment_settings.php'">
                <i class="fas fa-chart-pie fa-2x mb-2"></i>
                <h6 class="mb-0">Reports</h6>
                <small>Financial reports</small>
            </div>
        </div>
    </div>

    <!-- Recent Transactions -->
    <div class="card shadow-sm border-0 rounded-4 bg-white">
        <div class="card-header bg-white border-0 pt-3">
            <h5><i class="fas fa-history me-2" style="color: #d4a017;"></i> Recent Transactions</h5>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr><th>ID</th><th>User</th><th>Amount</th><th>Type</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="location.href='view_transaction.php?id=<?= $tx['id'] ?>'">
                                    <td><?= $tx['id'] ?></td>
                                    <td><?= htmlspecialchars($tx['user_name'] ?? 'User ' . $tx['user_id']) ?></td>
                                    <td class="fw-bold text-success">₦<?= number_format($tx['amount'], 2) ?></td>
                                    <td><?= str_replace('_', ' ', ucfirst($tx['payment_type'] ?? 'N/A')) ?></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(); location.href='view_transaction.php?id=<?= $tx['id'] ?>'">
                                            <i class="fas fa-eye"></i> View
                                        </button>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr><td colspan="7" class="text-center text-muted py-4">No transactions found</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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