<?php
require_once '../config/database.php';

try {
    // Check if user is authenticated
    if (!isAuthenticated()) {
        header('HTTP/1.1 403 Forbidden');
        echo 'Unauthorized access';
        exit;
    }

    $id = $_GET['id'] ?? '';
    
    if (empty($id)) {
        header('HTTP/1.1 400 Bad Request');
        echo 'Transaction ID is required';
        exit;
    }

    $pdo = getDBConnection();

    // Get transaction details
    $stmt = $pdo->prepare("
        SELECT t.*, m.name as member_name, m.kso_id 
        FROM transactions t 
        LEFT JOIN members m ON t.member_id = m.id 
        WHERE t.id = ?
    ");
    $stmt->execute([$id]);
    $transaction = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$transaction) {
        header('HTTP/1.1 404 Not Found');
        echo 'Transaction not found';
        exit;
    }

    // Set headers for PDF download
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="receipt_' . $id . '.pdf"');

    // Simple PDF generation (basic implementation)
    // You can enhance this with proper PDF libraries like TCPDF or FPDF
    
    // For now, create a simple text-based receipt
    $receipt_content = "
RECEIPT
=======

Receipt ID: {$id}
Date: {$transaction['created_at']}
Type: " . ucfirst($transaction['type']) . "
Amount: ₹{$transaction['amount']}
Description: {$transaction['description']}
Category: {$transaction['category']}
";

    if ($transaction['member_name']) {
        $receipt_content .= "Member: {$transaction['member_name']} ({$transaction['kso_id']})";
    }

    $receipt_content .= "

Thank you for your transaction.
KSO Chandigarh
";

    // For a basic implementation, output as plain text
    // In production, use proper PDF generation
    header('Content-Type: text/plain');
    header('Content-Disposition: attachment; filename="receipt_' . $id . '.txt"');
    echo $receipt_content;

} catch (PDOException $e) {
    header('HTTP/1.1 500 Internal Server Error');
    echo 'Database error: ' . $e->getMessage();
} catch (Exception $e) {
    header('HTTP/1.1 500 Internal Server Error');
    echo 'Error: ' . $e->getMessage();
}
?>
