<?php
session_start();

// التحقق من تسجيل الدخول
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

// تضمين ملف الاتصال بقاعدة البيانات
require_once 'db_connect.php';

// التأكد من أن الاتصال ناجح
if (!isset($conn) || !$conn) {
    die("فشل الاتصال بقاعدة البيانات. تحقق من ملف db_connect.php.");
}

// جلب بيانات المحل
$store_settings = [];
try {
    $stmt = $conn->query("SELECT * FROM settings LIMIT 1");
    $store_settings = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
} catch (PDOException $e) {
    error_log("Error fetching store settings: " . $e->getMessage());
    $store_settings = ['store_name' => 'Astra', 'phone' => '', 'address' => '', 'logo' => ''];
}

// جلب اسم المستخدم الحالي
$user_name = $_SESSION['user_name'] ?? '';
$user_id = $_SESSION['user_id'];
if (empty($user_name)) {
    try {
        $stmt = $conn->prepare("SELECT username FROM users WHERE id = :user_id");
        $stmt->execute([':user_id' => $user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        if (!empty($user) && isset($user['username'])) {
            $user_name = $user['username'];
            $_SESSION['user_name'] = $user_name;
        }
    } catch (PDOException $e) {
        error_log("Error fetching user name: " . $e->getMessage());
        $user_name = 'مستخدم غير محدد';
    }
}

// جلب الفواتير التي تحتوي على تقسيط (باستثناء الفواتير المنتهية)
$installment_invoices = [];
try {
    $stmt = $conn->query("
        SELECT si.id, si.invoice_number, si.date, si.final_total, si.advance_payment, si.remaining_amount, si.installment_duration, c.id AS client_id, c.name AS client_name,
               GROUP_CONCAT(i.name) AS item_names
        FROM sales_invoices si
        JOIN clients c ON si.client_id = c.id
        JOIN sales_invoice_items sii ON sii.invoice_id = si.id
        JOIN items i ON sii.item_id = i.id
        WHERE si.installment_type = 'installment' AND si.remaining_amount > 0
        GROUP BY si.id
        ORDER BY si.date DESC
    ");
    $installment_invoices = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching installment invoices: " . $e->getMessage());
}

// جلب الخزنات لاختيار الخزنة عند الدفع
$treasuries = [];
try {
    $treasuries = $conn->query("SELECT id, name FROM treasuries")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching treasuries: " . $e->getMessage());
    $treasuries[] = ['id' => 1, 'name' => 'الخزنة الافتراضية'];
}

// معالجة تسجيل الدفعات
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['pay_installment'])) {
    $installment_id = $_POST['installment_id'] ?? 0;
    $amount_paid = $_POST['amount_paid'] ?? 0;
    $treasury_id = $_POST['treasury_id'] ?? 1;
    $payment_date = $_POST['payment_date'] ?? date('Y-m-d');
    $installment_number = $_POST['installment_number'] ?? 0;

    try {
        $conn->beginTransaction();

        // جلب تفاصيل القسط
        $stmt = $conn->prepare("SELECT invoice_id, amount FROM installments WHERE id = :installment_id AND status = 'pending'");
        $stmt->execute([':installment_id' => $installment_id]);
        $installment = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$installment) {
            throw new Exception("القسط غير موجود أو تم دفعه بالفعل.");
        }

        if ($amount_paid != $installment['amount']) {
            throw new Exception("المبلغ المدفوع يجب أن يكون مساويًا لقيمة القسط: " . $installment['amount']);
        }

        // تحديث حالة القسط إلى "مدفوع"
        $stmt = $conn->prepare("UPDATE installments SET status = 'paid', paid_date = :payment_date WHERE id = :installment_id");
        $stmt->execute([
            ':installment_id' => $installment_id,
            ':payment_date' => $payment_date
        ]);

        // تحديث المبلغ المتبقي في الفاتورة
        $stmt = $conn->prepare("UPDATE sales_invoices SET remaining_amount = remaining_amount - :amount, paid_amount = paid_amount + :amount WHERE id = :invoice_id");
        $stmt->execute([
            ':amount' => $installment['amount'],
            ':invoice_id' => $installment['invoice_id']
        ]);

        // جلب بيانات الفاتورة
        $stmt = $conn->prepare("SELECT invoice_number, client_id, paid_amount FROM sales_invoices WHERE id = :invoice_id");
        $stmt->execute([':invoice_id' => $installment['invoice_id']]);
        $invoice = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$invoice) {
            throw new Exception("الفاتورة غير موجودة.");
        }

        // جلب اسم العميل
        $stmt = $conn->prepare("SELECT name FROM clients WHERE id = :client_id");
        $stmt->execute([':client_id' => $invoice['client_id']]);
        $client = $stmt->fetch(PDO::FETCH_ASSOC);
        $client_name = $client['name'] ?? 'عميل غير محدد';

        // تسجيل المعاملة في treasury_transactions
        $stmt = $conn->prepare("INSERT INTO treasury_transactions (treasury_id, invoice_id, transaction_type, amount, description, date) VALUES (:treasury_id, :invoice_id, 'income', :amount, :description, :date)");
        $stmt->execute([
            ':treasury_id' => $treasury_id,
            ':invoice_id' => $installment['invoice_id'],
            ':amount' => $installment['amount'],
            ':description' => "دفع قسط لفاتورة رقم " . $invoice['invoice_number'],
            ':date' => $payment_date
        ]);

        // تحديث رصيد الخزنة
        $stmt = $conn->prepare("UPDATE treasuries SET current_balance = current_balance + :amount WHERE id = :treasury_id");
        $stmt->execute([
            ':amount' => $installment['amount'],
            ':treasury_id' => $treasury_id
        ]);

        // جلب الأقساط المتبقية
        $stmt = $conn->prepare("SELECT installment_number, amount, due_date FROM installments WHERE invoice_id = :invoice_id AND status = 'pending' ORDER BY installment_number");
        $stmt->execute([':invoice_id' => $installment['invoice_id']]);
        $remaining_installments = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $conn->commit();

        header('Content-Type: application/json');
        echo json_encode([
            'status' => 'success',
            'message' => 'تم تسجيل الدفع بنجاح',
            'installment_number' => $installment_number,
            'payment_date' => $payment_date,
            'amount' => $installment['amount'],
            'remaining_installments' => $remaining_installments,
            'total_paid' => $invoice['paid_amount'],
            'invoice_number' => $invoice['invoice_number'],
            'client_name' => $client_name
        ]);
        exit();
    } catch (Exception $e) {
        $conn->rollBack();
        error_log("Error paying installment: " . $e->getMessage());
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => 'فشل تسجيل الدفع: ' . $e->getMessage()]);
        exit();
    }
}

