<?php
/**
 * طباعة الفاتورة مع QR للتحقق
 */
use App\Core\Tenant;
use App\Core\PaymentGateway;

$invoiceId = (int)($_GET['invoice_id'] ?? 0);
$tenantId = Tenant::id();

if ($invoiceId <= 0) {
    echo 'فاتورة غير معروفة';
    return;
}

$invoice = null;
$order = null;
try {
    $tenantAnd = '';
    try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $tenantAnd = ' AND o.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
    $stmt = $db->prepare(
        'SELECT i.*, o.order_number, o.order_date, p.full_name AS patient_name, p.phone
         FROM invoices i
         JOIN lab_orders o ON o.id = i.order_id
         JOIN patients p ON p.id = o.patient_id
         WHERE i.id = ?' . $tenantAnd
    );
    $stmt->execute([$invoiceId]);
    $invoice = $stmt->fetch();
} catch (Throwable $e) {}

if (!$invoice) {
    echo 'الفاتورة غير موجودة';
    return;
}

$labName = 'مختبر تحاليل';
$labPhone = '';
try {
    $stmt = $db->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('lab_name','lab_phone')");
    $stmt->execute();
    foreach ($stmt->fetchAll() as $r) {
        if ($r['setting_key'] === 'lab_name') $labName = $r['setting_value'] ?: $labName;
        if ($r['setting_key'] === 'lab_phone') $labPhone = $r['setting_value'] ?? '';
    }
} catch (Throwable $e) {}
try {
    $stmt = $db->prepare('SELECT name FROM tenants WHERE id = ?');
    $stmt->execute([$tenantId]);
    if (($t = $stmt->fetch()) && !empty($t['name'])) $labName = $t['name'];
} catch (Throwable $e) {}

