<?php
// Payment Acknowledgement Receipt Template - Based on Invoice Template
// This template generates a professional receipt matching the invoice design

// Get settings
$settings = InvoiceSettings::get() ?? [];

// Calculate totals
$totalPaid = array_sum(array_column($payments, 'amount'));
$amountDue = $invoiceData['total'] - $totalPaid;
$paymentStatus = $amountDue <= 0 ? 'Paid' : ($totalPaid > 0 ? 'Partially Paid' : 'Unpaid');

// Company info from settings
$companyName = $settings['company_name'] ?? 'Your Company';

// Build company address from individual fields
$addressParts = [];
if (!empty($settings['address_line_1'])) $addressParts[] = $settings['address_line_1'];
if (!empty($settings['address_line_2'])) $addressParts[] = $settings['address_line_2'];
if (!empty($settings['city'])) $addressParts[] = $settings['city'];
if (!empty($settings['state'])) $addressParts[] = $settings['state'];
if (!empty($settings['zip_code'])) $addressParts[] = $settings['zip_code'];
if (!empty($settings['country'])) $addressParts[] = $settings['country'];
$companyAddress = !empty($addressParts) ? implode("\n", $addressParts) : 'Your Address';

$companyEmail = $settings['company_email'] ?? 'contact@yourcompany.com';
$companyPhone = $settings['company_phone'] ?? 'Your Phone';
$companyLogo = $settings['company_logo_path'] ?? '';

