<?php
require_once 'includes/middleware.php';
require_once 'config/database.php';
require_once 'config/currency.php';
require_once 'includes/functions.php';

$db = getDB();

// Check if user is logged in
if (!isLoggedIn()) {
    header('Location: login.php?redirect=receipt.php');
    exit;
}

$userId = $_SESSION['user_id'];

// Get receipt data from session or URL parameters
$receiptId = $_GET['id'] ?? null;
$transactionId = $_GET['transaction'] ?? null;

if (!$receiptId && !$transactionId) {
    header('Location: student/dashboard.php');
    exit;
}

$page_title = 'Payment Receipt';
include 'includes/header.php';

// Fetch real transaction data from database
$receiptData = null;

try {
    if ($transactionId) {
        // Get transaction by transaction_id or reference_number
        $stmt = $db->prepare("
            SELECT pt.*, c.title as course_title, c.thumbnail as course_thumbnail
            FROM payment_transactions pt
            LEFT JOIN courses c ON pt.item_type = 'course' AND pt.item_id = c.id
            WHERE pt.transaction_id = ? OR pt.reference_number = ?
        ");
        $stmt->execute([$transactionId, $transactionId]);
        $transaction = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($transaction) {
            $receiptData = [
                'receipt_id' => 'RCP-' . date('Ymd', strtotime($transaction['created_at'])) . '-' . substr($transaction['transaction_id'], -4),
                'transaction_id' => $transaction['transaction_id'],
                'reference_number' => $transaction['reference_number'],
                'date' => $transaction['created_at'],
                'status' => $transaction['status'],
                'payment_method' => ucfirst($transaction['gateway_name']),
                'currency' => $transaction['currency'],
                'items' => [
                    [
                        'title' => $transaction['course_title'] ?? 'Course Purchase',
                        'price' => $transaction['final_amount'],
                        'quantity' => 1,
                        'thumbnail' => $transaction['course_thumbnail']
                    ]
                ],
                'subtotal' => $transaction['amount'],
                'discount' => $transaction['discount_amount'],
                'total' => $transaction['final_amount'],
                'customer_email' => $_SESSION['user_email'] ?? 'student@example.com'
            ];
        }
    }
} catch (Exception $e) {
    // Log error and fall back to mock data
    error_log("Receipt error: " . $e->getMessage());
}

// Fallback mock data if transaction not found
if (!$receiptData) {
    $receiptData = [
        'receipt_id' => $receiptId ?: 'RCP-' . date('Ymd') . '-' . rand(1000, 9999),
        'transaction_id' => $transactionId ?: 'TXN-' . date('Ymd') . '-' . rand(1000, 9999),
        'date' => date('Y-m-d H:i:s'),
        'status' => 'completed',
        'payment_method' => 'PayPal',
        'currency' => 'USD',
        'items' => [
            [
                'title' => 'Course Purchase',
                'price' => 99.99,
                'quantity' => 1
            ]
        ],
        'subtotal' => 99.99,
        'discount' => 0.00,
        'total' => 99.99,
        'customer_email' => $_SESSION['user_email'] ?? 'student@example.com'
    ];
}
?>

<div class="container my-5">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="card shadow">
                <div class="card-header bg-success text-white text-center">
                    <h4 class="mb-0">
                        <i class="fas fa-check-circle me-2"></i>
                        Payment Successful!
                    </h4>
                </div>
                <div class="card-body">
                    <div class="text-center mb-4">
                        <i class="fas fa-receipt fa-4x text-success mb-3"></i>
                        <h5 class="text-success">Thank you for your purchase!</h5>
                        <p class="text-muted">Your payment has been processed successfully. A confirmation email has been sent to <?php echo htmlspecialchars($receiptData['customer_email']); ?>.</p>
                    </div>

                    <!-- Receipt Details -->
                    <div class="receipt-details">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <strong>Receipt ID:</strong><br>
                                <?php echo htmlspecialchars($receiptData['receipt_id']); ?>
                            </div>
                            <div class="col-md-6 text-md-end">
                                <strong>Transaction ID:</strong><br>
                                <?php echo htmlspecialchars($receiptData['transaction_id']); ?>
                            </div>
                        </div>

                        <?php if (isset($receiptData['reference_number'])): ?>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <strong>Reference Number:</strong><br>
                                <?php echo htmlspecialchars($receiptData['reference_number']); ?>
                            </div>
                            <div class="col-md-6 text-md-end">
                                <strong>Status:</strong><br>
                                <span class="badge bg-<?php echo $receiptData['status'] === 'completed' ? 'success' : 'warning'; ?>">
                                    <?php echo ucfirst(htmlspecialchars($receiptData['status'])); ?>
                                </span>
                            </div>
                        </div>
                        <?php endif; ?>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <strong>Date:</strong><br>
                                <?php echo date('F j, Y \a\t g:i A', strtotime($receiptData['date'])); ?>
                            </div>
                            <div class="col-md-6 text-md-end">
                                <strong>Payment Method:</strong><br>
                                <?php echo htmlspecialchars($receiptData['payment_method']); ?>
                            </div>
                        </div>

                        <hr>

                        <!-- Items -->
                        <h6 class="mb-3">Purchased Items</h6>
                        <div class="table-responsive">
                            <table class="table table-borderless">
                                <thead>
                                    <tr>
                                        <th>Course</th>
                                        <th class="text-end">Price</th>
                                        <th class="text-end">Qty</th>
                                        <th class="text-end">Total</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($receiptData['items'] as $item): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($item['title']); ?></td>
                                            <td class="text-end"><?php echo formatCurrency($item['price'], $receiptData['currency']); ?></td>
                                            <td class="text-end"><?php echo $item['quantity']; ?></td>
                                            <td class="text-end"><?php echo formatCurrency($item['price'] * $item['quantity'], $receiptData['currency']); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <hr>

                        <!-- Totals -->
                        <div class="row">
                            <div class="col-md-8 ms-auto">
                                <div class="d-flex justify-content-between mb-2">
                                    <span>Subtotal:</span>
                                    <span><?php echo formatCurrency($receiptData['subtotal'], $receiptData['currency']); ?></span>
                                </div>
                                <?php if (isset($receiptData['discount']) && $receiptData['discount'] > 0): ?>
                                <div class="d-flex justify-content-between mb-2 text-success">
                                    <span>Discount:</span>
                                    <span>-<?php echo formatCurrency($receiptData['discount'], $receiptData['currency']); ?></span>
                                </div>
                                <?php endif; ?>
                                <div class="d-flex justify-content-between fw-bold fs-5">
                                    <span>Total:</span>
                                    <span><?php echo formatCurrency($receiptData['total'], $receiptData['currency']); ?></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Actions -->
                    <div class="text-center mt-4">
                        <a href="student/dashboard.php" class="btn btn-primary me-2">
                            <i class="fas fa-graduation-cap me-2"></i>Start Learning
                        </a>
                        <button onclick="window.print()" class="btn btn-outline-secondary">
                            <i class="fas fa-print me-2"></i>Print Receipt
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.receipt-details {
    background: #f8f9fa;
    padding: 2rem;
    border-radius: 8px;
}

@media print {
    .btn, .card-header {
        display: none !important;
    }

    .container {
        max-width: none !important;
        margin: 0 !important;
        padding: 0 !important;
    }

    .card {
        box-shadow: none !important;
        border: 1px solid #ddd !important;
    }

    .card-body {
        padding: 1rem !important;
    }
}
</style>

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