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

// Get payment statistics
$total_payments = $conn->query("SELECT COUNT(*) as cnt FROM payments WHERE status = 'successful'")->fetch_assoc()['cnt'] ?? 0;
$total_amount = $conn->query("SELECT SUM(amount) as total FROM payments WHERE status = 'successful'")->fetch_assoc()['total'] ?? 0;
$pending_withdrawals = $conn->query("SELECT SUM(amount) as total FROM withdrawal_requests WHERE status = 'pending'")->fetch_assoc()['total'] ?? 0;
$hps_revenue = $conn->query("SELECT SUM(amount) as total FROM payments WHERE payment_type IN ('hps_single', 'hps_family', 'hps_associates') AND status = 'successful'")->fetch_assoc()['total'] ?? 0;
$invest_revenue = $conn->query("SELECT SUM(amount) as total FROM payments WHERE payment_type = 'hps_invest' AND status = 'successful'")->fetch_assoc()['total'] ?? 0;

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

// Get pending withdrawal requests
$withdrawals = $conn->query("
    SELECT w.*, 
           (SELECT CONCAT(first_name, ' ', last_name) FROM patients WHERE patient_id = w.user_id) as user_name
    FROM withdrawal_requests w
    WHERE w.status = 'pending'
    ORDER BY w.requested_at ASC
");

$page_title = 'HPS 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>HPS 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; border-bottom: 3px solid #d4a017; }
        .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-successful { background: #28a745; color: white; }
        .status-pending { background: #ffc107; color: #856404; }
        .status-failed { background: #dc3545; color: white; }
        .nav-tabs .nav-link { color: #0a3d2f; font-weight: 500; }
        .nav-tabs .nav-link.active { color: #d4a017; border-bottom-color: #d4a017; }
    </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> HPS Payment Management</h2>
            <p class="text-muted">Manage HPS payments, withdrawals, and financial transactions</p>
        </div>
        <a href="dashboard.php" class="btn btn-outline-secondary rounded-pill">
            <i class="fas fa-arrow-left me-2"></i> Back to HPS Admin
        </a>
    </div>

    <!-- Statistics 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-shield-alt fa-2x mb-2 text-success"></i>
                <div class="stat-number">₦<?= number_format($hps_revenue, 2) ?></div>
                <p>HPS Insurance</p>
            </div>
        </div>
        <div class="col-md-3 col-6">
            <div class="stat-card">
                <i class="fas fa-chart-line fa-2x mb-2 text-info"></i>
                <div class="stat-number">₦<?= number_format($invest_revenue, 2) ?></div>
                <p>HPS Invest</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">₦<?= number_format($pending_withdrawals, 2) ?></div>
                <p>Pending Withdrawals</p>
            </div>
        </div>
    </div>

    <!-- Tabs -->
    <ul class="nav nav-tabs mb-4" id="paymentTabs" role="tablist">
        <li class="nav-item">
            <button class="nav-link active" id="transactions-tab" data-bs-toggle="tab" data-bs-target="#transactions" type="button">
                <i class="fas fa-list me-1"></i> Transactions
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" id="withdrawals-tab" data-bs-toggle="tab" data-bs-target="#withdrawals" type="button">
                <i class="fas fa-hand-holding-usd me-1"></i> Withdrawal Requests
                <?php if($withdrawals && $withdrawals->num_rows > 0): ?>
                    <span class="badge bg-danger ms-1"><?= $withdrawals->num_rows ?></span>
                <?php endif; ?>
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" id="summary-tab" data-bs-toggle="tab" data-bs-target="#summary" type="button">
                <i class="fas fa-chart-pie me-1"></i> Financial Summary
            </button>
        </li>
    </ul>

    <!-- Tab Content -->
    <div class="tab-content">
        <!-- Transactions Tab -->
        <div class="tab-pane fade show active" id="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_payments && $recent_payments->num_rows > 0): ?>
                                    <?php while($p = $recent_payments->fetch_assoc()): ?>
                                        <tr>
                                            <td><?= $p['id'] ?></td>
                                            <td><?= htmlspecialchars($p['user_name'] ?? 'User ' . $p['user_id']) ?></td>
                                            <td class="fw-bold">₦<?= number_format($p['amount'], 2) ?></td>
                                            <td><?= str_replace('_', ' ', ucfirst($p['payment_type'])) ?></td>
                                            <td><small><?= substr($p['transaction_id'] ?? '', 0, 15) ?>...</small></td>
                                            <td>
                                                <span class="status-badge status-<?= $p['status'] ?>">
                                                    <?= ucfirst($p['status']) ?>
                                                </span>
                                            </td
                                            <td><?= date('M d, Y', strtotime($p['created_at'])) ?></td
                                            <td>
                                                <button class="btn btn-sm btn-info" onclick="viewDetails(<?= $p['id'] ?>)">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                             </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>

        <!-- Withdrawals Tab -->
        <div class="tab-pane fade" id="withdrawals">
            <div class="card shadow-sm border-0 rounded-4">
                <div class="card-header bg-white border-0 pt-3">
                    <h5><i class="fas fa-clock me-2"></i> Pending Withdrawal Requests</h5>
                </div>
                <div class="card-body">
                    <?php if($withdrawals && $withdrawals->num_rows > 0): ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead class="table-light">
                                    <tr><th>ID</th><th>User</th><th>Amount</th><th>Bank</th><th>Account</th><th>Date</th><th>Action</th></tr>
                                </thead>
                                <tbody>
                                    <?php while($w = $withdrawals->fetch_assoc()): ?>
                                        <tr>
                                            <td><?= $w['id'] ?></td
                                            <td><?= htmlspecialchars($w['user_name'] ?? 'User ' . $w['user_id']) ?></td
                                            <td class="fw-bold text-danger">₦<?= number_format($w['amount'], 2) ?></td
                                            <td><?= htmlspecialchars($w['bank_name'] ?? 'N/A') ?></td
                                            <td><?= htmlspecialchars($w['account_number'] ?? 'N/A') ?></td
                                            <td><?= date('M d, Y', strtotime($w['requested_at'])) ?></td
                                            <td>
                                                <button class="btn btn-sm btn-success" onclick="approveWithdrawal(<?= $w['id'] ?>, <?= $w['amount'] ?>)">
                                                    <i class="fas fa-check"></i> Approve
                                                </button>
                                                <button class="btn btn-sm btn-danger" onclick="rejectWithdrawal(<?= $w['id'] ?>)">
                                                    <i class="fas fa-times"></i> Reject
                                                </button>
                                             </td
                                         </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-info text-center py-4">No pending withdrawal requests</div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Summary Tab -->
        <div class="tab-pane fade" id="summary">
            <div class="row g-3">
                <div class="col-md-6">
                    <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-pie me-2"></i> Revenue by Payment Type</h5>
                        </div>
                        <div class="card-body">
                            <canvas id="revenueChart" height="250"></canvas>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <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"></i> Monthly Revenue</h5>
                        </div>
                        <div class="card-body">
                            <canvas id="monthlyChart" height="250"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
function viewDetails(id) {
    alert('Transaction details for ID: ' + id);
}

function approveWithdrawal(id, amount) {
    if(confirm(`Approve withdrawal of ₦${amount.toLocaleString()}?`)) {
        fetch('api/approve_withdrawal.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ id: id, action: 'approve' })
        }).then(response => response.json()).then(data => {
            if(data.success) alert('Withdrawal approved!');
            else alert('Error: ' + data.message);
            location.reload();
        });
    }
}

function rejectWithdrawal(id) {
    if(confirm('Reject this withdrawal request?')) {
        fetch('api/approve_withdrawal.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ id: id, action: 'reject' })
        }).then(() => location.reload());
    }
}

// Revenue Chart
<?php
$hps_total = $conn->query("SELECT SUM(amount) as total FROM payments WHERE payment_type IN ('hps_single', 'hps_family', 'hps_associates') AND status = 'successful'")->fetch_assoc()['total'] ?? 0;
$invest_total = $conn->query("SELECT SUM(amount) as total FROM payments WHERE payment_type = 'hps_invest' AND status = 'successful'")->fetch_assoc()['total'] ?? 0;
$wallet_total = $conn->query("SELECT SUM(amount) as total FROM payments WHERE payment_type = 'wallet_deposit' AND status = 'successful'")->fetch_assoc()['total'] ?? 0;
?>

new Chart(document.getElementById('revenueChart'), {
    type: 'doughnut',
    data: {
        labels: ['HPS Insurance', 'HPS Invest', 'Wallet Deposits'],
        datasets: [{
            data: [<?= $hps_total ?>, <?= $invest_total ?>, <?= $wallet_total ?>],
            backgroundColor: ['#d4a017', '#28a745', '#17a2b8']
        }]
    }
});

// Monthly Chart
<?php
$monthly_data = [];
for($i = 5; $i >= 0; $i--) {
    $month = date('M', strtotime("-$i months"));
    $amount = $conn->query("SELECT SUM(amount) as total FROM payments WHERE status = 'successful' AND MONTH(created_at) = MONTH(DATE_SUB(NOW(), INTERVAL $i MONTH))")->fetch_assoc()['total'] ?? 0;
    $monthly_data[] = $amount;
}
?>
new Chart(document.getElementById('monthlyChart'), {
    type: 'line',
    data: {
        labels: ['5 months ago', '4 months ago', '3 months ago', '2 months ago', 'Last month', 'This month'],
        datasets: [{
            label: 'Revenue (₦)',
            data: <?= json_encode($monthly_data) ?>,
            borderColor: '#d4a017',
            backgroundColor: 'rgba(212,160,23,0.1)',
            tension: 0.3,
            fill: true
        }]
    }
});
</script>

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