<?php
session_start();
require_once '../config/config.php';
require_once '../config/email_helper.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;
$send_email = $_GET['send_email'] ?? false;

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 PDF and save to temporary file
    $pdf = new ReceiptPDFGenerator();
    $pdf->generateReceipt($pdfData);
    
    // Create temp file for email attachment
    $tempFile = tempnam(sys_get_temp_dir(), 'receipt_');
    file_put_contents($tempFile, $pdf->Output('', 'S'));
    
    // Send email with PDF attachment
    if ($send_email && !empty($receipt['email'])) {
        $emailResult = sendReceiptEmailHelper($receipt, $tempFile);
        
        if ($emailResult['success']) {
            // Log the email send event
            $logStmt = $conn->prepare("
                INSERT INTO email_logs (recipient, subject, status, created_at)
                VALUES (?, ?, 'sent', NOW())
            ");
            $logStmt->execute([
                $receipt['email'],
                'Receipt #' . $receipt['receipt_number']
            ]);
            
            echo json_encode(['success' => true, 'message' => 'Receipt PDF emailed successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to send email: ' . $emailResult['message']]);
        }
    } else {
        // Just output the PDF file
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="receipt_' . $receipt['receipt_number'] . '.pdf"');
        readfile($tempFile);
    }
    
    // Clean up temp file
    unlink($tempFile);
    
} 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()]);
}
?>
