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

$id = intval($_GET['id']);
$transaction = $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,
           (SELECT email FROM patients WHERE patient_id = t.user_id) as user_email
    FROM transactions t
    WHERE t.id = '$id'
")->fetch_assoc();

if (!$transaction) {
    header("Location: index.php");
    exit();
}

$page_title = 'Transaction Details | Admin';
include '../../include/header.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Transaction Details</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">
    <div class="d-flex justify-content-between mb-4">
        <h2 class="text-white">Transaction Details</h2>
        <a href="index.php" class="btn btn-outline-light rounded-pill">← Back</a>
    </div>

    <div class="card shadow rounded-4 bg-white">
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <p><strong>Transaction ID:</strong> <?= $transaction['id'] ?></p>
                    <p><strong>Reference:</strong> <?= $transaction['tx_ref'] ?></p>
                    <p><strong>Amount:</strong> <span class="fw-bold text-success">₦<?= number_format($transaction['amount'], 2) ?></span></p>
                    <p><strong>Payment Type:</strong> <?= ucfirst(str_replace('_', ' ', $transaction['payment_type'] ?? 'N/A')) ?></p>
                </div>
                <div class="col-md-6">
                    <p><strong>User:</strong> <?= htmlspecialchars($transaction['user_name'] ?? 'Guest') ?></p>
                    <p><strong>Email:</strong> <?= htmlspecialchars($transaction['user_email'] ?? 'N/A') ?></p>
                    <p><strong>Status:</strong> 
                        <span class="badge bg-<?= $transaction['status'] == 'completed' ? 'success' : 'warning' ?>">
                            <?= ucfirst($transaction['status']) ?>
                        </span>
                    </p>
                    <p><strong>Date:</strong> <?= date('F j, Y h:i A', strtotime($transaction['created_at'])) ?></p>
                </div>
            </div>
            <?php if($transaction['payment_data']): ?>
                <hr>
                <h6>Payment Data</h6>
                <pre class="bg-light p-3 rounded"><?= print_r(json_decode($transaction['payment_data'], true), true) ?></pre>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php include '../../include/footer.php'; ?>