<?php
$pageTitle = 'Payment Receipt';
include 'includes/header.php';

// --- Authentication and Role Check (made generic) ---
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], ['team_manager', 'club_manager'])) {
    header('Location: login.php');
    exit();
}

// --- Instantiate Models and Fetch Data ---
$fineModel = new Fine();
$paymentModel = new Payment();
$teamModel = new Team();
$clubManagerModel = new ClubManager();

// Determine context and back link
$context = $_GET['context'] ?? 'team_manager';
$back_link = ($context === 'club_manager') ? 'my_club.php' : 'my_team.php';

// --- Resolve Payment and Fines ---
$payment = null;
$fine_ids_string = null;

if (isset($_GET['ref'])) {
    // Lookup by Transaction Reference (from history table)
    $ref = $_GET['ref'];
    $payment = $paymentModel->findByTransactionRef($ref, $_SESSION['user_id']);
    if ($payment) {
        $meta = json_decode($payment->metadata);
        $fine_ids_string = $meta->fine_ids ?? null;
    }
} elseif (isset($_GET['ids'])) {
    // Legacy/Direct lookup by IDs
    $fine_ids_string = $_GET['ids'];
    $payment = $paymentModel->findByMetadata('fine_ids', $fine_ids_string, $_SESSION['user_id']);
}

$paid_fines = [];
if ($fine_ids_string) {
    $fine_ids = explode(',', $fine_ids_string);
    $fine_ids = array_filter($fine_ids, 'is_numeric');
    if (!empty($fine_ids)) {
        $paid_fines = $fineModel->getFinesByIds($fine_ids);
    }
}

if (!$payment) {
    echo "<div class='page-content'><p class='no-data-msg'>Receipt not found.</p><a href='$back_link' class='btn'>Go Back</a></div>";
    include 'includes/footer.php';
    exit();
}

// Fetch header info based on context
$header_logo = '/smart_football/public/assets/images/logo.png';
$header_name = 'Smart Football';

if ($context === 'club_manager') {
    $club = $clubManagerModel->getClubByManagerId($_SESSION['user_id']);
    if ($club) {
        $header_logo = $club->logo;
        $header_name = $club->name;
    }
} else { // team_manager
    $team = $teamModel->getTeamByManagerId($_SESSION['user_id']);
    if ($team) {
        $header_logo = $team->club_logo;
        $header_name = $team->club_name;
    }
}

?>

<div class="page-content">
    <div class="receipt-container" id="receipt-content">
        <div class="receipt-header">
            <div class="receipt-status">
                <i class="fa-solid fa-check-circle"></i>
                <h1>Payment Successful</h1>
                <p>Thank you for your payment. Here is your receipt.</p>
            </div>
            <div class="receipt-company-info">
                <img src="<?php echo htmlspecialchars($header_logo); ?>" alt="Club Logo" class="receipt-logo">
                <h2><?php echo htmlspecialchars($header_name); ?></h2>
            </div>
        </div>

        <div class="receipt-details">
            <div class="detail-item">
                <span class="detail-label">Transaction ID</span>
                <span class="detail-value"><?php echo htmlspecialchars($payment->transaction_ref); ?></span>
            </div>
            <div class="detail-item">
                <span class="detail-label">Date Paid</span>
                <span class="detail-value"><?php echo date('d F Y, H:i', strtotime($payment->created_at)); ?></span>
            </div>
            <div class="detail-item">
                <span class="detail-label">Payment Method</span>
                <span class="detail-value"><?php echo htmlspecialchars(ucfirst($payment->payment_gateway)); ?></span>
            </div>
            <div class="detail-item total-amount">
                <span class="detail-label">Total Amount Paid</span>
                <span class="detail-value">$<?php echo number_format($payment->amount, 2); ?></span>
            </div>
        </div>

        <?php if (!empty($paid_fines)): ?>
        <div class="receipt-items">
            <h3>Paid Items</h3>
            <div class="table-wrapper">
                <table class="styled-table">
                    <thead>
                        <tr>
                            <th>Player</th>
                            <th>Reason</th>
                            <th>Date Issued</th>
                            <th>Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($paid_fines as $fine): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($fine->first_name . ' ' . $fine->last_name); ?></td>
                                <td><?php echo htmlspecialchars($fine->reason); ?></td>
                                <td><?php echo date('d M Y', strtotime($fine->issue_date)); ?></td>
                                <td>$<?php echo number_format($fine->amount, 2); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <div class="receipt-actions">
        <a href="<?php echo $back_link; ?>" class="btn btn-secondary"><i class="fa-solid fa-arrow-left"></i> Back to Dashboard</a>
        <button onclick="window.print()" class="btn"><i class="fa-solid fa-print"></i> Print / Save as PDF</button>
    </div>
</div>

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