<?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 = $_POST['receipt_id'] ?? null;
$invoice_id = $_POST['invoice_id'] ?? null;
$template_data = $_POST['template_data'] ?? [];

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

try {
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    if ($receipt_id) {
        // Get receipt data
        $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]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$data) {
            echo json_encode(['success' => false, 'message' => 'Receipt not found']);
            exit();
        }
        
        $type = 'receipt';
        $number = $data['receipt_number'];
        
    } else {
        // Get invoice data
        $stmt = $conn->prepare("
            SELECT 
                i.*,
                m.first_name,
                m.last_name,
                m.kso_id,
                m.email,
                m.phone,
                m.address
            FROM invoices i
            LEFT JOIN members m ON i.member_id = m.id
            WHERE i.id = ?
        ");
        $stmt->execute([$invoice_id]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$data) {
            echo json_encode(['success' => false, 'message' => 'Invoice not found']);
            exit();
        }
        
        $type = 'invoice';
        $number = $data['invoice_number'];
    }
    
    // Apply template customizations
    $customizations = [
        'company_name' => $template_data['company_name'] ?? 'KSO Organization',
        'company_address' => $template_data['company_address'] ?? 'KSO Headquarters, City, State 12345',
        'company_phone' => $template_data['company_phone'] ?? '(555) 123-4567',
        'company_email' => $template_data['company_email'] ?? 'info@kso.com',
        'logo_path' => $template_data['logo_path'] ?? null,
        'theme_color' => $template_data['theme_color'] ?? '#006496',
        'show_watermark' => $template_data['show_watermark'] ?? true,
        'custom_footer' => $template_data['custom_footer'] ?? null,
        'include_qr' => $template_data['include_qr'] ?? true,
        'digital_signature' => $template_data['digital_signature'] ?? true
    ];
    
    // Generate preview HTML
    $previewHtml = generatePreviewHTML($type, $data, $customizations);
    
    echo json_encode([
        'success' => true,
        'preview_html' => $previewHtml,
        'type' => $type,
        'number' => $number
    ]);
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error generating preview: ' . $e->getMessage()]);
}

