<?php

use App\Core\Auth;
use App\Core\Tenant;
use App\Core\PaymentGateway;

$tenantId = Tenant::id();
$pg = new PaymentGateway($db, (int)$tenantId);
$action = $_GET['action'] ?? 'index';

if (!($auth instanceof Auth) || !$auth->can('billing.view')) {
    http_response_code(403);
    echo 'غير مسموح بالوصول إلى هذه الصفحة';
    return;
}

if ($action === 'send_debt_reminder' && $_SERVER['REQUEST_METHOD'] === 'POST' && ($auth->can('billing.view') || $auth->can('billing.create'))) {
    $remindPatientId = (int)($_POST['patient_id'] ?? 0);
    if ($remindPatientId > 0) {
        try {
            $tAnd = '';
            try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $tAnd = ' AND o.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
            $stmt = $db->prepare('SELECT p.id, p.full_name, p.phone, SUM(i.net_amount - i.paid_amount) AS debt, GROUP_CONCAT(i.invoice_number) AS inv_nums FROM invoices i JOIN lab_orders o ON o.id = i.order_id JOIN patients p ON p.id = o.patient_id WHERE (i.net_amount - i.paid_amount) > 0 AND p.id = ?' . $tAnd . ' GROUP BY p.id, p.full_name, p.phone');
            $stmt->execute([$remindPatientId]);
            $row = $stmt->fetch();
            if ($row && (float)$row['debt'] > 0) {
                $whatsapp = new \App\Core\WhatsApp($db, $config['whatsapp'] ?? []);
                if ($whatsapp->sendDebtReminder((int)$row['id'], (float)$row['debt'], $row['inv_nums'] ?? '')) {
                    $_SESSION['billing_success'] = 'تم إرسال تذكير واتساب للمريض.';
                } else {
                    $_SESSION['billing_error'] = 'فشل الإرسال. تأكد من إعداد واتساب.';
                }
            }
        } catch (Throwable $e) {
            $_SESSION['billing_error'] = 'حدث خطأ: ' . $e->getMessage();
        }
    }
    header('Location: index.php?page=billing');
    exit;
}