// Get the latest payment for this receipt
$latestPayment = !empty($payments) ? $payments[0] : null;
$receiptNumber = 'R-' . $invoiceData['invoice_number'] . '-' . date('YmdHis');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Payment Receipt <?= h($receiptNumber) ?></title>
    <style>
        @page { size: A4; margin: 20mm; }
        body { 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
            font-size: 14px; 
            line-height: 1.6; 
            margin: 0; 
            padding: 0; 
            color: #1a1a1a; 
            background: white; 
        }
        .receipt-container { padding: 12px; background: white; max-width: 800px; margin: 0 auto; }
        .header { border-bottom: 1px solid #e5e5e5; padding-bottom: 20px; margin-bottom: 20px; }
        .header-flex { display: flex; justify-content: space-between; align-items: flex-start; }
        .logo { max-width: 120px; max-height: 40px; object-fit: contain; }
        .logo-placeholder { width: 120px; height: 40px; background: #f8f9fa; border: 1px solid #e5e5e5; border-radius: 4px; display: flex; align-items: center; justify-content: center; }
        .logo-text { color: #9ca3af; font-size: 12px; font-weight: 500; }
        .receipt-title { font-size: 28px; font-weight: 600; color: #1a1a1a; letter-spacing: -0.5px; }
        .receipt-number { font-size: 18px; font-weight: 700; color: #1a1a1a; margin-top: 4px; }
        .receipt-dates { font-size: 14px; color: #6b7280; margin-top: 8px; line-height: 1.5; }
        .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px; }
        .section-title { font-size: 11px; font-weight: 600; color: #8892b0; margin-bottom: 16px; text-transform: uppercase; letter-spacing: 0.5px; }
        .company-name { font-weight: 600; color: #1a1a1a; font-size: 16px; margin-bottom: 4px; }
        .company-legal { font-weight: 400; color: #6b7280; font-size: 14px; margin-bottom: 8px; }
        .address { font-size: 14px; color: #6b7280; white-space: pre-line; word-break: break-word; margin-bottom: 12px; line-height: 1.5; }
        .contact { font-size: 14px; color: #6b7280; margin-top: 12px; line-height: 1.5; }
        .contact-item { margin-bottom: 4px; display: flex; align-items: center; }
        .contact-item svg { width: 14px; height: 14px; margin-right: 6px; opacity: 0.6; }
        .meta-item { margin-bottom: 4px; }
        .meta-label { font-weight: 600; color: #4b5563; }
        
        .payment-status {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .status-paid { background: #dcfce7; color: #166534; }
        .status-partially-paid { background: #fef3c7; color: #92400e; }
        .status-unpaid { background: #fee2e2; color: #dc2626; }
        
        .amount-summary { border: 1px solid #e5e5e5; border-radius: 4px; overflow: hidden; margin-bottom: 20px; }
        .amount-row { display: flex; justify-content: space-between; align-items: center; padding: 10px 16px; border-bottom: 1px solid #f5f5f5; background: white; }
        .amount-row:last-child { border-bottom: none; }
        .amount-row.total { background: #1a1a1a; padding: 12px 16px; }
        .amount-row.total .amount-label { color: white; font-weight: 600; font-size: 14px; }
        .amount-row.total .amount-value { color: white; font-size: 18px; font-weight: 700; }
        .amount-label { font-size: 14px; color: #6b7280; font-weight: 500; }
        .amount-value { font-size: 14px; font-weight: 600; color: #1a1a1a; }
        
        .payment-history { margin-bottom: 20px; }
        .payment-item { border: 1px solid #e5e5e5; border-radius: 4px; padding: 16px; margin-bottom: 12px; background: #fafbfc; }
        .payment-item-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
        .payment-amount { font-weight: 700; color: #059669; font-size: 16px; }
        .payment-date { color: #6b7280; font-size: 13px; }
        .payment-method { background: #e2e8f0; color: #475569; padding: 2px 8px; border-radius: 12px; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
        .payment-notes { color: #6b7280; font-size: 13px; margin-top: 8px; line-height: 1.5; }
        
        .footer { margin-top: 40px; padding-top: 20px; border-top: 1px solid #e5e5e5; text-align: center; font-size: 12px; color: #6b7280; }
    </style>
</head>
<body>
    <div class="receipt-container">
        <!-- Receipt Header -->
        <div class="header">
            <div class="header-flex">
                <!-- Left: Logo -->
                <div>
                    <?php if (!empty($settings['company_logo_path'])): ?>
                        <?php 
                        // Convert to absolute file path and encode as base64 for Puppeteer
                        $logoPath = $settings['company_logo_path'];
                        if (strpos($logoPath, '/') === 0) {
                            $logoPath = __DIR__ . '/../public' . $logoPath;
                        }
                        
                        if (file_exists($logoPath)) {
                            $imageData = base64_encode(file_get_contents($logoPath));
                            $mimeType = mime_content_type($logoPath);
                            $logoSrc = 'data:' . $mimeType . ';base64,' . $imageData;
                        } else {
                            $logoSrc = '';
                            error_log("Logo file not found: " . $logoPath);
                        }
                        ?>
                        <?php if (!empty($logoSrc)): ?>
                            <img src="<?= h($logoSrc) ?>" alt="Company Logo" class="logo">
                        <?php else: ?>
                            <div class="logo-placeholder">
                                <div class="logo-text"><?= h($companyName) ?></div>
                            </div>
                        <?php endif; ?>
                    <?php else: ?>
                        <div class="logo-placeholder">
                            <div class="logo-text"><?= h($companyName) ?></div>
                        </div>
                    <?php endif; ?>
                </div>
                
                <!-- Right: Receipt Info -->
                <div style="text-align: right;">
                    <div class="receipt-title">PAYMENT RECEIPT</div>
                    <div class="receipt-number"><?= h($receiptNumber) ?></div>
                    <div class="receipt-dates">
                        Receipt Date: <?= date('F j, Y') ?><br>
                        Invoice: <?= h($invoiceData['invoice_number']) ?>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Company & Client Info -->
        <div class="grid-2">
            <!-- Company Information -->
            <div>
                <div class="section-title">COMPANY INFORMATION</div>
                <div class="company-name"><?= h($companyName) ?></div>
                <div class="address"><?= h($companyAddress) ?></div>
                <div class="contact">
                    <div class="contact-item">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                        </svg>
                        <?= h($companyEmail) ?>
                    </div>
                    <div class="contact-item">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"></path>
                        </svg>
                        <?= h($companyPhone) ?>
                    </div>
                </div>
            </div>
            
            <!-- Client Information -->
            <div>
                <div class="section-title">CLIENT INFORMATION</div>
                <div class="company-name"><?= h($invoiceData['client_info']['name']) ?></div>
                <?php if (!empty($invoiceData['client_info']['company_name'])): ?>
                    <div class="company-legal"><?= h($invoiceData['client_info']['company_name']) ?></div>
                <?php endif; ?>
                <?php if (!empty($invoiceData['client_info']['address'])): ?>
                    <div class="address"><?= h($invoiceData['client_info']['address']) ?></div>
                <?php endif; ?>
                <div class="contact">
                    <?php if (!empty($invoiceData['client_info']['email'])): ?>
                        <div class="contact-item">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                            </svg>
                            <?= h($invoiceData['client_info']['email']) ?>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($invoiceData['client_info']['phone'])): ?>
                        <div class="contact-item">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"></path>
                            </svg>
                            <?= h($invoiceData['client_info']['phone']) ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Payment Status Summary -->
        <div class="section-title">PAYMENT STATUS</div>
        <div class="amount-summary">
            <div class="amount-row">
                <span class="amount-label">Invoice Amount:</span>
                <span class="amount-value"><?= h($settings['currency'] ?? 'USD') ?> <?= number_format($invoiceData['total'], 2) ?></span>
            </div>
            <div class="amount-row">
                <span class="amount-label">Total Paid:</span>
                <span class="amount-value"><?= h($settings['currency'] ?? 'USD') ?> <?= number_format($totalPaid, 2) ?></span>
            </div>
            <div class="amount-row">
                <span class="amount-label">Balance Due:</span>
                <span class="amount-value"><?= h($settings['currency'] ?? 'USD') ?> <?= number_format($amountDue, 2) ?></span>
            </div>
            <div class="amount-row total">
                <span class="amount-label">Payment Status:</span>
                <span class="payment-status status-<?= str_replace('_', '-', $paymentStatus) ?>"><?= h($paymentStatus) ?></span>
            </div>
        </div>
        
        <!-- Payment History -->
        <div class="payment-history">
            <div class="section-title">PAYMENT HISTORY</div>
            <?php if (!empty($payments)): ?>
                <?php foreach ($payments as $payment): ?>
                    <div class="payment-item">
                        <div class="payment-item-header">
                            <div>
                                <span class="payment-amount"><?= h($settings['currency'] ?? 'USD') ?> <?= number_format($payment['amount'], 2) ?></span>
                                <span class="payment-date"><?= date('F j, Y', strtotime($payment['payment_date'])) ?></span>
                            </div>
                            <span class="payment-method"><?= h(ucwords(str_replace('_', ' ', $payment['payment_method']))) ?></span>
                        </div>
                        <?php if (!empty($payment['notes'])): ?>
                            <div class="payment-notes">
                                <strong>Notes:</strong> <?= h($payment['notes']) ?>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div style="text-align: center; color: #6b7280; padding: 2rem;">
                    No payments recorded yet
                </div>
            <?php endif; ?>
        </div>
        
        <!-- Footer -->
        <div class="footer">
            <div style="margin-bottom: 1rem;">
                This is a computer-generated receipt and does not require a signature.
            </div>
            <div>
                For questions about this receipt, please contact us at <?= h($companyEmail) ?>
            </div>
        </div>
    </div>
</body>
</html>