function generatePreviewHTML($type, $data, $customizations) {
    $themeColor = $customizations['theme_color'];
    $companyName = $customizations['company_name'];
    $companyAddress = $customizations['company_address'];
    $companyPhone = $customizations['company_phone'];
    $companyEmail = $customizations['company_email'];
    
    ob_start();
    ?>
    <div style="font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; background: white;">
        <!-- Header -->
        <div style="border-bottom: 2px solid <?php echo $themeColor; ?>; padding-bottom: 20px; margin-bottom: 30px;">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <h1 style="color: <?php echo $themeColor; ?>; margin: 0; font-size: 24px;"><?php echo $companyName; ?></h1>
                    <p style="margin: 5px 0; color: #666; font-size: 14px;"><?php echo $companyAddress; ?></p>
                    <p style="margin: 5px 0; color: #666; font-size: 14px;">Phone: <?php echo $companyPhone; ?> | Email: <?php echo $companyEmail; ?></p>
                </div>
                <div style="text-align: right;">
                    <h2 style="color: #333; margin: 0; font-size: 32px; font-weight: bold;">
                        <?php echo strtoupper($type); ?>
                    </h2>
                </div>
            </div>
        </div>
        
        <!-- Document Details -->
        <div style="display: flex; justify-content: space-between; margin-bottom: 30px;">
            <div style="flex: 1;">
                <h3 style="color: <?php echo $themeColor; ?>; margin-bottom: 10px;">
                    <?php echo $type === 'receipt' ? 'Receipt To:' : 'Bill To:'; ?>
                </h3>
                <p style="margin: 5px 0; font-size: 14px;"><strong><?php echo $data['first_name'] . ' ' . $data['last_name']; ?></strong></p>
                <p style="margin: 5px 0; font-size: 14px;">KSO ID: <?php echo $data['kso_id']; ?></p>
                <p style="margin: 5px 0; font-size: 14px;">Email: <?php echo $data['email']; ?></p>
                <p style="margin: 5px 0; font-size: 14px;">Phone: <?php echo $data['phone']; ?></p>
                <?php if (!empty($data['address'])): ?>
                <p style="margin: 5px 0; font-size: 14px;">Address: <?php echo $data['address']; ?></p>
                <?php endif; ?>
            </div>
            
            <div style="background: #f5f5f5; padding: 20px; border-radius: 8px; min-width: 250px;">
                <table style="width: 100%; font-size: 14px;">
                    <tr>
                        <td style="padding: 5px 0; font-weight: bold;">
                            <?php echo $type === 'receipt' ? 'Receipt #:' : 'Invoice #:'; ?>
                        </td>
                        <td style="padding: 5px 0; text-align: right;">
                            <?php echo $type === 'receipt' ? $data['receipt_number'] : $data['invoice_number']; ?>
                        </td>
                    </tr>
                    <tr>
                        <td style="padding: 5px 0; font-weight: bold;">Date:</td>
                        <td style="padding: 5px 0; text-align: right;"><?php echo date('Y-m-d', strtotime($data['created_at'])); ?></td>
                    </tr>
                    <?php if ($type === 'invoice'): ?>
                    <tr>
                        <td style="padding: 5px 0; font-weight: bold;">Due Date:</td>
                        <td style="padding: 5px 0; text-align: right;"><?php echo date('Y-m-d', strtotime($data['due_date'])); ?></td>
                    </tr>
                    <tr>
                        <td style="padding: 5px 0; font-weight: bold;">Status:</td>
                        <td style="padding: 5px 0; text-align: right;">
                            <span style="color: <?php echo $data['status'] === 'paid' ? 'green' : 'red'; ?>;">
                                <?php echo ucfirst($data['status']); ?>
                            </span>
                        </td>
                    </tr>
                    <?php endif; ?>
                </table>
            </div>
        </div>
        
        <!-- Items/Details -->
        <?php if ($type === 'invoice' && !empty($data['items'])): ?>
        <div style="margin-bottom: 30px;">
            <table style="width: 100%; border-collapse: collapse; font-size: 14px;">
                <thead>
                    <tr style="background: <?php echo $themeColor; ?>; color: white;">
                        <th style="padding: 12px; text-align: left; border: 1px solid #ddd;">Description</th>
                        <th style="padding: 12px; text-align: center; border: 1px solid #ddd;">Quantity</th>
                        <th style="padding: 12px; text-align: right; border: 1px solid #ddd;">Unit Price</th>
                        <th style="padding: 12px; text-align: right; border: 1px solid #ddd;">Total</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $items = json_decode($data['items'], true) ?? [];
                    foreach ($items as $item): 
                    ?>
                    <tr>
                        <td style="padding: 10px; border: 1px solid #ddd;"><?php echo htmlspecialchars($item['description']); ?></td>
                        <td style="padding: 10px; text-align: center; border: 1px solid #ddd;"><?php echo $item['quantity']; ?></td>
                        <td style="padding: 10px; text-align: right; border: 1px solid #ddd;">$<?php echo number_format($item['unit_price'], 2); ?></td>
                        <td style="padding: 10px; text-align: right; border: 1px solid #ddd;">$<?php echo number_format($item['total'], 2); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
        
        <!-- Totals -->
        <div style="margin-bottom: 30px;">
            <table style="width: 100%; font-size: 14px;">
                <tr>
                    <td style="width: 70%;"></td>
                    <td style="width: 30%;">
                        <table style="width: 100%; border-collapse: collapse;">
                            <?php if ($type === 'invoice'): ?>
                            <tr>
                                <td style="padding: 8px; text-align: right; border: 1px solid #ddd; background: #f9f9f9;">
                                    <strong>Subtotal:</strong>
                                </td>
                                <td style="padding: 8px; text-align: right; border: 1px solid #ddd; background: #f9f9f9;">
                                    $<?php echo number_format($data['subtotal'], 2); ?>
                                </td>
                            </tr>
                            <?php if ($data['tax_amount'] > 0): ?>
                            <tr>
                                <td style="padding: 8px; text-align: right; border: 1px solid #ddd; background: #f9f9f9;">
                                    <strong>Tax:</strong>
                                </td>
                                <td style="padding: 8px; text-align: right; border: 1px solid #ddd; background: #f9f9f9;">
                                    $<?php echo number_format($data['tax_amount'], 2); ?>
                                </td>
                            </tr>
                            <?php endif; ?>
                            <tr>
                                <td style="padding: 10px; text-align: right; border: 2px solid <?php echo $themeColor; ?>; background: <?php echo $themeColor; ?>; color: white;">
                                    <strong>Total:</strong>
                                </td>
                                <td style="padding: 10px; text-align: right; border: 2px solid <?php echo $themeColor; ?>; background: <?php echo $themeColor; ?>; color: white;">
                                    <strong>$<?php echo number_format($data['total_amount'], 2); ?></strong>
                                </td>
                            </tr>
                            <?php else: ?>
                            <tr>
                                <td style="padding: 10px; text-align: right; border: 2px solid <?php echo $themeColor; ?>; background: <?php echo $themeColor; ?>; color: white;">
                                    <strong>Amount:</strong>
                                </td>
                                <td style="padding: 10px; text-align: right; border: 2px solid <?php echo $themeColor; ?>; background: <?php echo $themeColor; ?>; color: white;">
                                    <strong>$<?php echo number_format($data['amount'], 2); ?></strong>
                                </td>
                            </tr>
                            <?php endif; ?>
                        </table>
                    </td>
                </tr>
            </table>
        </div>
        
        <!-- Footer -->
        <div style="margin-top: 50px; padding-top: 20px; border-top: 1px solid #ddd;">
            <div style="display: flex; justify-content: space-between; align-items: flex-end;">
                <div style="flex: 1;">
                    <?php if ($customizations['include_qr']): ?>
                    <div style="width: 100px; height: 100px; background: #f0f0f0; border: 1px solid #ddd; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #666;">
                        QR Code
                    </div>
                    <?php endif; ?>
                </div>
                
                <?php if ($customizations['digital_signature']): ?>
                <div style="text-align: right;">
                    <p style="margin: 0; font-size: 12px; color: #666;">Authorized Signature:</p>
                    <div style="width: 200px; height: 50px; border-bottom: 1px solid #333; margin: 10px 0;"></div>
                    <p style="margin: 0; font-size: 12px; color: #666;">Date: <?php echo date('Y-m-d'); ?></p>
                </div>
                <?php endif; ?>
            </div>
            
            <?php if ($customizations['custom_footer']): ?>
            <div style="text-align: center; margin-top: 20px; font-size: 12px; color: #666;">
                <?php echo nl2br(htmlspecialchars($customizations['custom_footer'])); ?>
            </div>
            <?php endif; ?>
        </div>
        
        <!-- Watermark -->
        <?php if ($customizations['show_watermark'] && ($type === 'invoice' && $data['status'] !== 'paid')): ?>
        <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) rotate(-45deg); font-size: 60px; color: rgba(255, 0, 0, 0.1); font-weight: bold; z-index: -1;">
            <?php echo strtoupper($data['status']); ?>
        </div>
        <?php endif; ?>
    </div>
    <?php
    return ob_get_clean();
}
?>