// جلب الأقساط المستحقة لإرسال الإشعارات
$due_installments = [];
try {
    $stmt = $conn->query("
        SELECT i.id, i.invoice_id, i.installment_number, i.amount, i.due_date, si.invoice_number, c.name AS client_name, c.phone
        FROM installments i
        JOIN sales_invoices si ON i.invoice_id = si.id
        JOIN clients c ON si.client_id = c.id
        WHERE i.status = 'pending' AND i.due_date <= DATE_ADD(CURDATE(), INTERVAL 3 DAY)
        ORDER BY i.due_date ASC
    ");
    $due_installments = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching due installments: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Astra - إدارة الأقساط</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            min-height: 100vh;
            direction: rtl;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #2ECC71, #3498DB, #E74C3C);
            overflow-x: hidden;
            animation: gradientShift 10s ease infinite;
            background-size: 400% 400%;
        }

        @keyframes gradientShift {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }

        .container-fluid {
            padding: 20px;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            padding: 20px;
            margin-bottom: 20px;
            animation: fadeIn 1s ease-in-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        h2, h4 {
            color: #2ECC71;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
            text-shadow: 0 0 5px rgba(46, 204, 113, 0.5);
        }

        .table {
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            width: 100%;
        }

        .table thead {
            background: #2ECC71;
            color: #fff;
        }

        .table tbody tr:hover {
            background: rgba(46, 204, 113, 0.1);
        }

        .btn {
            border-radius: 10px;
            padding: 6px 15px;
            font-weight: bold;
            transition: all 0.4s ease;
            position: relative;
            overflow: hidden;
            font-size: 0.9rem;
        }

        .btn-pay {
            background: linear-gradient(45deg, #2ECC71, #27AE60);
            border: none;
            color: #fff;
        }

        .btn-pay:hover {
            background: linear-gradient(45deg, #27AE60, #219653);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(46, 204, 113, 0.5);
        }

        .btn-notify {
            background: linear-gradient(45deg, #F1C40F, #D4AC0D);
            border: none;
            color: #fff;
        }

        .btn-notify:hover {
            background: linear-gradient(45deg, #D4AC0D, #B7950B);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(241, 196, 15, 0.5);
        }

        .btn-details {
            background: linear-gradient(45deg, #3498DB, #2980B9);
            border: none;
            color: #fff;
        }

        .btn-details:hover {
            background: linear-gradient(45deg, #2980B9, #2471A3);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.5);
        }

        .btn i {
            margin-left: 8px;
        }

        .due-notifications {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1000;
            max-width: 300px;
        }

        .notification {
            background: linear-gradient(45deg, #E74C3C, #C0392B);
            color: #fff;
            padding: 10px 20px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(231, 76, 60, 0.5);
            margin-bottom: 10px;
            font-size: 0.9rem;
            font-weight: bold;
            animation: slideIn 0.5s ease-in-out;
        }

        @keyframes slideIn {
            from { opacity: 0; transform: translateX(100%); }
            to { opacity: 1; transform: translateX(0); }
        }

        .form-label {
            color: #3498DB;
            font-weight: bold;
            margin-bottom: 5px;
            display: flex;
            align-items: center;
            font-size: 0.9rem;
        }

        .form-label i {
            margin-left: 8px;
            color: #2ECC71;
        }

        .form-control, .form-select {
            border-radius: 10px;
            border: 2px solid #2ECC71;
            padding: 6px 10px;
            background: rgba(255, 255, 255, 0.8);
            transition: all 0.3s ease;
            box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.1);
            font-size: 0.9rem;
        }

        .form-control:focus, .form-select:focus {
            border-color: #3498DB;
            box-shadow: 0 0 10px rgba(52, 152, 219, 0.5), inset 0 2px 5px rgba(0, 0, 0, 0.1);
            background: #fff;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="card">
            <h2><i class="fas fa-money-check-alt me-2"></i> إدارة الأقساط</h2>

            <!-- جدول الفواتير التي تحتوي على تقسيط -->
            <h4>الفواتير بالتقسيط</h4>
            <div class="row mb-3">
                <div class="col-md-4">
                    <label class="form-label"><i class="fas fa-user"></i> فلتر حسب العميل</label>
                    <select class="form-select" id="clientFilter" onchange="filterInvoices()">
                        <option value="">جميع العملاء</option>
                        <?php
                        $clients = $conn->query("SELECT id, name FROM clients")->fetchAll(PDO::FETCH_ASSOC);
                        foreach ($clients as $client) {
                            echo '<option value="' . $client['id'] . '">' . htmlspecialchars($client['name']) . '</option>';
                        }
                        ?>
                    </select>
                </div>
            </div>
            <div class="table-responsive" style="max-height: 50vh; overflow-y: auto;">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>رقم الفاتورة</th>
                            <th>التاريخ</th>
                            <th>اسم العميل</th>
                            <th>الأصناف</th>
                            <th>الإجمالي</th>
                            <th>الدفعة المقدمة</th>
                            <th>المتبقي</th>
                            <th>مدة التقسيط</th>
                            <th>الإجراء</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($installment_invoices)): ?>
                            <?php foreach ($installment_invoices as $invoice): ?>
                                <tr data-client-id="<?php echo $invoice['client_id']; ?>">
                                    <td><?php echo htmlspecialchars($invoice['invoice_number']); ?></td>
                                    <td><?php echo htmlspecialchars($invoice['date']); ?></td>
                                    <td><?php echo htmlspecialchars($invoice['client_name']); ?></td>
                                    <td><?php echo htmlspecialchars($invoice['item_names']); ?></td>
                                    <td><?php echo number_format($invoice['final_total'], 2); ?> ج.م</td>
                                    <td><?php echo number_format($invoice['advance_payment'], 2); ?> ج.م</td>
                                    <td><?php echo number_format($invoice['remaining_amount'], 2); ?> ج.م</td>
                                    <td><?php echo htmlspecialchars($invoice['installment_duration']); ?> شهر</td>
                                    <td>
                                        <button class="btn btn-details" onclick="showInstallmentDetails(<?php echo $invoice['id']; ?>)">
                                            <i class="fas fa-eye"></i> عرض التفاصيل
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="9" style="text-align: center; color: #E74C3C;">لا توجد فواتير تقسيط.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- قسم تفاصيل الأقساط -->
            <div id="installmentDetails" style="display: none; margin-top: 20px;">
                <h4>تفاصيل الأقساط</h4>
                <div class="table-responsive" style="max-height: 30vh; overflow-y: auto;">
                    <table class="table table-striped" id="installmentsTable">
                        <thead>
                            <tr>
                                <th>رقم القسط</th>
                                <th>المبلغ</th>
                                <th>تاريخ الاستحقاق</th>
                                <th>الحالة</th>
                                <th>تاريخ الدفع</th>
                                <th>الإجراء</th>
                            </tr>
                        </thead>
                        <tbody id="installmentsTableBody">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- قسم الإشعارات -->
        <div class="due-notifications">
            <?php if (!empty($due_installments)): ?>
                <?php foreach ($due_installments as $due): ?>
                    <div class="notification">
                        قسط مستحق (#<?php echo $due['installment_number']; ?>) لفاتورة #<?php echo $due['invoice_number']; ?><br>
                        العميل: <?php echo htmlspecialchars($due['client_name']); ?><br>
                        المبلغ: <?php echo number_format($due['amount'], 2); ?> ج.م<br>
                        تاريخ الاستحقاق: <?php echo $due['due_date']; ?><br>
                        <?php if (!empty($due['phone'])): ?>
                            <button class="btn btn-notify mt-2" onclick="sendNotification(<?php echo $due['id']; ?>, '<?php echo htmlspecialchars($due['client_name']); ?>', '<?php echo htmlspecialchars($due['phone']); ?>', <?php echo $due['amount']; ?>, '<?php echo $due['due_date']; ?>')">
                                <i class="fas fa-bell"></i> إرسال إشعار
                            </button>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="notification" style="background: linear-gradient(45deg, #2ECC71, #27AE60);">
                    لا توجد أقساط مستحقة قريبًا.
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Modal لاختيار الخزنة وتاريخ الدفع -->
    <div class="modal fade" id="payInstallmentModal" tabindex="-1" aria-labelledby="payInstallmentModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="payInstallmentModalLabel">دفع قسط</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="payInstallmentForm">
                        <input type="hidden" name="installment_id" id="modalInstallmentId">
                        <input type="hidden" name="installment_number" id="modalInstallmentNumber">
                        <input type="hidden" name="amount_paid" id="modalAmount">
                        <div class="mb-3">
                            <label for="treasury_id" class="form-label">الخزنة</label>
                            <select class="form-select" name="treasury_id" id="treasury_id" required>
                                <?php foreach ($treasuries as $treasury): ?>
                                    <option value="<?php echo $treasury['id']; ?>"><?php echo htmlspecialchars($treasury['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="payment_date" class="form-label">تاريخ الدفع</label>
                            <input type="date" class="form-control" name="payment_date" id="payment_date" value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="button" class="btn btn-primary" id="confirmPayBtn">تأكيد الدفع</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentInstallmentId = null;
        let currentAmount = null;
        let currentInstallmentNumber = null;

        function showInstallmentDetails(invoiceId) {
            fetch('fetch_installments.php?invoice_id=' + invoiceId)
                .then(response => response.json())
                .then(data => {
                    const tableBody = document.getElementById('installmentsTableBody');
                    tableBody.innerHTML = '';
                    if (data.status === 'success' && data.installments.length > 0) {
                        data.installments.forEach(installment => {
                            const row = document.createElement('tr');
                            row.innerHTML = `
                                <td>${installment.installment_number}</td>
                                <td>${Number(installment.amount).toFixed(2)} ج.م</td>
                                <td>${installment.due_date}</td>
                                <td>${installment.status === 'pending' ? 'معلق' : 'مدفوع'}</td>
                                <td>${installment.paid_date || '-'}</td>
                                <td>
                                    ${installment.status === 'pending' ? `
                                        <button class="btn btn-pay" onclick="openPayModal(${installment.id}, ${installment.installment_number}, ${installment.amount})">
                                            <i class="fas fa-money-bill"></i> دفع
                                        </button>
                                    ` : '-'}
                                </td>
                            `;
                            tableBody.appendChild(row);
                        });
                        document.getElementById('installmentDetails').style.display = 'block';
                    } else {
                        tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #E74C3C;">لا توجد أقساط لهذه الفاتورة.</td></tr>';
                        document.getElementById('installmentDetails').style.display = 'block';
                    }
                })
                .catch(error => {
                    console.error('Error fetching installments:', error);
                    document.getElementById('installmentsTableBody').innerHTML = '<tr><td colspan="6" style="text-align: center; color: #E74C3C;">حدث خطأ أثناء جلب الأقساط.</td></tr>';
                    document.getElementById('installmentDetails').style.display = 'block';
                });
        }

        function openPayModal(installmentId, installmentNumber, amount) {
            currentInstallmentId = installmentId;
            currentInstallmentNumber = installmentNumber;
            currentAmount = amount;
            document.getElementById('modalInstallmentId').value = installmentId;
            document.getElementById('modalInstallmentNumber').value = installmentNumber;
            document.getElementById('modalAmount').value = amount;
            const modal = new bootstrap.Modal(document.getElementById('payInstallmentModal'));
            modal.show();
        }

        document.getElementById('confirmPayBtn').addEventListener('click', () => {
            const form = document.getElementById('payInstallmentForm');
            const formData = new FormData(form);
            formData.append('pay_installment', '1');

            fetch('manage_installments.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                const modal = bootstrap.Modal.getInstance(document.getElementById('payInstallmentModal'));
                modal.hide();
                if (data.status === 'success') {
                    alert(data.message);

                    // طباعة إيصال السداد
                    printPaymentReceipt(
                        data.installment_number,
                        data.payment_date,
                        data.amount,
                        data.remaining_installments,
                        data.total_paid,
                        data.invoice_number,
                        data.client_name
                    );

                    location.reload();
                } else {
                    alert('حدث خطأ: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error paying installment:', error);
                alert('حدث خطأ أثناء تسجيل الدفع: ' + error.message);
            });
        });

        function printPaymentReceipt(installmentNumber, paymentDate, amount, remainingInstallments, totalPaid, invoiceNumber, clientName) {
            const printWindow = window.open('', 'PRINT', 'height=400,width=300');
            if (!printWindow) {
                console.error('Failed to open print window. It might be blocked by the browser.');
                alert('فشل فتح نافذة الطباعة. قد تكون محظورة بواسطة المتصفح.');
                return;
            }

            const storeName = '<?php echo htmlspecialchars($store_settings['store_name'] ?? 'Astra'); ?>';
            const storePhone = '<?php echo htmlspecialchars($store_settings['phone'] ?? ''); ?>';
            const storeAddress = '<?php echo htmlspecialchars($store_settings['address'] ?? ''); ?>';
            const storeLogo = '<?php echo !empty($store_settings['logo']) ? "uploads/" . htmlspecialchars($store_settings['logo']) : ''; ?>';
            const userName = '<?php echo htmlspecialchars($user_name); ?>';

            // مصفوفة أسماء الشهور باللغة العربية
            const monthNames = [
                'يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو',
                'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'
            ];

            // تنسيق تواريخ الأقساط المتبقية
            let remainingInstallmentsHtml = '';
            if (remainingInstallments && remainingInstallments.length > 0) {
                remainingInstallments.forEach(installment => {
                    const dueDate = new Date(installment.due_date);
                    const day = dueDate.getDate();
                    const month = monthNames[dueDate.getMonth()];
                    const year = dueDate.getFullYear();
                    remainingInstallmentsHtml += `<p>القسط ${installment.installment_number}: ${day} ${month} ${year}</p>`;
                });
            } else {
                remainingInstallmentsHtml = '<p>لا توجد أقساط متبقية.</p>';
            }

            printWindow.document.write(`
                <html dir="rtl">
                <head>
                    <title>إيصال سداد قسط #${invoiceNumber}</title>
                    <style>
                        @media print {
                            body {
                                margin: 0;
                                padding: 0;
                                width: 80mm;
                                font-family: 'Arial', sans-serif;
                                font-size: 12px;
                                text-align: center;
                                direction: rtl;
                                line-height: 1.2;
                            }
                            .header, .footer {
                                margin: 3px 0;
                            }
                            h3 {
                                font-size: 14px;
                                margin: 5px 0;
                            }
                            p {
                                margin: 2px 0;
                            }
                            .logo {
                                width: 30mm;
                                height: 30mm;
                                margin: 5px auto;
                                display: block;
                            }
                            @page {
                                margin: 0;
                            }
                        }
                    </style>
                </head>
                <body>
                    <div class="header">
                        ${storeLogo ? `<img src="${storeLogo}" alt="Logo" class="logo">` : ''}
                        <h3>${storeName}</h3>
                        <h3>إيصال سداد قسط</h3>
                        <p>رقم الفاتورة: ${invoiceNumber}</p>
                        <p>العميل: ${clientName}</p>
                        <p>المستخدم: ${userName}</p>
                    </div>
                    <div class="content">
                        <p>تم سداد القسط رقم ${installmentNumber} بتاريخ ${paymentDate}</p>
                        <p>المبلغ: ${Number(amount).toFixed(2)} ج.م</p>
                        <p>إجمالي المبلغ المدفوع: ${Number(totalPaid).toFixed(2)} ج.م</p>
                        <h4>الأقساط المتبقية:</h4>
                        ${remainingInstallmentsHtml}
                    </div>
                    <div class="footer">
                        ${storePhone ? `<p>رقم الهاتف: ${storePhone}</p>` : ''}
                        ${storeAddress ? `<p>العنوان: ${storeAddress}</p>` : ''}
                    </div>
                </body>
                </html>
            `);

            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            setTimeout(() => {
                if (!printWindow.closed) {
                    printWindow.close();
                }
            }, 1000);
        }

        function sendNotification(installmentId, clientName, phone, amount, dueDate) {
            const message = `مرحبًا ${clientName}،\nلديك قسط مستحق بقيمة ${amount.toFixed(2)} ج.م بتاريخ ${dueDate}.\nيرجى السداد في أقرب وقت.\nشكرًا!`;
            const whatsappUrl = `https://api.whatsapp.com/send?phone=${phone}&text=${encodeURIComponent(message)}`;
            window.open(whatsappUrl, '_blank');
        }

        function filterInvoices() {
            const clientId = document.getElementById('clientFilter').value;
            const rows = document.querySelectorAll('table.table-striped tbody tr');
            rows.forEach(row => {
                const rowClientId = row.getAttribute('data-client-id');
                if (!clientId || rowClientId === clientId) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        }
    </script>
</body>
</html>