if ($action === 'add_payment' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $invoiceId = (int)($_POST['invoice_id'] ?? 0);
    $amount = (float)($_POST['amount'] ?? 0);
    if ($invoiceId > 0 && $amount > 0) {
        try {
            $tenantCheck = '';
            try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $tenantCheck = ' JOIN lab_orders o ON o.id = i.order_id AND o.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
            $stmt = $db->prepare('SELECT i.id, i.order_id, i.invoice_number, i.net_amount, i.paid_amount FROM invoices i' . $tenantCheck . ' WHERE i.id = ?');
            $stmt->execute([$invoiceId]);
            $inv = $stmt->fetch();
            if ($inv) {
                $newPaid = (float)$inv['paid_amount'] + $amount;
                $net = (float)$inv['net_amount'];
                if ($newPaid > $net) $newPaid = $net;
                $stmt = $db->prepare('UPDATE invoices SET paid_amount = ? WHERE id = ?');
                $stmt->execute([$newPaid, $invoiceId]);
                $status = $newPaid >= $net ? 'paid' : 'partial';
                $stmt = $db->prepare('UPDATE lab_orders SET payment_status = ? WHERE id = ?');
                $stmt->execute([$status, $inv['order_id']]);
                if (isset($auditLog)) {
                    $auditLog->log('payment_added', 'invoice', $invoiceId, json_encode(['paid_before' => $inv['paid_amount']], JSON_UNESCAPED_UNICODE), json_encode(['amount' => $amount, 'paid_after' => $newPaid, 'status' => $status], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
                }
                header('Location: index.php?page=billing&paid=1');
                exit;
            }
        } catch (Throwable $e) {}
    }
}

$billingCurrency = 'IQD';
try {
    $stmt = $db->prepare("SELECT setting_value FROM settings WHERE tenant_id = ? AND setting_key = 'currency' LIMIT 1");
    $stmt->execute([$tenantId]);
    if (($row = $stmt->fetch()) && !empty(trim($row['setting_value'] ?? ''))) {
        $cv = strtoupper(trim($row['setting_value']));
        if (in_array($cv, ['USD', 'IQD'], true)) $billingCurrency = $cv;
    }
} catch (Throwable $e) {}

if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!($auth instanceof Auth) || !$auth->can('billing.create')) {
        http_response_code(403);
        echo 'غير مسموح بإنشاء الفواتير';
        return;
    }
    $orderId = (int)($_POST['order_id'] ?? 0);
    $paidAmount = (float)(str_replace(',', '.', $_POST['paid_amount'] ?? '0'));
    $paymentMethod = $_POST['payment_method'] ?? null;
    $discountAmount = (float)(str_replace(',', '.', $_POST['discount_amount'] ?? '0'));
    $manualTotal = trim($_POST['manual_total'] ?? '') !== '' ? (float)str_replace(',', '.', $_POST['manual_total']) : null;
    $invoiceCurrency = strtoupper(trim($_POST['invoice_currency'] ?? 'IQD'));
    if (!in_array($invoiceCurrency, ['USD', 'IQD'], true)) $invoiceCurrency = 'IQD';
    $loyaltyRedeem = (float)(str_replace(',', '.', $_POST['loyalty_redeem'] ?? '0'));

    if ($orderId > 0) {
        $invError = '';
        try {
            $tenantJoin = '';
            try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $tenantJoin = ' JOIN lab_orders o ON o.id = i.order_id AND o.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
            $stmt = $db->prepare('SELECT i.id FROM invoices i' . $tenantJoin . ' WHERE i.order_id = ? LIMIT 1');
            $stmt->execute([$orderId]);
            if ($stmt->fetch()) {
                $invError = 'يوجد فاتورة لهذا الطلب مسبقاً.';
            }
        } catch (Throwable $e) {}
        if ($invError === '') {
        try {
            $db->beginTransaction();

            $tenantClause = '';
            try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $tenantClause = ' AND tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
            $stmt = $db->prepare(
                'SELECT id, order_number, patient_id, total_amount, discount_amount, net_amount
                 FROM lab_orders
                 WHERE id = :id' . $tenantClause . '
                 FOR UPDATE'
            );
            $stmt->execute(['id' => $orderId]);
            $order = $stmt->fetch();

            if ($order) {
                $orderTotal = (float)$order['total_amount'];
                $total = $manualTotal !== null && $manualTotal >= 0 ? $manualTotal : $orderTotal;
                if ($orderTotal <= 0 && $total <= 0) {
                    $invError = 'أدخل إجمالي الفاتورة يدوياً.';
                    $db->rollBack();
                } else {
                $patientId = (int)($order['patient_id'] ?? 0);
                $existingDiscount = (float)$order['discount_amount'];
                $totalDiscount = $existingDiscount + $discountAmount;
                $loyaltyDeduction = 0;
                if ($patientId > 0 && $loyaltyRedeem > 0) {
                    try {
                        $db->query('SELECT loyalty_points FROM patients LIMIT 1');
                        $pStmt = $db->prepare('SELECT loyalty_points FROM patients WHERE id = ?');
                        $pStmt->execute([$patientId]);
                        $pRow = $pStmt->fetch();
                        $availPoints = $pRow ? (float)($pRow['loyalty_points'] ?? 0) : 0;
                        $pointsValue = 0.1;
                        try {
                            $sv = $db->query("SELECT setting_value FROM settings WHERE setting_key = 'loyalty_point_value' LIMIT 1")->fetch();
                            if ($sv && ($v = trim($sv['setting_value'] ?? '')) !== '') $pointsValue = (float)$v;
                        } catch (Throwable $e) {}
                        $maxRedeem = $availPoints * $pointsValue;
                        $loyaltyDeduction = min($loyaltyRedeem, $maxRedeem, $total - $totalDiscount);
                        if ($loyaltyDeduction > 0) {
                            $pointsUsed = ceil($loyaltyDeduction / $pointsValue);
                            $totalDiscount += $loyaltyDeduction;
                            $db->prepare('UPDATE patients SET loyalty_points = loyalty_points - ? WHERE id = ?')->execute([$pointsUsed, $patientId]);
                            $db->prepare('INSERT INTO loyalty_transactions (patient_id, order_id, points, type, note) VALUES (?, ?, ?, ?, ?)')->execute([$patientId, $orderId, $pointsUsed, 'redeem', 'خصم من الفاتورة']);
                        }
                    } catch (Throwable $e) {}
                }

                if ($totalDiscount < 0) $totalDiscount = 0;
                if ($totalDiscount > $total) $totalDiscount = $total;

                $net = $total - $totalDiscount;
                if ($paidAmount > $net) {
                    $paidAmount = $net;
                }

                $invoiceNumber = 'I' . time();

                $hasCurrency = false;
                try { $db->query('SELECT currency FROM invoices LIMIT 1'); $hasCurrency = true; } catch (Throwable $e) {}
                if ($hasCurrency) {
                    $stmt = $db->prepare(
                        'INSERT INTO invoices (invoice_number, order_id, issue_date, total_amount, discount_amount, net_amount, paid_amount, payment_method, currency)
                         VALUES (:num, :order_id, NOW(), :total, :discount, :net, :paid, :method, :curr)'
                    );
                    $stmt->execute([
                        'num' => $invoiceNumber, 'order_id' => $orderId, 'total' => $total, 'discount' => $totalDiscount,
                        'net' => $net, 'paid' => $paidAmount, 'method' => $paymentMethod ?: null, 'curr' => $invoiceCurrency
                    ]);
                } else {
                    $stmt = $db->prepare(
                        'INSERT INTO invoices (invoice_number, order_id, issue_date, total_amount, discount_amount, net_amount, paid_amount, payment_method)
                         VALUES (:num, :order_id, NOW(), :total, :discount, :net, :paid, :method)'
                    );
                    $stmt->execute([
                        'num' => $invoiceNumber, 'order_id' => $orderId, 'total' => $total, 'discount' => $totalDiscount,
                        'net' => $net, 'paid' => $paidAmount, 'method' => $paymentMethod ?: null
                    ]);
                }

                $status = 'unpaid';
                if ($paidAmount >= $net) {
                    $status = 'paid';
                } elseif ($paidAmount > 0) {
                    $status = 'partial';
                }

                $stmt = $db->prepare(
                    'UPDATE lab_orders
                     SET total_amount = :total, discount_amount = :discount, net_amount = :net, payment_status = :status
                     WHERE id = :id'
                );
                $stmt->execute([
                    'total' => $total,
                    'discount' => $totalDiscount,
                    'net' => $net,
                    'status' => $status,
                    'id' => $orderId
                ]);

                // ربط الفاتورة بالحساب المالي للمريض
                try {
                    require_once __DIR__ . '/../src/Core/AccountManager.php';
                    $accountManager = new \App\Core\AccountManager($db, $tenantId);
                    $conversionRate = 1300;
                    if ($invoiceCurrency === 'USD') {
                        $totalAmountIQD = $net * $conversionRate;
                        $paidAmountIQD = $paidAmount * $conversionRate;
                    } else {
                        $totalAmountIQD = $net;
                        $paidAmountIQD = $paidAmount;
                    }
                    $accountManager->linkInvoiceToAccount(
                        (int)$db->lastInsertId(), 
                        $orderId, 
                        $patientId, 
                        $totalAmountIQD, 
                        $paidAmountIQD, 
                        $invoiceNumber, 
                        'IQD'
                    );
                } catch (\Throwable $e) {
                    error_log("Failed to link invoice to account: " . $e->getMessage());
                }

                $db->commit();
                if (isset($auditLog)) {
                    $auditLog->log(
                        'invoice_created',
                        'invoice',
                        (int)$db->lastInsertId(),
                        null,
                        json_encode([
                            'order_id' => $orderId,
                            'invoice_number' => $invoiceNumber,
                            'total' => $total,
                            'net' => $net,
                            'paid' => $paidAmount,
                            'payment_status' => $status
                        ], JSON_UNESCAPED_UNICODE),
                        $_SESSION['user_id'] ?? null
                    );
                }
                }
            } else {
                $db->rollBack();
                $invError = 'الطلب غير موجود.';
            }
        } catch (Throwable $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            $invError = 'حدث خطأ عند الحفظ: ' . $e->getMessage();
        }
        }
        if ($invError !== '') {
            $_SESSION['billing_error'] = $invError;
            header('Location: index.php?page=billing&action=create&order_id=' . $orderId);
            exit;
        }
                if ($patientId > 0 && $paidAmount > 0 && $status === 'paid') {
                    try {
                        $db->query('SELECT loyalty_points FROM patients LIMIT 1');
                        $earnRate = 0.1;
                        try {
                            $er = $db->query("SELECT setting_value FROM settings WHERE setting_key = 'loyalty_earn_rate' LIMIT 1")->fetch();
                            if ($er && ($v = trim($er['setting_value'] ?? '')) !== '') $earnRate = (float)$v;
                        } catch (Throwable $e) {}
                        $pointsEarned = floor($paidAmount * $earnRate);
                        if ($pointsEarned > 0) {
                            $db->prepare('UPDATE patients SET loyalty_points = loyalty_points + ? WHERE id = ?')->execute([$pointsEarned, $patientId]);
                            $db->prepare('INSERT INTO loyalty_transactions (patient_id, order_id, points, type, note) VALUES (?, ?, ?, ?, ?)')->execute([$patientId, $orderId, $pointsEarned, 'earn', 'نقاط من الدفع']);
                        }
                    } catch (Throwable $e) {}
                }
                $_SESSION['billing_success'] = 'تم حفظ الفاتورة بنجاح.';
                $_SESSION['last_invoice_currency'] = $invoiceCurrency;
    }

    header('Location: index.php?page=billing');
    exit;
}

