<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (!isset($_SESSION['admin_id'])) { header("Location: login.php"); exit(); }
include '../include/config.php';

// Create table if not exists (safe way)
$conn->query("CREATE TABLE IF NOT EXISTS patient_payments (
    id INT AUTO_INCREMENT PRIMARY KEY,
    patient_id VARCHAR(50) NOT NULL,
    amount DECIMAL(10,2) DEFAULT 5000,
    reference VARCHAR(100),
    status ENUM('pending','completed','failed') DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

$payments = $conn->query("
    SELECT pp.*, p.first_name, p.last_name, p.email 
    FROM patient_payments pp 
    JOIN patients p ON pp.patient_id = p.patient_id 
    ORDER BY pp.created_at DESC
");
?>
<!DOCTYPE html>
<html>
<head><title>Patient Payments</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"></head>
<body>
<div class="container mt-4">
    <h2>Portal Activation Payments</h2>
    <?php if($payments && $payments->num_rows > 0): ?>
    <table class="table table-bordered">
        <thead><tr><th>Patient</th><th>Email</th><th>Amount</th><th>Reference</th><th>Status</th><th>Date</th></tr></thead>
        <tbody>
        <?php while($p = $payments->fetch_assoc()): ?>
        <tr>
            <td><?= htmlspecialchars($p['first_name'].' '.$p['last_name']) ?></td>
            <td><?= htmlspecialchars($p['email']) ?></td>
            <td>₦<?= number_format($p['amount'], 2) ?></td>
            <td><?= htmlspecialchars($p['reference']) ?></td>
            <td><span class="badge bg-<?= $p['status']=='completed'?'success':'warning' ?>"><?= $p['status'] ?></span></td>
            <td><?= $p['created_at'] ?></td>
        </tr>
        <?php endwhile; ?>
        </tbody>
    </table>
    <?php else: ?>
        <p>No payments found.</p>
    <?php endif; ?>
    <a href="dashboard.php" class="btn btn-secondary mt-3">Back to Dashboard</a>
</div>
</body>
</html>