<?php
require_once 'db_config.php';

// Get registration ID and hash from URL
$registrationNumber = $_GET['id'] ?? '';
$accessHash = $_GET['hash'] ?? '';

if (empty($registrationNumber) || empty($accessHash)) {
    die('Invalid access parameters');
}

try {
    // Initialize database connection
    $pdo = getDBConnection();
    
    // Get registration details
    $stmt = $pdo->prepare("
        SELECT 
            r.*,
            pt.transaction_reference,
            pt.amount as payment_amount,
            pt.transaction_status,
            pt.created_at as payment_date,
            MD5(CONCAT(r.registration_number, r.contact_email, r.created_at)) as security_hash
        FROM registrations r
        LEFT JOIN payment_transactions pt ON r.id = pt.registration_id
        WHERE r.registration_number = ?
        ORDER BY pt.created_at DESC
        LIMIT 1
    ");
    $stmt->execute([$registrationNumber]);
    $registration = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$registration) {
        die('Registration not found');
    }
    
    // Verify access hash for security
    if ($accessHash !== $registration['security_hash']) {
        die('Invalid access token');
    }
    
    // Get purchased products
    $stmt = $pdo->prepare("
        SELECT 
            rp.*, 
            p.name as product_name, 
            p.product_code, 
            pc.name as category
        FROM registration_products rp 
        JOIN products p ON rp.product_id = p.id 
        LEFT JOIN product_categories pc ON p.category_id = pc.id
        WHERE rp.registration_id = ?
        ORDER BY pc.name, p.name
    ");
    $stmt->execute([$registration['id']]);
    $purchased_products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get company settings
    $settingsStmt = $pdo->prepare("SELECT setting_key, setting_value FROM admin_settings");
    $settingsStmt->execute();
    $settingsRows = $settingsStmt->fetchAll(PDO::FETCH_ASSOC);
    
    $settings = [];
    foreach ($settingsRows as $row) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
    
    // Generate invoice number and type based on payment status
    $isPaid = ($registration['payment_status'] === 'paid');
    $invoiceType = $isPaid ? 'INVOICE' : 'PROFORMA INVOICE';
    $invoicePrefix = $isPaid ? 'INV' : 'PI';
    $invoiceNumber = $invoicePrefix . '-' . $registration['registration_number'] . '-' . date('Y');
    $invoiceDate = date('F j, Y');
    $dueDate = date('F j, Y', strtotime('+7 days'));
    
    // Legacy line items (keeping for backward compatibility)
    $delegatePrice = $registration['delegate_type'] === 'earlyBird' ? 500 : 550;
    $standardTablePrice = $registration['has_standard_table'] ? 550 : 0;
    $doubleTablePrice = $registration['has_double_table'] ? 850 : 0;
    
    // Format company address into two lines as requested:
    // Line 1: "7 Temasek Boulevard #12-07,"
    // Line 2: "Suntec Tower One, Singapore 038987"
    
    $originalLine1 = trim($settings['companyAddress'] ?? '');
    $originalLine2 = trim($settings['companyAddress2'] ?? '');
    
    // Check if we need to reformat the address based on the current content
    if ($originalLine1 === "7 Temasek Boulevard #12-07 Suntec Tower One" && $originalLine2 === "Singapore 038987") {
        // Reformat to the desired format
        $addressLine1 = "7 Temasek Boulevard #12-07,";
        $addressLine2 = "Suntec Tower One, Singapore 038987";
    } else if (!empty($originalLine1) && !empty($originalLine2)) {
        // Use existing two-line format, ensure first line has comma
        $addressLine1 = $originalLine1;
        $addressLine2 = $originalLine2;
        if (substr($addressLine1, -1) !== ',') {
            $addressLine1 .= ',';
        }
    } else if (!empty($originalLine1) && empty($originalLine2)) {
        // Try to split single line intelligently
        if (strpos($originalLine1, ',') !== false) {
            $parts = explode(',', $originalLine1, 2);
            if (count($parts) === 2) {
                $addressLine1 = trim($parts[0]) . ',';
                $addressLine2 = trim($parts[1]);
            }
        } else {
            // Try regex patterns for splitting
            $patterns = [
                '/^(.+#\d+[-\d]*)\s+(.+)$/',  // Split after unit number like #12-07
                '/^(.+Boulevard\s+#\d+[-\d]*)\s*,?\s*(.+)$/',  // Split after Boulevard + unit
                '/^(.+Street\s+#\d+[-\d]*)\s*,?\s*(.+)$/',     // Split after Street + unit
                '/^(.+Road\s+#\d+[-\d]*)\s*,?\s*(.+)$/',      // Split after Road + unit
            ];
            
            foreach ($patterns as $pattern) {
                if (preg_match($pattern, $originalLine1, $matches)) {
                    $addressLine1 = trim($matches[1]) . ',';
                    $addressLine2 = trim($matches[2]);
                    break;
                }
            }
            
            // If no pattern matched, use original line
            if (!isset($addressLine1)) {
                $addressLine1 = $originalLine1;
                $addressLine2 = '';
            }
        }
    } else {
        $addressLine1 = $originalLine1;
        $addressLine2 = $originalLine2;
    }
    
} catch (Exception $e) {
    die('Database error: ' . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $invoiceType; ?> <?php echo htmlspecialchars($invoiceNumber); ?></title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <style>
        /* Invoice Styles */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            line-height: 1.6;
            color: #000000;
            background: white;
        }
        
        .invoice-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: white;
        }
        
        .invoice-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #6366f1;
        }
        
        .invoice-logo {
            display: block;
            max-height: 60px;
            margin-bottom: 6px;
        }
        
        .company-info h1 {
            color: #000000;
            font-size: 22px;
            font-weight: 800;
            margin-bottom: 4px;
        }
        
        .company-info p {
            color: #000000;
            margin: 1px 0;
            font-size: 14px;
        }
        
        .invoice-meta {
            text-align: right;
        }
        
        .invoice-meta h2 {
            color: #000000;
            font-size: 24px;
            font-weight: 800;
            margin-bottom: 6px;
        }
        
        .invoice-meta p {
            color: #000000;
            margin: 2px 0;
            font-size: 13px;
        }
        
        .invoice-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .bill-to, .event-info {
            background: #f8fafc;
            padding: 12px;
            border-radius: 6px;
        }
        
        .bill-to h3, .event-info h3 {
            color: #000000;
            font-weight: 700;
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .bill-to p, .event-info p {
            margin: 2px 0;
            color: #000000;
            font-size: 12px;
        }
        
        .invoice-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 15px;
        }
        
        .invoice-table th {
            background: #6366f1;
            color: white;
            padding: 8px 10px;
            text-align: left;
            font-weight: 600;
            font-size: 14px;
        }
        
        .invoice-table td {
            padding: 8px 10px;
            border-bottom: 1px solid #e2e8f0;
            font-size: 14px;
        }
        
        .invoice-table tr:nth-child(even) {
            background: #f8fafc;
        }
        
        .text-right {
            text-align: right;
        }
        
        .text-center {
            text-align: center;
        }
        
        .invoice-table th {
            text-align: center;
        }
        
        .invoice-table th:first-child {
            text-align: left;
        }
        
        .invoice-table td.text-center {
            vertical-align: middle;
        }
        
        .total-row {
            background: #6366f1 !important;
            color: white;
            font-weight: 500;
        }
        
        .payment-info {
            background: #f0f9ff;
            border: 1px solid #0ea5e9;
            border-radius: 6px;
            padding: 12px;
            margin-bottom: 15px;
        }
        
        .payment-info h3 {
            color: #000000;
            margin-bottom: 8px;
            font-weight: 700;
            font-size: 14px;
        }
        
        .bank-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px;
        }
        
        .bank-detail {
            display: flex;
            justify-content: space-between;
            padding: 4px 0;
            border-bottom: 1px solid #bae6fd;
            font-size: 14px;
        }
        
        .bank-detail:last-child {
            border-bottom: none;
        }
        
        .bank-detail strong {
            color: #000000;
        }
        
        .highlight {
            background: #fef3c7;
            padding: 6px;
            border-radius: 3px;
            border-left: 3px solid #f59e0b;
        }
        
        .invoice-footer {
            margin-top: 15px;
            padding-top: 10px;
            border-top: 1px solid #e2e8f0;
            color: #000000;
            font-size: 14px;
        }
        
        .status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .status-pending {
            background: #fef3c7;
            color: #92400e;
        }
        
        .status-paid {
            background: #d1fae5;
            color: #065f46;
        }
        
        .status-failed {
            background: #fee2e2;
            color: #991b1b;
        }
        
        /* Floating Print Button */
        .floating-print-bar {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(255, 255, 255, 0.95);
            padding: 10px 0;
            text-align: center;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
            z-index: 1000;
            border-top: 1px solid #e2e8f0;
        }
        
        .print-button {
            background: #6366f1;
            color: white;
            border: none;
            padding: 10px 24px;
            border-radius: 6px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .print-button:hover {
            background: #4f46e5;
        }
        
        /* Print Styles */
        @media print {
            @page {
                size: A4;
                margin: 0.5in;
            }
            
            body {
                margin: 0;
                padding: 0;
                font-size: 11px !important;
                line-height: 1.3 !important;
            }
            
            /* Force background colors to print */
            * {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
                color-adjust: exact !important;
            }
            
            /* Ensure table headers maintain their color and visibility */
            .invoice-table th {
                background-color: #6366f1 !important;
                color: white !important;
            }
            
            /* Ensure total row maintains its color and visibility */
            .total-row {
                background-color: #6366f1 !important;
                color: white !important;
            }
            
            /* Ensure strong text in total row is visible */
            .total-row strong {
                color: white !important;
            }
            
            .invoice-container {
                padding: 0 !important;
                margin: 0 !important;
                box-shadow: none;
                max-width: 100% !important;
            }
            
            .invoice-header {
                margin-bottom: 12px !important;
                padding-bottom: 6px !important;
            }
            
            .company-info h1 {
                font-size: 18px !important;
                margin-bottom: 2px !important;
            }
            
            .invoice-meta h2 {
                font-size: 20px !important;
                margin-bottom: 4px !important;
            }
            
            .invoice-details {
                margin-bottom: 12px !important;
                gap: 12px !important;
            }
            
            .bill-to, .event-info {
                padding: 8px !important;
            }
            
            .invoice-table {
                margin-bottom: 10px !important;
            }
            
            .invoice-table th {
                padding: 6px 8px !important;
                font-size: 12px !important;
            }
            
            .invoice-table td {
                padding: 6px 8px !important;
                font-size: 12px !important;
            }
            
            .payment-info {
                padding: 8px !important;
                margin-bottom: 10px !important;
            }
            
            .payment-info h3 {
                font-size: 12px !important;
                margin-bottom: 6px !important;
            }
            
            .bank-details {
                gap: 6px !important;
            }
            
            .bank-detail {
                padding: 2px 0 !important;
                font-size: 12px !important;
            }
            
            .invoice-footer {
                margin-top: 10px !important;
                padding-top: 6px !important;
                font-size: 9px !important;
            }
            
            .highlight {
                padding: 4px !important;
            }
            
            /* Fix for Important notice font size */
            .payment-info div[style*="margin-top: 15px"] p {
                font-size: 12px !important;
            }
            
            .no-print {
                display: none !important;
            }
            
            /* Ensure content fits on one page */
            .invoice-container {
                page-break-inside: avoid;
                transform: scale(0.95);
                transform-origin: top left;
            }
        }
    </style>
</head>
<body>
    <div class="invoice-container">
        <!-- Invoice Header -->
        <div class="invoice-header">
            <div class="company-info">
                <?php if (!empty($settings['companyLogo'])): ?>
                <img src="<?php echo htmlspecialchars($settings['companyLogo']); ?>" alt="Company Logo" class="invoice-logo">
                <?php endif; ?>
                <h1><?php echo htmlspecialchars($settings['accountName'] ?? ''); ?></h1>
                <p><?php echo htmlspecialchars($addressLine1); ?></p>
                <p><?php echo htmlspecialchars($addressLine2); ?></p>
                <p>Email: <?php echo htmlspecialchars($settings['adminEmail'] ?? ''); ?></p>
                <p>Phone: <?php echo htmlspecialchars($settings['companyPhone'] ?? ''); ?></p>
            </div>
            <div class="invoice-meta">
                <h2><?php echo $invoiceType; ?></h2>
                <p><strong><?php echo $isPaid ? 'Invoice' : 'Proforma'; ?> #:</strong> <?php echo htmlspecialchars($invoiceNumber); ?></p>
                <p><strong>Date:</strong> <?php echo $invoiceDate; ?></p>
                <p><strong>Due Date:</strong> <?php echo $dueDate; ?></p>
                <p><strong>Status:</strong> 
                    <span class="status-badge status-<?php echo $registration['payment_status']; ?>">
                        <?php echo ucfirst($registration['payment_status']); ?>
                    </span>
                </p>
            </div>
        </div>
        
        <!-- Invoice Details -->
        <div class="invoice-details">
            <div class="bill-to">
                <h3>Bill To:</h3>
                <p><strong><?php echo htmlspecialchars($registration['contact_full_name']); ?></strong></p>
                <p><?php echo htmlspecialchars($registration['contact_designation'] ?? ''); ?></p>
                <p><?php echo htmlspecialchars($registration['university_name']); ?></p>
                <p><?php echo htmlspecialchars($registration['country']); ?></p>
                <p>Email: <?php echo htmlspecialchars($registration['contact_email']); ?></p>
                <p>Phone: <?php echo htmlspecialchars($registration['contact_mobile']); ?></p>
            </div>
            
            <div class="event-info">
                <h3>Event Information:</h3>
                <p><strong>AppliedHE Xchange 2025</strong></p>
                <p>Registration #: <?php echo htmlspecialchars($registration['registration_number']); ?></p>
                <p>Registration Date: <?php echo date('F j, Y', strtotime($registration['created_at'])); ?></p>
                <?php if ($registration['payment_method']): ?>
                <p>Payment Method: <?php echo $registration['payment_method'] === 'gateway' ? 'Online Payment' : 'Bank Transfer'; ?></p>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Invoice Table -->
        <table class="invoice-table">
            <thead>
                <tr>
                    <th>Description</th>
                    <th class="text-center">Quantity</th>
                    <th class="text-center">Unit Price</th>
                    <th class="text-center">Amount</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($purchased_products)): ?>
                    <?php foreach ($purchased_products as $product): ?>
                    <tr>
                        <td>
                            <?php echo htmlspecialchars($product['product_name']); ?>
                            <?php if (!empty($product['product_code'])): ?>
                            <br><small>Product Code: <?php echo htmlspecialchars($product['product_code']); ?></small>
                            <?php endif; ?>
                        </td>
                        <td class="text-center"><?php echo $product['quantity']; ?></td>
                        <td class="text-center">USD $<?php echo number_format($product['unit_price'], 2); ?></td>
                        <td class="text-center">USD $<?php echo number_format($product['total_price'], 2); ?></td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <!-- Fallback to legacy display if no products found -->
                    <tr>
                        <td>
                            Delegate Pass (<?php echo $registration['delegate_type'] === 'earlyBird' ? 'Early Bird' : 'Standard'; ?>)
                            <br><small>AppliedHE Xchange 2025 Conference</small>
                        </td>
                        <td class="text-center"><?php echo $registration['delegate_count']; ?></td>
                        <td class="text-center">USD $<?php echo number_format($delegatePrice); ?></td>
                        <td class="text-center">USD $<?php echo number_format($delegatePrice * $registration['delegate_count']); ?></td>
                    </tr>
                    
                    <?php if ($registration['has_standard_table']): ?>
                    <tr>
                        <td>
                            Standard Table-top Presentation
                            <br><small>Exhibition space with standard setup</small>
                        </td>
                        <td class="text-center">1</td>
                        <td class="text-center">USD $<?php echo number_format($standardTablePrice); ?></td>
                        <td class="text-center">USD $<?php echo number_format($standardTablePrice); ?></td>
                    </tr>
                    <?php endif; ?>
                    
                    <?php if ($registration['has_double_table']): ?>
                    <tr>
                        <td>
                            Double Table-top Presentation
                            <br><small>Premium exhibition space with enhanced setup</small>
                        </td>
                        <td class="text-center">1</td>
                        <td class="text-center">USD $<?php echo number_format($doubleTablePrice); ?></td>
                        <td class="text-center">USD $<?php echo number_format($doubleTablePrice); ?></td>
                    </tr>
                    <?php endif; ?>
                <?php endif; ?>
                
                <tr class="total-row">
                    <td colspan="3"><strong>TOTAL AMOUNT</strong></td>
                    <td class="text-center"><strong>USD $<?php echo number_format($registration['total_amount']); ?></strong></td>
                </tr>
            </tbody>
        </table>
        
        <!-- Payment Information -->
        <?php if ($registration['payment_method'] === 'tt'): ?>
        <div class="payment-info">
            <h3>🏦 Payment Instructions</h3>
            <p>Please complete payment using the bank details below:</p>
            
            <div class="bank-details">
                <div>
                    <div class="bank-detail">
                        <span><strong>Bank Name:</strong></span>
                        <span><?php echo htmlspecialchars($settings['bankName'] ?? ''); ?></span>
                    </div>
                    <div class="bank-detail">
                        <span><strong>Account Name:</strong></span>
                        <span><?php echo htmlspecialchars($settings['accountName'] ?? ''); ?></span>
                    </div>
                    <div class="bank-detail">
                        <span><strong>Account Number:</strong></span>
                        <span><?php echo htmlspecialchars($settings['accountNumber'] ?? ''); ?></span>
                    </div>
                </div>
                <div>
                    <div class="bank-detail">
                        <span><strong>SWIFT Code:</strong></span>
                        <span><?php echo htmlspecialchars($settings['swiftCode'] ?? ''); ?></span>
                    </div>
                    <div class="bank-detail highlight">
                        <span><strong>Reference:</strong></span>
                        <span><?php echo htmlspecialchars($registration['registration_number']); ?></span>
                    </div>
                    <div class="bank-detail highlight">
                        <span><strong>Amount:</strong></span>
                        <span>USD $<?php echo number_format($registration['total_amount']); ?></span>
                    </div>
                </div>
            </div>
            
            <div style="margin-top: 15px; padding: 10px; background: #fef3c7; border-radius: 4px;">
                <p style="font-size: 14px;"><strong>Important:</strong> Please use the exact reference number <strong><?php echo htmlspecialchars($registration['registration_number']); ?></strong> when making the transfer.</p>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Invoice Footer -->
        <div class="invoice-footer">
            <p><strong>Terms & Conditions:</strong></p>
            <?php 
            $termsConditions = $settings['invoiceTermsConditions'] ?? "• Payment is due within 7 days of invoice date\n• Please include the reference number with your payment\n• For any queries, contact us at finance@appliedhe.com\n• All prices are in USD and subject to change without notice\n• Registration is confirmed upon receipt of payment";
            echo '<p>' . nl2br(htmlspecialchars($termsConditions)) . '</p>';
            ?>
        </div>
        <div style="margin-top: 20px; text-align: center; color: #000000;">
            <p style="font-size: 14px;">This invoice was generated on <?php echo date('F j, Y \a\t g:i A'); ?></p>
        </div>
        
        <!-- Floating Print Button Bar -->
        <div class="floating-print-bar no-print">
            <button onclick="window.print()" class="print-button">
                🖨️ Print Invoice
            </button>
            <button onclick="window.close()" class="print-button" style="background: #000000; margin-left: 10px;">
                ✕ Close
            </button>
        </div>
        
        <script>
        // Add padding to the bottom of the body to prevent the floating bar from covering content
        document.addEventListener('DOMContentLoaded', function() {
            const floatingBar = document.querySelector('.floating-print-bar');
            if (floatingBar) {
                const barHeight = floatingBar.offsetHeight;
                document.body.style.paddingBottom = (barHeight + 20) + 'px';
            }
        });
        </script>
    </div>
</body>
</html>