if ($action === 'create') {
    $orderId = (int)($_GET['order_id'] ?? 0);
    $order = null;

    if ($orderId > 0) {
        try {
            $tenantClause = '';
            try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $tenantClause = ' AND o.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
            $stmt = $db->prepare(
                'SELECT o.id, o.order_number, o.patient_id, o.total_amount, o.discount_amount, o.net_amount,
                        o.payment_status, p.full_name AS patient_name
                 FROM lab_orders o
                 JOIN patients p ON p.id = o.patient_id
                 WHERE o.id = :id' . $tenantClause
            );
            $stmt->execute(['id' => $orderId]);
            $order = $stmt->fetch();
            if ($order && ($order['patient_id'] ?? 0) > 0) {
                try {
                    $db->query('SELECT loyalty_points FROM patients LIMIT 1');
                    $lpStmt = $db->prepare('SELECT loyalty_points FROM patients WHERE id = ?');
                    $lpStmt->execute([$order['patient_id']]);
                    $lpRow = $lpStmt->fetch();
                    $order['loyalty_points'] = $lpRow ? ($lpRow['loyalty_points'] ?? 0) : 0;
                } catch (Throwable $e) { $order['loyalty_points'] = 0; }
            }
        } catch (Throwable $e) {
        }
    }

    if (!$order) {
        echo '<p>الطلب غير موجود</p>';
        return;
    }

    // إذا كان إجمالي الطلب صفراً، احسبه تلقائياً من مجموع مبالغ الفحوصات (order_items)
    $orderTotalFromItems = 0;
    try {
        $sumStmt = $db->prepare('SELECT COALESCE(SUM(price), 0) AS total FROM order_items WHERE order_id = ?');
        $sumStmt->execute([$orderId]);
        $row = $sumStmt->fetch();
        if ($row) {
            $orderTotalFromItems = (float)$row['total'];
        }
    } catch (Throwable $e) {}
    if ($orderTotalFromItems > 0 && (float)$order['total_amount'] <= 0) {
        $order['total_amount'] = $orderTotalFromItems;
        $order['net_amount'] = $orderTotalFromItems - (float)$order['discount_amount'];
        if ($order['net_amount'] < 0) {
            $order['net_amount'] = 0;
        }
        try {
            $upd = $db->prepare('UPDATE lab_orders SET total_amount = ?, net_amount = ? WHERE id = ?');
            $upd->execute([$order['total_amount'], $order['net_amount'], $orderId]);
        } catch (Throwable $e) {}
    }

    $remaining = (float)$order['net_amount'];
    $orderTotal = (float)$order['total_amount'];
    $preselectedCurrency = $_POST['invoice_currency'] ?? ($_SESSION['last_invoice_currency'] ?? $billingCurrency);
    if (!in_array($preselectedCurrency, ['USD', 'IQD'], true)) $preselectedCurrency = 'IQD';

    ?>
    <div class="page-header">
        <h1>إنشاء فاتورة للطلب</h1>
    </div>
    <?php if (!empty($_SESSION['billing_error'])): ?>
    <div class="alert alert-danger"><?php echo htmlspecialchars($_SESSION['billing_error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['billing_error']); ?></div>
    <?php endif; ?>
    <div class="card">
        <p>رقم الطلب: <?php echo htmlspecialchars($order['order_number'], ENT_QUOTES, 'UTF-8'); ?></p>
        <p>المريض: <?php echo htmlspecialchars($order['patient_name'], ENT_QUOTES, 'UTF-8'); ?></p>
        <p>الإجمالي: <?php echo number_format((float)$order['total_amount'], 2); ?></p>
        <p>الخصم الحالي: <?php echo number_format((float)$order['discount_amount'], 2); ?></p>
        <p>الصافي: <?php echo number_format((float)$order['net_amount'], 2); ?></p>
        <?php
        $patientPoints = 0;
        $pointValue = 0.1;
        if (isset($order['patient_id']) && $order['patient_id'] && isset($order['loyalty_points'])) {
            $patientPoints = (float)$order['loyalty_points'];
            try { $sv = $db->query("SELECT setting_value FROM settings WHERE setting_key = 'loyalty_point_value' LIMIT 1")->fetch(); if ($sv && trim($sv['setting_value'] ?? '') !== '') $pointValue = (float)$sv['setting_value']; } catch (Throwable $e) {}
        }
        $maxRedeemValue = $patientPoints * $pointValue;
        if ($patientPoints > 0): ?>
        <p>نقاط الولاء: <strong><?php echo number_format($patientPoints, 0); ?></strong> نقطة (قيمة تقديرية: <?php echo number_format($maxRedeemValue, 2); ?> <?php echo $sym; ?>)</p>
        <?php endif; ?>
    </div>
    <form method="post" action="index.php?page=billing&action=create" class="form-grid">
        <input type="hidden" name="order_id" value="<?php echo (int)$order['id']; ?>">
        <div>
            <label>نوع العملة</label>
            <select name="invoice_currency" id="inv_currency" onchange="var l=this.value==='IQD'?'د.ع':'$';document.querySelectorAll('.curr-sym').forEach(function(e){e.textContent=l;});">
                <option value="IQD" <?php echo $preselectedCurrency === 'IQD' ? 'selected' : ''; ?>>دينار عراقي (د.ع)</option>
                <option value="USD" <?php echo $preselectedCurrency === 'USD' ? 'selected' : ''; ?>>دولار أمريكي ($)</option>
            </select>
        </div>
        <?php $sym = $preselectedCurrency === 'IQD' ? 'د.ع' : '$'; ?>
        <?php if ($orderTotal <= 0): ?>
        <div>
            <label>إجمالي الفاتورة (<span class="curr-sym"><?php echo $sym; ?></span>)</label>
            <input type="number" step="0.01" min="0" name="manual_total" required placeholder="أدخل المبلغ يدوياً">
        </div>
        <?php endif; ?>
        <?php if ($patientPoints > 0): ?>
        <div>
            <label>استخدام نقاط الولاء (خصم حتى <?php echo number_format($maxRedeemValue, 2); ?> <?php echo $sym; ?>)</label>
            <input type="number" step="0.01" min="0" max="<?php echo $maxRedeemValue; ?>" name="loyalty_redeem" value="0" placeholder="0">
        </div>
        <?php endif; ?>
        <div>
            <label>خصم إضافي (<span class="curr-sym"><?php echo $sym; ?></span>)</label>
            <input type="number" step="0.01" min="0" name="discount_amount" value="0">
        </div>
        <div>
            <label>المبلغ المدفوع الآن (<span class="curr-sym"><?php echo $sym; ?></span>)</label>
            <input type="number" step="0.01" min="0" name="paid_amount" id="paid_amount" value="<?php echo $remaining > 0 ? htmlspecialchars(number_format($remaining, 2, '.', ''), ENT_QUOTES, 'UTF-8') : ''; ?>" placeholder="0" required>
            <div id="invoice_remaining" style="margin-top:6px;font-size:0.9rem;color:var(--text-secondary);"></div>
        </div>
        <div>
            <label>طريقة الدفع</label>
            <select name="payment_method">
                <option value="">غير محدد</option>
                <option value="cash">نقداً</option>
                <option value="card">بطاقة</option>
                <option value="transfer">تحويل</option>
                <option value="mixed">مختلط</option>
            </select>
        </div>
        <div class="full-width form-actions">
            <button type="submit">حفظ الفاتورة</button>
            <a href="index.php?page=orders" class="btn-secondary">رجوع إلى الطلبات</a>
        </div>
    </form>
    <script>
    (function(){
        var baseNet = <?php echo json_encode((float)$remaining); ?>;
        var manualInp = document.querySelector('input[name="manual_total"]');
        var discountInp = document.querySelector('input[name="discount_amount"]');
        var paidInp = document.getElementById('paid_amount');
        var remEl = document.getElementById('invoice_remaining');
        var sym = '<?php echo addslashes($sym); ?>';
        function calc(){
            var total = baseNet;
            if (manualInp && manualInp.value !== '') {
                total = parseFloat(manualInp.value) || 0;
            }
            var disc = parseFloat(discountInp ? discountInp.value : 0) || 0;
            total = Math.max(0, total - disc);
            var paid = parseFloat(paidInp.value) || 0;
            var rem = Math.max(0, total - paid);
            if (rem > 0) remEl.textContent = 'المتبقي بعد الدفع: ' + rem.toFixed(2) + ' ' + sym;
            else if (total > 0 && paid >= total) remEl.textContent = '✓ الدفع كامل';
            else remEl.textContent = '';
        }
        if (paidInp) { paidInp.addEventListener('input', calc); paidInp.addEventListener('change', calc); }
        if (manualInp) { manualInp.addEventListener('input', calc); manualInp.addEventListener('change', calc); }
        if (discountInp) { discountInp.addEventListener('input', calc); discountInp.addEventListener('change', calc); }
        calc();
    })();
    </script>
    <?php
    return;
}

$invoices = [];
$patientDebts = [];
$billingSearch = trim($_GET['q'] ?? '');
$billingExport = isset($_GET['export']) && $_GET['export'] === 'csv';
$billingPage = max(1, (int)($_GET['p'] ?? 1));
$billingPerPage = 25;
$billingOffset = ($billingPage - 1) * $billingPerPage;

$hasInvCurrency = false;
try { $db->query('SELECT currency FROM invoices LIMIT 1'); $hasInvCurrency = true; } catch (Throwable $e) {}
try {
    $baseSql = 'SELECT i.id, i.invoice_number, i.issue_date, i.total_amount, i.discount_amount, i.net_amount, i.paid_amount, i.payment_method' . ($hasInvCurrency ? ', i.currency' : '') . ',
                o.order_number, p.full_name AS patient_name
         FROM invoices i
         JOIN lab_orders o ON o.id = i.order_id
         JOIN patients p ON p.id = o.patient_id';
    $tenantAnd = '';
    try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $tenantAnd = ' AND o.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
    $where = ($billingSearch !== '' ? ' WHERE (o.order_number LIKE ? OR p.full_name LIKE ? OR i.invoice_number LIKE ?)' : '') . $tenantAnd;
    if ($billingSearch !== '') {
        $where = ' WHERE (o.order_number LIKE ? OR p.full_name LIKE ? OR i.invoice_number LIKE ?)' . $tenantAnd;
        $params = ['%' . $billingSearch . '%', '%' . $billingSearch . '%', '%' . $billingSearch . '%'];
    } else {
        $where = $tenantAnd ? (' WHERE ' . substr($tenantAnd, 5)) : '';
        $params = [];
    }
    $order = ' ORDER BY i.id DESC';
    if ($billingExport) {
        $stmt = $params ? $db->prepare($baseSql . $where . $order) : $db->query($baseSql . $where . $order);
        if ($params) $stmt->execute($params);
        $invoices = $stmt->fetchAll();
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="invoices_' . date('Y-m-d') . '.csv"');
        echo "\xEF\xBB\xBF";
        echo "رقم الفاتورة,رقم الطلب,المريض,التاريخ" . ($hasInvCurrency ? ",العملة" : "") . ",الإجمالي,الخصم,الصافي,المدفوع,طريقة الدفع\n";
        $payLabels = ['cash' => 'نقداً', 'card' => 'بطاقة', 'transfer' => 'تحويل', 'mixed' => 'مختلط'];
        foreach ($invoices as $r) {
            $pm = $payLabels[$r['payment_method'] ?? ''] ?? ($r['payment_method'] ?? '-');
            $curr = ($r['currency'] ?? 'IQD') === 'USD' ? '$' : 'د.ع';
            $line = [$r['invoice_number'], $r['order_number'], $r['patient_name'], $r['issue_date']];
            if ($hasInvCurrency) $line[] = $curr;
            $line = array_merge($line, [$r['total_amount'], $r['discount_amount'], $r['net_amount'], $r['paid_amount'], $pm]);
            $escaped = [];
            foreach ($line as $v) {
                $v = (string)$v;
                if (strpbrk($v, ",\"\n\r") !== false) $v = '"' . str_replace('"', '""', $v) . '"';
                $escaped[] = $v;
            }
            echo implode(',', $escaped) . "\n";
        }
        exit;
    }
    $limitSql = ' LIMIT ' . (int)$billingPerPage . ' OFFSET ' . (int)$billingOffset;
    $stmt = $params ? $db->prepare($baseSql . $where . $order . $limitSql) : $db->query($baseSql . $where . $order . $limitSql);
    if ($params) $stmt->execute($params);
    $invoices = $stmt->fetchAll();
    $cntSql = 'SELECT COUNT(*) FROM invoices i JOIN lab_orders o ON o.id = i.order_id JOIN patients p ON p.id = o.patient_id' . $where;
    $stmt = $params ? $db->prepare($cntSql) : $db->query($cntSql);
    if ($params) $stmt->execute($params);
    $billingTotal = (int)($stmt->fetchColumn() ?? 0);

    $debtSql = 'SELECT p.id, p.full_name, p.phone, SUM(i.net_amount - i.paid_amount) AS debt FROM invoices i JOIN lab_orders o ON o.id = i.order_id JOIN patients p ON p.id = o.patient_id WHERE (i.net_amount - i.paid_amount) > 0' . $tenantAnd . ' GROUP BY p.id, p.full_name, p.phone ORDER BY debt DESC LIMIT 50';
    $patientDebts = $db->query($debtSql)->fetchAll();
} catch (Throwable $e) {
    $billingTotal = 0;
}
$billingTotalPages = $billingTotal > 0 ? (int)ceil($billingTotal / $billingPerPage) : 1;
$payMethodLabels = ['cash' => 'نقداً', 'card' => 'بطاقة', 'transfer' => 'تحويل', 'mixed' => 'مختلط'];
$invoicesWithBalance = [];
try {
    $invBalSql = 'SELECT i.id, i.invoice_number, i.order_id, i.net_amount, i.paid_amount, o.order_number, p.full_name AS patient_name FROM invoices i JOIN lab_orders o ON o.id = i.order_id JOIN patients p ON p.id = o.patient_id WHERE (i.net_amount - i.paid_amount) > 0';
    try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $invBalSql .= ' AND o.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
    $invBalSql .= ' ORDER BY i.id DESC LIMIT 30';
    $invoicesWithBalance = $db->query($invBalSql)->fetchAll();
} catch (Throwable $e) {}
?>
<?php if (isset($_GET['paid'])): ?><div class="alert alert-success">تم تسجيل الدفعة بنجاح.</div><?php endif; ?>
<?php if (!empty($_SESSION['billing_success'])): ?><div class="alert alert-success"><?php echo htmlspecialchars($_SESSION['billing_success'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['billing_success']); ?></div><?php endif; ?>
<div class="page-header">
    <h1>الفواتير والمدفوعات</h1>
    <div class="actions-bar" style="flex-wrap:wrap;gap:12px;">
        <form method="get" style="display:inline-flex;gap:6px;">
            <input type="hidden" name="page" value="billing">
            <input type="search" name="q" placeholder="بحث برقم طلب أو مريض أو فاتورة..." value="<?php echo htmlspecialchars($billingSearch ?? '', ENT_QUOTES, 'UTF-8'); ?>" style="min-width:180px;">
            <button type="submit">بحث</button>
            <?php if (!empty($billingSearch)): ?><a href="index.php?page=billing" class="btn-secondary">إلغاء</a><?php endif; ?>
        </form>
        <a href="index.php?page=billing&export=csv<?php echo $billingSearch ? '&q=' . urlencode($billingSearch) : ''; ?>" class="btn-secondary">تصدير CSV</a>
    </div>
</div>
<?php if (!empty($patientDebts)): ?>
<div class="section-card" style="margin-bottom:24px;">
    <h3>ديون المرضى (<?php echo count($patientDebts); ?>)</h3>
    <div class="table-wrapper">
        <table class="table">
            <thead><tr><th>المريض</th><th>الهاتف</th><th>المبلغ المتبقي</th><th>إجراء</th></tr></thead>
            <tbody>
            <?php foreach ($patientDebts as $d): ?>
                <tr>
                    <td><?php echo htmlspecialchars($d['full_name'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($d['phone'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo number_format((float)$d['debt'], 2); ?></td>
                    <td>
                        <a href="index.php?page=patients&action=view&id=<?php echo (int)$d['id']; ?>">ملف المريض</a>
                        <form method="post" action="index.php?page=billing&action=send_debt_reminder" style="display:inline;margin-right:8px;">
                            <input type="hidden" name="patient_id" value="<?php echo (int)$d['id']; ?>">
                            <button type="submit" class="btn-link" style="padding:0;border:none;background:none;cursor:pointer;color:var(--primary);">تذكير واتساب</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>
<?php if (!empty($invoicesWithBalance)): ?>
<div class="section-card" style="margin-bottom:24px;">
    <h3>تسجيل دفعة إضافية</h3>
    <form method="post" action="index.php?page=billing&action=add_payment" class="form-grid">
        <div>
            <label>الفاتورة</label>
            <select name="invoice_id" required onchange="var o=this.options[this.selectedIndex];if(o&&o.value){document.getElementById('max_pay').max=o.getAttribute('data-remaining')||99999;document.getElementById('max_pay').placeholder='الحد: '+o.getAttribute('data-remaining');}">
                <option value="">اختر فاتورة</option>
                <?php foreach ($invoicesWithBalance as $iv): $rem = (float)$iv['net_amount'] - (float)$iv['paid_amount']; ?>
                <option value="<?php echo (int)$iv['id']; ?>" data-remaining="<?php echo $rem; ?>">
                    <?php echo htmlspecialchars($iv['invoice_number'] . ' - ' . $iv['patient_name'], ENT_QUOTES, 'UTF-8'); ?> (متبقي: <?php echo number_format($rem, 2); ?>)
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label>المبلغ</label>
            <input type="number" step="0.01" name="amount" id="max_pay" required min="0.01" placeholder="المبلغ المدفوع">
        </div>
        <div class="form-actions"><button type="submit">تسجيل الدفعة</button></div>
    </form>
</div>
<?php endif; ?>
<div class="table-wrapper">
<table class="table">
    <thead>
        <tr>
            <th>رقم الفاتورة</th>
            <th>رقم الطلب</th>
            <th>المريض</th>
            <th>التاريخ</th>
            <?php if ($hasInvCurrency): ?><th>العملة</th><?php endif; ?>
            <th>الإجمالي</th>
            <th>الخصم</th>
            <th>الصافي</th>
            <th>المدفوع</th>
            <th>طريقة الدفع</th>
            <th>إجراء</th>
        </tr>
    </thead>
    <tbody>
    <?php foreach ($invoices as $row): $rowCurr = isset($row['currency']) && $row['currency'] ? $row['currency'] : 'IQD'; $rowSym = $rowCurr === 'USD' ? '$' : 'د.ع'; ?>
        <tr>
            <td><?php echo htmlspecialchars($row['invoice_number'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo htmlspecialchars($row['order_number'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo htmlspecialchars($row['patient_name'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo htmlspecialchars($row['issue_date'], ENT_QUOTES, 'UTF-8'); ?></td>
            <?php if ($hasInvCurrency): ?><td><?php echo $rowCurr === 'USD' ? '$' : 'د.ع'; ?></td><?php endif; ?>
            <td><?php echo number_format((float)$row['total_amount'], 2); ?> <?php echo $rowSym; ?></td>
            <td><?php echo number_format((float)$row['discount_amount'], 2); ?> <?php echo $rowSym; ?></td>
            <td><?php echo number_format((float)$row['net_amount'], 2); ?> <?php echo $rowSym; ?></td>
            <td><?php echo number_format((float)$row['paid_amount'], 2); ?> <?php echo $rowSym; ?></td>
            <td><?php echo htmlspecialchars($payMethodLabels[$row['payment_method'] ?? ''] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
            <td>
                <a href="index.php?page=print_invoice&invoice_id=<?php echo (int)$row['id']; ?>" target="_blank" class="btn-action btn-action--view">طباعة</a>
                <?php
                $rowRem = max(0, (float)$row['net_amount'] - (float)$row['paid_amount']);
                if ($rowRem > 0 && isset($pg) && $pg->isEnabled()):
                ?><a href="index.php?page=pay&invoice_id=<?php echo (int)$row['id']; ?>" target="_blank" class="btn-action btn-action--order">دفع</a><?php endif; ?>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>
<?php if ($billingTotalPages > 1): ?>
<div class="pagination" style="margin-top:16px;">
    <?php
    $baseUrl = 'index.php?page=billing' . ($billingSearch ? '&q=' . urlencode($billingSearch) : '');
    for ($i = 1; $i <= min($billingTotalPages, 10); $i++):
        $active = $i === $billingPage ? ' style="font-weight:bold;"' : '';
    ?><a href="<?php echo $baseUrl . '&p=' . $i; ?>"<?php echo $active; ?>><?php echo $i; ?></a><?php endfor; ?>
</div>
<?php endif; ?>
