<?php
/**
 * Generate Payment Receipt for Paid Cash Invoices
 * Includes payment method, payer details, and service details
 */

session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$invoice_id = isset($_GET['id']) ? intval($_GET['id']) : (isset($_GET['invoice_id']) ? intval($_GET['invoice_id']) : 0);

if (!$invoice_id) {
    die('Invalid invoice ID');
}

// Fetch invoice details
$invoice_sql = "SELECT 
    i.*,
    p.patient_id,
    p.patient_number,
    u.full_name as patient_name,
    u.gender,
    u.date_of_birth,
    u.phone_primary,
    u.email,
    u.address,
    creator.full_name as created_by_name,
    pv.visit_id,
    pv.visit_number
FROM invoices i
INNER JOIN patients p ON i.patient_id = p.patient_id
INNER JOIN users u ON p.user_id = u.user_id
LEFT JOIN users creator ON i.created_by = creator.user_id
LEFT JOIN patient_visits pv ON i.visit_id = pv.visit_id
WHERE i.invoice_id = ?";

$stmt = $conn->prepare($invoice_sql);
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$invoice = $stmt->get_result()->fetch_assoc();

if (!$invoice) {
    die('Invoice not found');
}

// Fetch invoice items
$items_sql = "SELECT 
    ii.*
FROM invoice_items ii
WHERE ii.invoice_id = ?
ORDER BY ii.created_at, ii.item_id";

$stmt = $conn->prepare($items_sql);
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$items_result = $stmt->get_result();

// Fetch payment history
$payments_sql = "SELECT 
    p.*,
    u.full_name as recorded_by_name,
    p.payment_method as payment_method_name,
    COALESCE(p.payment_reference, p.transaction_ref) as reference_number,
    COALESCE(p.amount, p.amount_paid) as amount
FROM payments p
LEFT JOIN users u ON COALESCE(p.received_by, p.created_by) = u.user_id
WHERE p.invoice_id = ?
ORDER BY p.payment_date DESC, p.created_at DESC";

$stmt = $conn->prepare($payments_sql);
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$payments_result = $stmt->get_result();

// Get hospital settings
$settings_sql = "SELECT setting_key, setting_value FROM system_settings 
                 WHERE setting_key IN ('hospital_name', 'hospital_address', 'hospital_phone', 
                                      'hospital_email', 'hospital_logo', 'hospital_tax_id')";
$settings_result = $conn->query($settings_sql);
$settings = [];
while ($row = $settings_result->fetch_assoc()) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

// Helper function
function getSetting($key, $default = '') {
    global $settings;
    return $settings[$key] ?? $default;
}

// Calculate patient age
$age = null;
if ($invoice['date_of_birth']) {
    $dob = new DateTime($invoice['date_of_birth']);
    $now = new DateTime();
    $age = $now->diff($dob)->y;
}

// Get staff name (cashier/received by)
$staff_name = $invoice['created_by_name'] ?? 'Cashier';
if ($payments_result->num_rows > 0) {
    $first_payment = $payments_result->fetch_assoc();
    if ($first_payment['recorded_by_name']) {
        $staff_name = $first_payment['recorded_by_name'];
    }
    // Reset pointer
    $payments_result->data_seek(0);
}

// Calculate amounts
$total_amount = floatval($invoice['total_amount']);
$total_paid = floatval($invoice['amount_paid'] ?? $invoice['total_amount']);
$balance_due = floatval($invoice['balance']);

// Get payment mode from first payment
$payment_mode = 'CASH';
if ($payments_result->num_rows > 0) {
    $first_payment = $payments_result->fetch_assoc();
    $payment_mode = strtoupper($first_payment['payment_method_name'] ?? 'CASH');
    $payments_result->data_seek(0);
}

// Generate receipt number
$receipt_number = 'RCT-' . str_pad($invoice_id, 6, '0', STR_PAD_LEFT);

// Get payment date
$payment_date = $invoice['updated_at'] ?? $invoice['invoice_date'];
if ($payments_result->num_rows > 0) {
    $first_payment = $payments_result->fetch_assoc();
    if ($first_payment['payment_date']) {
        $payment_date = $first_payment['payment_date'];
    }
    $payments_result->data_seek(0);
}