$hasCurrency = isset($invoice['currency']) && $invoice['currency'];
$currSym = ($hasCurrency && $invoice['currency'] === 'USD') ? '$' : 'د.ع';
$baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
$scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? ''));
if ($scriptDir === '/') $scriptDir = '';
$verifyUrl = $baseUrl . $scriptDir . '/verify_invoice.php?code=' . urlencode($invoice['invoice_number']);
$printSettings = [];
try {
    $hasTenant = false;
    try { $db->query('SELECT tenant_id FROM settings LIMIT 1'); $hasTenant = true; } catch (Throwable $e) {}
    $st = $hasTenant ? $db->prepare('SELECT setting_key, setting_value FROM settings WHERE tenant_id = ? AND setting_key LIKE "print_%"') : $db->query('SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE "print_%"');
    if ($hasTenant) $st->execute([$tenantId]);
    if ($st) foreach ($st->fetchAll() as $r) { $printSettings[$r['setting_key']] = $r['setting_value'] ?? ''; }
} catch (Throwable $e) {}
$invoiceColor = $printSettings['print_invoice_color'] ?? '#0d9488';
$showInvoiceQr = ($printSettings['print_invoice_show_qr'] ?? '1') === '1';
$qrUrl = $showInvoiceQr ? 'https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=' . urlencode($verifyUrl) : '';
$invoiceFooter = trim($printSettings['print_invoice_footer'] ?? '');
$invoicePaper = $printSettings['print_invoice_paper'] ?? 'A4';
$showInvoiceItems = ($printSettings['print_invoice_show_items'] ?? '1') === '1';
$payLabels = ['cash' => 'نقداً', 'card' => 'بطاقة', 'transfer' => 'تحويل', 'mixed' => 'مختلط'];
$payMethod = $payLabels[$invoice['payment_method'] ?? ''] ?? ($invoice['payment_method'] ?? '-');
$remainingAmount = max(0, (float)$invoice['net_amount'] - (float)$invoice['paid_amount']);
$pg = new PaymentGateway($db, (int)$tenantId);
$showPayButton = $remainingAmount > 0 && $pg->isEnabled();
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>فاتورة <?php echo htmlspecialchars($invoice['invoice_number'], ENT_QUOTES, 'UTF-8'); ?></title>
    <link rel="stylesheet" href="styles.css">
    <style>
        <?php $invoiceOrientation = $printSettings['print_invoice_orientation'] ?? 'portrait'; ?>
        @page { size: <?php echo htmlspecialchars($invoicePaper, ENT_QUOTES, 'UTF-8'); ?> <?php echo htmlspecialchars($invoiceOrientation, ENT_QUOTES, 'UTF-8'); ?>; }
        .invoice-container { max-width: 600px; margin: 0 auto; padding: 24px; }
        .invoice-header { border-bottom: 2px solid <?php echo htmlspecialchars($invoiceColor, ENT_QUOTES, 'UTF-8'); ?>; padding-bottom: 16px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 16px; }
        .invoice-title { font-size: 1.5rem; color: <?php echo htmlspecialchars($invoiceColor, ENT_QUOTES, 'UTF-8'); ?>; }
        .invoice-table { width: 100%; border-collapse: collapse; margin: 20px 0; }
        .invoice-table th, .invoice-table td { padding: 10px 12px; text-align: right; border-bottom: 1px solid #e2e8f0; }
        .invoice-table th { background: #f8fafc; font-weight: 600; }
        .invoice-qr { text-align: center; margin-top: 24px; }
        @media print { .no-print { display: none !important; } }
    </style>
</head>
<body class="print-page">
    <div class="no-print" style="margin-bottom:16px; display:flex; gap:8px; flex-wrap:wrap;">
        <button type="button" onclick="window.print()" class="btn-primary">طباعة</button>
        <button type="button" id="btnPdf" class="btn-secondary">تحميل PDF</button>
        <?php if ($showPayButton): ?><a href="index.php?page=pay&invoice_id=<?php echo (int)$invoice['id']; ?>" class="btn-primary" style="background:linear-gradient(135deg,#059669,#047857);">💳 دفع أونلاين</a><?php endif; ?>
        <a href="index.php?page=billing" class="btn-secondary">رجوع</a>
    </div>
    <div class="invoice-container report-container">
        <div class="invoice-header">
            <div>
                <h1 class="invoice-title">فاتورة</h1>
                <div><strong>رقم الفاتورة:</strong> <?php echo htmlspecialchars($invoice['invoice_number'], ENT_QUOTES, 'UTF-8'); ?></div>
                <div><strong>المختبر:</strong> <?php echo htmlspecialchars($labName, ENT_QUOTES, 'UTF-8'); ?></div>
                <?php if ($labPhone): ?><div><strong>الهاتف:</strong> <?php echo htmlspecialchars($labPhone, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
            </div>
            <?php if ($showInvoiceQr && $qrUrl): ?>
            <div class="invoice-qr">
                <img src="<?php echo htmlspecialchars($qrUrl, ENT_QUOTES, 'UTF-8'); ?>" alt="QR" width="80" height="80" style="border:1px solid #ddd;">
                <div style="font-size:0.7rem; margin-top:4px;">التحقق من صحة الفاتورة</div>
            </div>
            <?php endif; ?>
        </div>
        <p><strong>رقم الطلب:</strong> <?php echo htmlspecialchars($invoice['order_number'], ENT_QUOTES, 'UTF-8'); ?></p>
        <p><strong>المريض:</strong> <?php echo htmlspecialchars($invoice['patient_name'], ENT_QUOTES, 'UTF-8'); ?></p>
        <p><strong>التاريخ:</strong> <?php echo htmlspecialchars($invoice['issue_date'], ENT_QUOTES, 'UTF-8'); ?></p>
        <?php if ($showInvoiceItems): ?>
        <table class="invoice-table table">
            <thead>
                <tr><th>البند</th><th>المبلغ (<?php echo $currSym; ?>)</th></tr>
            </thead>
            <tbody>
                <tr><td>الإجمالي</td><td><?php echo number_format((float)$invoice['total_amount'], 2); ?></td></tr>
                <tr><td>الخصم</td><td><?php echo number_format((float)$invoice['discount_amount'], 2); ?></td></tr>
                <tr><td>الصافي</td><td><strong><?php echo number_format((float)$invoice['net_amount'], 2); ?></strong></td></tr>
                <tr><td>المدفوع</td><td><?php echo number_format((float)$invoice['paid_amount'], 2); ?></td></tr>
                <tr><td>المتبقي</td><td><?php echo number_format(max(0, (float)$invoice['net_amount'] - (float)$invoice['paid_amount']), 2); ?></td></tr>
            </tbody>
        </table>
        <p><strong>طريقة الدفع:</strong> <?php echo htmlspecialchars($payMethod, ENT_QUOTES, 'UTF-8'); ?></p>
        <?php else: ?>
        <div style="margin:20px 0;padding:16px;background:#f8fafc;border-radius:8px;">
            <p style="margin:0;font-size:1.1em;"><strong>المبلغ الإجمالي:</strong> <?php echo number_format((float)$invoice['net_amount'], 2); ?> <?php echo $currSym; ?></p>
            <?php if ((float)$invoice['paid_amount'] > 0): ?><p style="margin:8px 0 0;"><strong>المدفوع:</strong> <?php echo number_format((float)$invoice['paid_amount'], 2); ?> <?php echo $currSym; ?></p><?php endif; ?>
            <?php if ($remainingAmount > 0): ?><p style="margin:8px 0 0;color:#dc2626;"><strong>المتبقي:</strong> <?php echo number_format($remainingAmount, 2); ?> <?php echo $currSym; ?></p><?php endif; ?>
        </div>
        <?php endif; ?>
        <p style="margin-top:20px;font-size:0.85rem;color:#64748b;">تاريخ الطباعة: <?php echo date('Y-m-d H:i:s'); ?></p>
        <?php if ($invoiceFooter): ?><p style="margin-top:12px;font-size:0.85rem;"><?php echo htmlspecialchars($invoiceFooter, ENT_QUOTES, 'UTF-8'); ?></p><?php endif; ?>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
    <script>
    document.getElementById('btnPdf') && document.getElementById('btnPdf').addEventListener('click', function(){
        var el = document.querySelector('.invoice-container');
        html2pdf().set({ margin: 10, filename: 'فاتورة_<?php echo preg_replace('/[^a-z0-9_-]/i', '_', $invoice['invoice_number']); ?>.pdf', image: { type: 'jpeg', quality: 0.98 }, html2canvas: { scale: 2 }, jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' } }).from(el).save();
    });
    </script>
</body>
</html>
