<?php
session_start();
require_once '../config/config.php';
require_once 'PDFGenerator.php';

header('Content-Type: application/json');

if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$receipt_id = $_GET['id'] ?? null;

if (!$receipt_id) {
    echo json_encode(['success' => false, 'message' => 'Receipt ID is required']);
    exit();
}

try {
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Get receipt data with member information
    $stmt = $conn->prepare("
        SELECT 
            r.*,
            m.first_name,
            m.last_name,
            m.kso_id,
            m.email,
            m.phone,
            f.payment_method,
            f.payment_date,
            f.description as payment_description
        FROM receipts r
        LEFT JOIN members m ON r.member_id = m.id
        LEFT JOIN finance f ON r.transaction_id = f.id
        WHERE r.id = ?
    ");
    $stmt->execute([$receipt_id]);
    $receipt = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$receipt) {
        echo json_encode(['success' => false, 'message' => 'Receipt not found']);
        exit();
    }
    
    // Prepare data for PDF generation
    $pdfData = [
        'number' => $receipt['receipt_number'],
        'date' => $receipt['created_at'],
        'member_name' => $receipt['first_name'] . ' ' . $receipt['last_name'],
        'kso_id' => $receipt['kso_id'],
        'email' => $receipt['email'],
        'phone' => $receipt['phone'],
        'amount' => $receipt['amount'],
        'transaction_type' => $receipt['transaction_type'],
        'payment_method' => $receipt['payment_method'],
        'description' => $receipt['payment_description'] ?: 'Payment received',
        'status' => 'paid',
        'include_qr' => true,
        'digital_signature' => true
    ];
    
    // Generate and output PDF
    PDFFactory::outputToBrowser('receipt', $pdfData, 'receipt_' . $receipt['receipt_number'] . '.pdf');
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error generating PDF: ' . $e->getMessage()]);
}
?>