// Convert amount to words function
function convertToWords($number) {
    $ones = ['', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE'];
    $teens = ['TEN', 'ELEVEN', 'TWELVE', 'THIRTEEN', 'FOURTEEN', 'FIFTEEN', 'SIXTEEN', 'SEVENTEEN', 'EIGHTEEN', 'NINETEEN'];
    $tens = ['', '', 'TWENTY', 'THIRTY', 'FORTY', 'FIFTY', 'SIXTY', 'SEVENTY', 'EIGHTY', 'NINETY'];
    $thousands = ['', 'THOUSAND', 'MILLION'];
    
    if ($number == 0) return 'ZERO';
    
    $words = '';
    $level = 0;
    
    while ($number > 0) {
        $chunk = $number % 1000;
        if ($chunk) {
            $chunk_words = '';
            
            $hundreds = floor($chunk / 100);
            if ($hundreds) {
                $chunk_words .= $ones[$hundreds] . ' HUNDRED ';
            }
            
            $remainder = $chunk % 100;
            if ($remainder >= 20) {
                $chunk_words .= $tens[floor($remainder / 10)] . ' ';
                $remainder %= 10;
            } elseif ($remainder >= 10) {
                $chunk_words .= $teens[$remainder - 10] . ' ';
                $remainder = 0;
            }
            
            if ($remainder > 0) {
                $chunk_words .= $ones[$remainder] . ' ';
            }
            
            $words = $chunk_words . $thousands[$level] . ' ' . $words;
        }
        
        $number = floor($number / 1000);
        $level++;
    }
    
    return trim($words);
}

$amount_words = convertToWords(floor($total_paid)) . ' SHILLINGS ONLY';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars(getSetting('hospital_name', 'ENT Hospital')); ?> - Payment Receipt</title>
    
    <!-- Barcode Library -->
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>
    
    <!-- QR Code Library -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: Arial, sans-serif; font-size: 11px; line-height: 1.3; background: white; color: #000; }
        .invoice-container { width: 210mm; min-height: 297mm; margin: 0 auto; padding: 12mm; background: white; position: relative; }
        .header { text-align: center; border-bottom: 2px solid #000; padding-bottom: 8px; margin-bottom: 12px; position: relative; }
        .header img { max-height: 50px; margin-bottom: 5px; }
        .header h1 { font-size: 18px; font-weight: bold; margin-bottom: 4px; letter-spacing: 1px; text-transform: uppercase; }
        .header .address { font-size: 9px; margin-bottom: 2px; }
        .header .contact { font-size: 9px; font-weight: bold; }
        .patient-info { display: flex; justify-content: space-between; margin-bottom: 15px; border: 1px solid #000; min-height: 70px; }
        .patient-left, .patient-right { flex: 1; padding: 6px 8px; }
        .patient-right { border-left: 1px solid #000; }
        .patient-info-row { display: flex; align-items: baseline; margin-bottom: 2px; min-height: 14px; }
        .patient-info-label { font-weight: bold; width: 80px; font-size: 9px; flex-shrink: 0; }
        .patient-info-value { flex: 1; border-bottom: 1px dotted #333; font-size: 9px; min-height: 12px; padding-bottom: 1px; }
        .invoice-details { border: 1px solid #000; margin-bottom: 12px; }
        .invoice-header { background: #f5f5f5; padding: 4px 8px; border-bottom: 1px solid #000; font-weight: bold; text-align: center; font-size: 10px; }
        .invoice-table { width: 100%; border-collapse: collapse; font-size: 9px; }
        .invoice-table th { border-right: 1px solid #000; border-bottom: 1px solid #000; padding: 4px; background: #f8f8f8; font-size: 8px; font-weight: bold; text-align: center; }
        .invoice-table th:last-child { border-right: none; }
        .invoice-table td { border-right: 1px solid #000; border-bottom: 1px solid #000; padding: 3px 4px; font-size: 8px; vertical-align: middle; }
        .invoice-table td:last-child { border-right: none; }
        .amount-column { text-align: right; font-weight: bold; }
        .total-row { background: #f0f0f0; font-weight: bold; }
        .total-row td { font-size: 9px; padding: 5px 4px; }
        .service-breakdown-row { background: #f9f9f9; }
        .service-breakdown-row td { font-weight: 600; }
        .payment-summary { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; margin: 15px 0; }
        .payment-box { border: 1px solid #000; padding: 6px; min-height: 60px; }
        .payment-box h4 { font-size: 8px; font-weight: bold; margin-bottom: 4px; text-align: center; background: #f5f5f5; padding: 2px; border-bottom: 1px solid #ccc; }
        .payment-row { display: flex; justify-content: space-between; margin-bottom: 1px; font-size: 8px; }
        .payment-row.highlight { border-top: 1px solid #000; padding-top: 2px; margin-top: 2px; font-weight: bold; }
        .amount-words { text-align: center; font-size: 9px; font-style: italic; margin: 8px 0; border: 1px dotted #666; padding: 6px; background: #f9f9f9; }
        .signature-section { display: flex; justify-content: space-between; margin-top: 25px; }
        .signature-box { width: 140px; text-align: center; font-size: 8px; }
        .signature-line { border-bottom: 1px solid #000; margin-bottom: 4px; height: 25px; }
        .verification-section { display: grid; grid-template-columns: 2fr 1fr; gap: 10px; margin: 15px 0; padding: 10px; border: 1px solid #ddd; border-radius: 4px; }
        .barcode-container { text-align: left; }
        .barcode-container svg { max-width: 100%; height: auto; }
        .barcode-info { font-size: 7px; color: #666; margin-top: 5px; font-family: 'Courier New', monospace; display: none; }
        .qr-container { text-align: center; border-left: 1px solid #ddd; padding-left: 10px; }
        .qr-container canvas { display: block; margin: 0 auto; }
        .qr-container img { display: block; margin: 0 auto; max-width: 100px; max-height: 100px; }
        .footer { margin-top: 20px; text-align: center; font-size: 7px; border-top: 1px solid #ccc; padding-top: 8px; }
        .footer p { margin-bottom: 2px; }
        
        @media print {
            body { -webkit-print-color-adjust: exact; color-adjust: exact; }
            .invoice-container { margin: 0; padding: 8mm; }
            .no-print { display: none; }
        }
    </style>
</head>
<body>
    <div class="invoice-container">
        <!-- Header -->
        <div class="header">
            <?php if (file_exists(getSetting('hospital_logo', 'assets/images/logo.png'))): ?>
                <img src="<?php echo htmlspecialchars(getSetting('hospital_logo', 'assets/images/logo.png')); ?>" 
                     alt="<?php echo htmlspecialchars(getSetting('hospital_name', 'ENT Hospital')); ?>">
            <?php endif; ?>
            <h1><?php echo strtoupper(getSetting('hospital_name', 'ENT Hospital')); ?></h1>
            <div class="address"><?php echo strtoupper(getSetting('hospital_address', '')); ?></div>
            <div class="contact">
                <?php echo getSetting('hospital_phone', ''); ?>
                <?php if (getSetting('hospital_email')): ?>
                    | <?php echo getSetting('hospital_email', ''); ?>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Patient Information -->
        <div class="patient-info">
            <div class="patient-left">
                <div class="patient-info-row">
                    <div class="patient-info-label">Name</div>
                    <div class="patient-info-value"><?php echo strtoupper($invoice['patient_name']); ?></div>
                </div>
                <div class="patient-info-row">
                    <div class="patient-info-label">Patient ID</div>
                    <div class="patient-info-value"><?php echo $invoice['patient_number']; ?></div>
                </div>
                <div class="patient-info-row">
                    <div class="patient-info-label">Phone</div>
                    <div class="patient-info-value"><?php echo $invoice['phone_primary'] ?? 'N/A'; ?></div>
                </div>
            </div>
            <div class="patient-right">
                <div class="patient-info-row">
                    <div class="patient-info-label">Receipt No.</div>
                    <div class="patient-info-value"><?php echo $receipt_number; ?></div>
                </div>
                <div class="patient-info-row">
                    <div class="patient-info-label">Payment Date</div>
                    <div class="patient-info-value"><?php echo date('d/m/Y', strtotime($payment_date)); ?></div>
                </div>
                <div class="patient-info-row">
                    <div class="patient-info-label">Time</div>
                    <div class="patient-info-value"><?php echo date('H:i', strtotime($payment_date)); ?></div>
                </div>
            </div>
        </div>
        
        <!-- Invoice Details with Service Breakdown -->
        <div class="invoice-details">
            <div class="invoice-header">PAYMENT RECEIPT - <?php echo $payment_mode; ?></div>
            <table class="invoice-table">
                <thead>
                    <tr>
                        <th style="width: 8%;">No</th>
                        <th style="width: 50%;">Description</th>
                        <th style="width: 8%;">Qty</th>
                        <th style="width: 17%;">Unit Price</th>
                        <th style="width: 17%;">Amount</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $row_num = 1;
                    $items_total = 0;
                    if ($items_result->num_rows > 0):
                        while($item = $items_result->fetch_assoc()): 
                            $line_total = floatval($item['total_price'] ?? ($item['line_total'] ?? ($item['unit_price'] * $item['quantity'])));
                            $items_total += $line_total;
                    ?>
                    <tr class="service-breakdown-row">
                        <td><?php echo $row_num++; ?></td>
                        <td>
                            <?php echo strtoupper($item['description'] ?? $item['service_name'] ?? 'Service'); ?>
                            <?php if ($item['service_code']): ?>
                                <br><small style="font-size: 7px; color: #666;">Code: <?php echo $item['service_code']; ?></small>
                            <?php endif; ?>
                        </td>
                        <td style="text-align: center;"><?php echo number_format($item['quantity'], 2); ?></td>
                        <td class="amount-column"><?php echo number_format($item['unit_price'], 2); ?></td>
                        <td class="amount-column"><?php echo number_format($line_total, 2); ?></td>
                    </tr>
                    <?php 
                        endwhile;
                    else:
                    ?>
                    <tr>
                        <td>1</td>
                        <td>GENERAL PAYMENT</td>
                        <td style="text-align: center;">1</td>
                        <td class="amount-column"><?php echo number_format($total_amount, 2); ?></td>
                        <td class="amount-column"><?php echo number_format($total_amount, 2); ?></td>
                    </tr>
                    <?php endif; ?>
                    <tr class="total-row">
                        <td colspan="4"><strong>TOTAL</strong></td>
                        <td class="amount-column"><strong><?php echo number_format($total_amount, 2); ?></strong></td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <!-- Payment Summary -->
        <div class="payment-summary">
            <div class="payment-box">
                <h4>INVOICE SUMMARY</h4>
                <div class="payment-row">
                    <span>Sub Total</span>
                    <span><?php echo number_format($invoice['subtotal'] ?? $items_total, 2); ?></span>
                </div>
                <div class="payment-row">
                    <span>Tax</span>
                    <span><?php echo number_format($invoice['tax_amount'] ?? 0, 2); ?></span>
                </div>
                <div class="payment-row">
                    <span>Discount</span>
                    <span><?php echo number_format($invoice['discount_amount'] ?? 0, 2); ?></span>
                </div>
                <div class="payment-row highlight">
                    <span>Net Amount</span>
                    <span><?php echo number_format($total_amount, 2); ?></span>
                </div>
            </div>
            
            <div class="payment-box">
                <h4>PAYMENT DETAILS</h4>
                <div class="payment-row">
                    <span>Amount Paid</span>
                    <span><?php echo number_format($total_paid, 2); ?></span>
                </div>
                <div class="payment-row">
                    <span>Payment Mode</span>
                    <span><?php echo $payment_mode; ?></span>
                </div>
                <div class="payment-row">
                    <span>Date</span>
                    <span><?php echo date('d/m/Y', strtotime($payment_date)); ?></span>
                </div>
                <div class="payment-row highlight">
                    <span>Balance</span>
                    <span><?php echo number_format($balance_due, 2); ?></span>
                </div>
            </div>
            
            <div class="payment-box">
                <h4>RECEIPT INFORMATION</h4>
                <div class="payment-row">
                    <span>Receipt No.</span>
                    <span><?php echo $receipt_number; ?></span>
                </div>
                <div class="payment-row">
                    <span>Served By</span>
                    <span><?php echo $staff_name; ?></span>
                </div>
                <div class="payment-row">
                    <span>Time</span>
                    <span><?php echo date('H:i', strtotime($payment_date)); ?></span>
                </div>
                <div class="payment-row highlight">
                    <span>Status</span>
                    <span><?php echo $balance_due > 0 ? 'PARTIAL' : 'PAID'; ?></span>
                </div>
            </div>
        </div>
        
        <!-- Amount in Words -->
        <div class="amount-words">
            Amount in Words: <strong><?php echo $amount_words; ?></strong>
        </div>
        
        <!-- Verification Section -->
        <div class="verification-section">
            <div class="barcode-container">
                <div style="font-size: 8px; font-weight: bold; margin-bottom: 5px;">Receipt Barcode</div>
                <svg id="receipt-barcode"></svg>
                <div class="barcode-info" id="barcode-data"></div>
            </div>
            
            <div class="qr-container">
                <div style="font-size: 8px; font-weight: bold; margin-bottom: 5px;">E-TIMS QR Code</div>
                <?php if (!empty($invoice['etims_qr_code'])): ?>
                    <?php 
                    // Check if QR code is a URL or base64 data
                    if (filter_var($invoice['etims_qr_code'], FILTER_VALIDATE_URL)) {
                        echo '<img src="' . htmlspecialchars($invoice['etims_qr_code']) . '" alt="E-TIMS QR Code" id="etims-qr-image" style="max-width: 100px; max-height: 100px; display: block; margin: 0 auto;">';
                    } elseif (strpos($invoice['etims_qr_code'], 'data:image') === 0) {
                        echo '<img src="' . htmlspecialchars($invoice['etims_qr_code']) . '" alt="E-TIMS QR Code" id="etims-qr-image" style="max-width: 100px; max-height: 100px; display: block; margin: 0 auto;">';
                    } else {
                        echo '<img src="data:image/png;base64,' . htmlspecialchars($invoice['etims_qr_code']) . '" alt="E-TIMS QR Code" id="etims-qr-image" style="max-width: 100px; max-height: 100px; display: block; margin: 0 auto;">';
                    }
                    ?>
                    <div style="font-size: 7px; margin-top: 3px; color: #666; font-weight: bold;">
                        <?php if ($invoice['etims_invoice_number']): ?>
                            E-TIMS Invoice: <?php echo htmlspecialchars($invoice['etims_invoice_number']); ?>
                        <?php endif; ?>
                        <?php if ($invoice['etims_cu_serial_number']): ?>
                            <br>CU Serial: <?php echo htmlspecialchars($invoice['etims_cu_serial_number']); ?>
                        <?php endif; ?>
                        <?php if ($invoice['etims_receipt_signature']): ?>
                            <br>Signature: <?php echo substr(htmlspecialchars($invoice['etims_receipt_signature']), 0, 20); ?>...
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <div style="padding: 20px; text-align: center; border: 1px dashed #ccc; background: #f9f9f9;">
                        <div style="font-size: 7px; color: #999; margin-bottom: 5px;">E-TIMS QR Code</div>
                        <div style="font-size: 7px; color: #666;">Not yet submitted to eTIMS</div>
                        <div style="font-size: 6px; color: #999; margin-top: 5px;">Please submit invoice to eTIMS first</div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Signature Section -->
        <div class="signature-section">
            <div class="signature-box">
                <div class="signature-line"></div>
                <div>Patient Signature</div>
                <div style="font-size: 7px; margin-top: 2px;">
                    <?php echo strtoupper($invoice['patient_name']); ?>
                </div>
            </div>
            <div class="signature-box">
                <div class="signature-line"></div>
                <div>Authorized Signature</div>
                <div style="font-size: 7px; margin-top: 2px; font-weight: bold;">
                    <?php echo strtoupper($staff_name); ?>
                </div>
            </div>
        </div>
        
        <!-- Footer -->
        <div class="footer">
            <p><strong>Thank you for choosing <?php echo getSetting('hospital_name', 'ENT Hospital'); ?></strong></p>
            <p>For inquiries, please contact us at <?php echo getSetting('hospital_email', ''); ?> or <?php echo getSetting('hospital_phone', ''); ?></p>
            <p style="margin-top: 6px; font-size: 6px;">
                This receipt is system generated. For any billing queries, please visit our front desk.
            </p>
        </div>
    </div>
    
    <!-- Print Button -->
    <div class="no-print" style="text-align: center; margin: 10px;">
        <button onclick="window.print()" style="padding: 10px 20px; background: #0066cc; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px;">
            Print Receipt
        </button>
        <button onclick="window.close()" style="padding: 10px 20px; background: #6c757d; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; margin-left: 10px;">
            Close
        </button>
    </div>
    
    <!-- JavaScript -->
    <script>
        function generateBothCodes() {
            try {
                const receiptNo = "<?php echo $receipt_number; ?>";
                const date = "<?php echo date('Ymd', strtotime($payment_date)); ?>";
                const amount = "<?php echo number_format($total_paid, 2, '.', ''); ?>";
                
                JsBarcode("#receipt-barcode", receiptNo + "|" + date + "|" + amount, {
                    format: "CODE128",
                    width: 1.5,
                    height: 40,
                    displayValue: true,
                    fontSize: 10
                });
                
                // QR Code - eTIMS QR is displayed from PHP, no need to generate fallback
                // The eTIMS QR code should always be present for invoices
                
                console.log('Barcode generated successfully');
                
            } catch (error) {
                console.error('Error:', error);
            }
        }
        
        window.addEventListener('load', function() {
            setTimeout(function() {
                generateBothCodes();
                setTimeout(window.print, 1000);
            }, 300);
        });
    </script>
</body>
</html>
