<?php
require_once 'config/init.php';
require_once 'includes/auth.php';
requireAuth();

$db = getDB();

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add_debt') {
        $subscriber_id = $_POST['subscriber_id'] ?? 0;
        $meter_number = $_POST['meter_number'] ?? '';
        $subscription_fee = floatval($_POST['subscription_fee'] ?? 0);
        $deposit_amount = floatval($_POST['deposit_amount'] ?? 0);
        $subscription_date = $_POST['subscription_date'] ?? '';
        $total_debt = $subscription_fee - $deposit_amount;

        try {
            $db->exec('BEGIN TRANSACTION');
            
            // Check if subscriber already has a debt
            $stmt = $db->prepare('SELECT COUNT(*) as count FROM subscriber_debts WHERE subscriber_id = :subscriber_id');
            $stmt->bindValue(':subscriber_id', $subscriber_id, SQLITE3_INTEGER);
            $result = $stmt->execute();
            $row = $result->fetchArray(SQLITE3_ASSOC);
            
            if ($row['count'] > 0) {
                throw new Exception('المشترك لديه دين مسجل بالفعل');
            }

            // Validate amounts
            if ($subscription_fee <= 0) {
                throw new Exception('مبلغ الاشتراك يجب أن يكون أكبر من صفر');
            }
            if ($deposit_amount < 0) {
                throw new Exception('مبلغ التسبيق لا يمكن أن يكون سالباً');
            }
            if ($deposit_amount >= $subscription_fee) {
                throw new Exception('مبلغ التسبيق لا يمكن أن يكون أكبر من أو يساوي مبلغ الاشتراك');
            }
            
            // Get cash fund
            if ($deposit_amount > 0) {
                $stmt = $db->prepare('SELECT id, current_balance FROM cash_fund ORDER BY id DESC LIMIT 1');
                $result = $stmt->execute();
                $cash_fund = $result->fetchArray(SQLITE3_ASSOC);
                
                if (!$cash_fund) {
                    throw new Exception('الرجاء إنشاء صندوق مالي أولاً');
                }
            }

            // Insert debt record
            $stmt = $db->prepare('INSERT INTO subscriber_debts (subscriber_id, meter_number, subscription_fee, deposit_amount, subscription_date, total_debt, remaining_debt) VALUES (:subscriber_id, :meter_number, :subscription_fee, :deposit_amount, :subscription_date, :total_debt, :remaining_debt)');
            
            $stmt->bindValue(':subscriber_id', $subscriber_id, SQLITE3_INTEGER);
            $stmt->bindValue(':meter_number', $meter_number);
            $stmt->bindValue(':subscription_fee', $subscription_fee);
            $stmt->bindValue(':deposit_amount', $deposit_amount);
            $stmt->bindValue(':subscription_date', $subscription_date);
            $stmt->bindValue(':total_debt', $total_debt);
            $stmt->bindValue(':remaining_debt', $total_debt);
            
            $stmt->execute();
            $debt_id = $db->lastInsertRowID();
            
            // If there's a deposit amount, update cash fund and record transaction
            if ($deposit_amount > 0) {
                // Update cash fund balance
                $new_balance = $cash_fund['current_balance'] + $deposit_amount;
                $stmt = $db->prepare('UPDATE cash_fund SET current_balance = :balance, updated_at = CURRENT_TIMESTAMP WHERE id = :id');
                $stmt->bindValue(':balance', $new_balance, SQLITE3_FLOAT);
                $stmt->bindValue(':id', $cash_fund['id'], SQLITE3_INTEGER);
                $stmt->execute();
                
                // Record financial transaction
                $stmt = $db->prepare('
                    INSERT INTO financial_transactions (
                        transaction_type,
                        amount,
                        source_type,
                        source_id,
                        description,
                        reference_type,
                        reference_id,
                        balance_after,
                        created_at
                    ) VALUES (
                        "DEPOSIT",
                        :amount,
                        "CASH_FUND",
                        :cash_fund_id,
                        :description,
                        "DEBT",
                        :debt_id,
                        :balance_after,
                        CURRENT_TIMESTAMP
                    )
                ');
                
                $stmt->bindValue(':amount', $deposit_amount, SQLITE3_FLOAT);
                $stmt->bindValue(':cash_fund_id', $cash_fund['id'], SQLITE3_INTEGER);
                $stmt->bindValue(':description', "تسبيق على دين الاشتراك - رقم العداد: " . $meter_number, SQLITE3_TEXT);
                $stmt->bindValue(':debt_id', $debt_id, SQLITE3_INTEGER);
                $stmt->bindValue(':balance_after', $new_balance, SQLITE3_FLOAT);
                $stmt->execute();
            }
            
            $db->exec('COMMIT');
            logActivity('إضافة دين', "رقم العداد: $meter_number، التسبيق: $deposit_amount درهم");
            $_SESSION['success'] = 'تم تسجيل الدين بنجاح' . ($deposit_amount > 0 ? ' وإضافة التسبيق إلى الصندوق' : '');
            header('Location: subscriber_debts.php');
            exit;
            
        } catch (Exception $e) {
            $db->exec('ROLLBACK');
            $_SESSION['error'] = 'حدث خطأ: ' . $e->getMessage();
            header('Location: subscriber_debts.php');
            exit;
        }
    } elseif ($action === 'add_payment') {
        $debt_id = $_POST['debt_id'] ?? 0;
        $payment_amount = floatval($_POST['payment_amount'] ?? 0);
        $payment_date = $_POST['payment_date'] ?? '';

        try {
            $db->exec('BEGIN TRANSACTION');

            // Get debt details
            $stmt = $db->prepare('SELECT id, meter_number, remaining_debt FROM subscriber_debts WHERE id = :id');
            $stmt->bindValue(':id', $debt_id, SQLITE3_INTEGER);
            $result = $stmt->execute();
            $debt = $result->fetchArray(SQLITE3_ASSOC);
            
            if (!$debt) {
                throw new Exception('الدين غير موجود');
            }
            
            if ($payment_amount <= 0) {
                throw new Exception('مبلغ الدفعة يجب أن يكون أكبر من صفر');
            }
            
            if ($payment_amount > $debt['remaining_debt']) {
                throw new Exception('مبلغ الدفعة أكبر من المبلغ المتبقي');
            }
            
            // Get cash fund
            $stmt = $db->prepare('SELECT id, current_balance FROM cash_fund ORDER BY id DESC LIMIT 1');
            $result = $stmt->execute();
            $cash_fund = $result->fetchArray(SQLITE3_ASSOC);
            
            if (!$cash_fund) {
                throw new Exception('الرجاء إنشاء صندوق مالي أولاً');
            }

            // Add payment record
            $stmt = $db->prepare('INSERT INTO debt_payments (debt_id, payment_amount, payment_date) VALUES (:debt_id, :payment_amount, :payment_date)');
            $stmt->bindValue(':debt_id', $debt_id, SQLITE3_INTEGER);
            $stmt->bindValue(':payment_amount', $payment_amount);
            $stmt->bindValue(':payment_date', $payment_date);
            $stmt->execute();

            // Update remaining debt
            $stmt = $db->prepare('UPDATE subscriber_debts SET remaining_debt = remaining_debt - :payment_amount WHERE id = :debt_id');
            $stmt->bindValue(':payment_amount', $payment_amount);
            $stmt->bindValue(':debt_id', $debt_id, SQLITE3_INTEGER);
            $stmt->execute();
            
            // Update cash fund balance
            $new_balance = $cash_fund['current_balance'] + $payment_amount;
            $stmt = $db->prepare('UPDATE cash_fund SET current_balance = :balance, updated_at = CURRENT_TIMESTAMP WHERE id = :id');
            $stmt->bindValue(':balance', $new_balance, SQLITE3_FLOAT);
            $stmt->bindValue(':id', $cash_fund['id'], SQLITE3_INTEGER);
            $stmt->execute();
            
            // Record financial transaction
            $stmt = $db->prepare('
                INSERT INTO financial_transactions (
                    transaction_type,
                    amount,
                    source_type,
                    source_id,
                    description,
                    reference_type,
                    reference_id,
                    balance_after,
                    created_at
                ) VALUES (
                    "DEPOSIT",
                    :amount,
                    "CASH_FUND",
                    :cash_fund_id,
                    :description,
                    "DEBT_PAYMENT",
                    :debt_id,
                    :balance_after,
                    CURRENT_TIMESTAMP
                )
            ');
            
            $stmt->bindValue(':amount', $payment_amount, SQLITE3_FLOAT);
            $stmt->bindValue(':cash_fund_id', $cash_fund['id'], SQLITE3_INTEGER);
            $stmt->bindValue(':description', "دفعة على دين الاشتراك - رقم العداد: " . $debt['meter_number'], SQLITE3_TEXT);
            $stmt->bindValue(':debt_id', $debt_id, SQLITE3_INTEGER);
            $stmt->bindValue(':balance_after', $new_balance, SQLITE3_FLOAT);
            $stmt->execute();

            $db->exec('COMMIT');
            logActivity('إضافة دفعة', "رقم الدين: $debt_id، المبلغ: $payment_amount درهم");
            $_SESSION['success'] = 'تم تسجيل الدفعة وإضافتها إلى الصندوق بنجاح';
            header('Location: subscriber_debts.php');
            exit;
            
        } catch (Exception $e) {
            $db->exec('ROLLBACK');
            $_SESSION['error'] = 'حدث خطأ: ' . $e->getMessage();
            header('Location: subscriber_debts.php');
            exit;
        }
    }
}

// Get all subscribers with debts and their payment history
$subscribers_debts = [];
$result = $db->query('
    SELECT 
        s.id as subscriber_id,
        s.full_name as subscriber_name,
        s.meter_number as subscriber_meter_number,
        sd.id as debt_id,
        sd.meter_number,
        sd.subscription_fee,
        sd.deposit_amount,
        sd.subscription_date,
        sd.total_debt,
        sd.remaining_debt,
        (
            SELECT GROUP_CONCAT(payment_amount || "|" || payment_date)
            FROM debt_payments dp
            WHERE dp.debt_id = sd.id
            ORDER BY dp.payment_date DESC
        ) as payment_history
    FROM subscribers s
    LEFT JOIN subscriber_debts sd ON s.id = sd.subscriber_id
    WHERE s.status = 1
    ORDER BY sd.created_at DESC
');

while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    if ($row['payment_history']) {
        $payments = [];
        foreach (explode(',', $row['payment_history']) as $payment) {
            list($amount, $date) = explode('|', $payment);
            $payments[] = [
                'amount' => $amount,
                'date' => $date
            ];
        }
        $row['payments'] = $payments;
    } else {
        $row['payments'] = [];
    }
    $subscribers_debts[] = $row;
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة ديون المشتركين</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .sidebar {
            position: fixed;
            top: 0;
            right: 0;
            bottom: 0;
            z-index: 100;
            padding: 48px 0 0;
            box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
            width: 280px;
        }
        .sidebar-sticky {
            position: relative;
            top: 0;
            height: calc(100vh - 48px);
            padding-top: .5rem;
            overflow-x: hidden;
            overflow-y: auto;
        }
        .main-content {
            margin-right: 280px;
            padding: 20px;
            transition: margin 0.3s;
            width: calc(100% - 280px);
        }
        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                position: relative;
                margin-bottom: 20px;
            }
            .main-content {
                margin-right: 0;
                width: 100%;
            }
        }
        .debt-status {
            display: inline-block;
            padding: 0.25em 0.6em;
            border-radius: 0.25rem;
            font-size: 0.875em;
        }
        .debt-status-paid {
            background-color: #d1e7dd;
            color: #0f5132;
        }
        .debt-status-partial {
            background-color: #fff3cd;
            color: #664d03;
        }
        .debt-status-unpaid {
            background-color: #f8d7da;
            color: #842029;
        }
        .payment-history {
            max-height: none;
            margin-top: 15px;
        }
        .payment-history-table {
            width: 100%;
            margin-bottom: 0;
        }
        .payment-history-header {
            background-color: #f8f9fa;
            padding: 10px 15px;
            border-radius: 4px;
            margin-bottom: 10px;
        }
        .status-badge {
            padding: 6px 12px;
            border-radius: 50px;
            font-weight: 500;
            font-size: 0.875rem;
        }
        .progress {
            height: 8px;
            margin-top: 10px;
            border-radius: 4px;
        }
        .payment-row:hover {
            background-color: #f8f9fa;
        }
        .modal-xl {
            max-width: 1140px;
        }
        .debt-card {
            border: 1px solid #dee2e6;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        .debt-card-header {
            background-color: #f8f9fa;
            padding: 15px;
            border-bottom: 1px solid #dee2e6;
            border-radius: 8px 8px 0 0;
        }
        .debt-card-body {
            padding: 15px;
        }
        .debt-info {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 15px;
        }
        .debt-info-item {
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 4px;
        }
        .debt-info-label {
            color: #6c757d;
            font-size: 0.875rem;
            margin-bottom: 5px;
        }
        .debt-info-value {
            font-weight: 500;
            font-size: 1rem;
        }

        @media print {
            body * {
                visibility: hidden;
            }
            .print-section, .print-section * {
                visibility: visible;
            }
            .print-section {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
            }
            .no-print {
                display: none !important;
            }
            .print-table {
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 20px;
            }
            .print-table th, .print-table td {
                border: 1px solid #000;
                padding: 8px;
                text-align: right;
            }
            .print-table th {
                background-color: #f8f9fa !important;
                -webkit-print-color-adjust: exact;
            }
            .print-header {
                text-align: center;
                margin-bottom: 20px;
            }
            .print-footer {
                text-align: left;
                margin-top: 20px;
                font-size: 0.9em;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <nav class="sidebar">
                <?php include 'includes/sidebar.php'; ?>
            </nav>
            <main class="main-content">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">إدارة ديون المشتركين</h1>
                </div>

                <?php if (isset($_SESSION['error'])): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo htmlspecialchars($_SESSION['error']); ?>
                        <button type="button" class="btn-close ms-0" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php unset($_SESSION['error']); ?>
                <?php endif; ?>

                <?php if (isset($_SESSION['success'])): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?php echo htmlspecialchars($_SESSION['success']); ?>
                        <button type="button" class="btn-close ms-0" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php unset($_SESSION['success']); ?>
                <?php endif; ?>

                <!-- Add New Debt Form -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h4 class="mb-0">تسجيل دين جديد</h4>
                    </div>
                    <div class="card-body">
                        <form method="POST" class="row g-3">
                            <input type="hidden" name="action" value="add_debt">
                            <div class="col-md-2">
                                <label class="form-label">المشترك</label>
                                <select name="subscriber_id" class="form-select" required>
                                    <option value="">اختر المشترك</option>
                                    <?php
                                    $stmt = $db->query('SELECT id, full_name, meter_number FROM subscribers WHERE status = 1 ORDER BY full_name');
                                    while ($row = $stmt->fetchArray(SQLITE3_ASSOC)) {
                                        echo "<option value='{$row['id']}'>{$row['full_name']} ({$row['meter_number']})</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">رقم العداد</label>
                                <input type="text" name="meter_number" class="form-control" required>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">مبلغ الاشتراك</label>
                                <input type="number" step="0.01" name="subscription_fee" class="form-control" required>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">مبلغ التسبيق</label>
                                <input type="number" step="0.01" name="deposit_amount" class="form-control" required>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">تاريخ الاشتراك</label>
                                <input type="date" name="subscription_date" class="form-control" required>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">&nbsp;</label>
                                <button type="submit" class="btn btn-primary form-control">تسجيل</button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Debts List -->
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h4 class="mb-0">سجل الديون والدفعات</h4>
                        <div>
                            <button class="btn btn-outline-primary me-2" type="button" data-bs-toggle="collapse" data-bs-target="#filterSection">
                                <i class="bi bi-funnel"></i> تصفية
                            </button>
                        </div>
                    </div>
                    <div class="collapse" id="filterSection">
                        <div class="card-body border-bottom">
                            <form class="row g-3">
                                <div class="col-md-3">
                                    <label class="form-label">حالة الدين</label>
                                    <select class="form-select">
                                        <option value="">الكل</option>
                                        <option value="unpaid">غير مسدد</option>
                                        <option value="partial">مسدد جزئياً</option>
                                        <option value="paid">مسدد</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">تاريخ الاشتراك من</label>
                                    <input type="date" class="form-control">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">تاريخ الاشتراك إلى</label>
                                    <input type="date" class="form-control">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">&nbsp;</label>
                                    <button type="submit" class="btn btn-primary d-block w-100">تطبيق</button>
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php foreach ($subscribers_debts as $debt): ?>
                            <?php if ($debt['debt_id']): ?>
                                <div class="debt-card">
                                    <div class="debt-card-header d-flex justify-content-between align-items-center">
                                        <div>
                                            <h5 class="mb-0"><?= htmlspecialchars($debt['subscriber_name']) ?></h5>
                                            <small class="text-muted">رقم العداد: <?= htmlspecialchars($debt['meter_number']) ?></small>
                                        </div>
                                        <div class="text-end">
                                            <?php
                                            $status_class = '';
                                            $status_text = '';
                                            if ($debt['remaining_debt'] <= 0) {
                                                $status_class = 'bg-success text-white';
                                                $status_text = 'مسدد';
                                            } elseif ($debt['remaining_debt'] < $debt['total_debt']) {
                                                $status_class = 'bg-warning text-dark';
                                                $status_text = 'مسدد جزئياً';
                                            } else {
                                                $status_class = 'bg-danger text-white';
                                                $status_text = 'غير مسدد';
                                            }
                                            $payment_percentage = 100 - ($debt['remaining_debt'] / $debt['total_debt'] * 100);
                                            ?>
                                            <span class="status-badge <?= $status_class ?>"><?= $status_text ?></span>
                                        </div>
                                    </div>
                                    <div class="debt-card-body">
                                        <div class="debt-info">
                                            <div class="debt-info-item">
                                                <div class="debt-info-label">مبلغ الاشتراك</div>
                                                <div class="debt-info-value"><?= number_format($debt['subscription_fee'], 2) ?> د.م</div>
                                            </div>
                                            <div class="debt-info-item">
                                                <div class="debt-info-label">مبلغ التسبيق</div>
                                                <div class="debt-info-value"><?= number_format($debt['deposit_amount'], 2) ?> د.م</div>
                                            </div>
                                            <div class="debt-info-item">
                                                <div class="debt-info-label">إجمالي الدين</div>
                                                <div class="debt-info-value"><?= number_format($debt['total_debt'], 2) ?> د.م</div>
                                            </div>
                                            <div class="debt-info-item">
                                                <div class="debt-info-label">المبلغ المتبقي</div>
                                                <div class="debt-info-value"><?= number_format($debt['remaining_debt'], 2) ?> د.م</div>
                                            </div>
                                            <div class="debt-info-item">
                                                <div class="debt-info-label">تاريخ الاشتراك</div>
                                                <div class="debt-info-value"><?= date('Y-m-d', strtotime($debt['subscription_date'])) ?></div>
                                            </div>
                                            <div class="debt-info-item">
                                                <div class="debt-info-label">نسبة السداد</div>
                                                <div class="debt-info-value"><?= number_format($payment_percentage, 1) ?>%</div>
                                                <div class="progress">
                                                    <div class="progress-bar <?= $status_class ?>" role="progressbar" style="width: <?= $payment_percentage ?>%"></div>
                                                </div>
                                            </div>
                                        </div>

                                        <?php if (!empty($debt['payments'])): ?>
                                            <div class="payment-history">
                                                <div class="payment-history-header d-flex justify-content-between align-items-center">
                                                    <h6 class="mb-0">سجل الدفعات</h6>
                                                    <span class="text-muted">عدد الدفعات: <?= count($debt['payments']) ?></span>
                                                </div>
                                                <div class="table-responsive">
                                                    <table class="table table-hover payment-history-table">
                                                        <thead>
                                                            <tr>
                                                                <th>#</th>
                                                                <th>التاريخ</th>
                                                                <th>المبلغ</th>
                                                                <th>النسبة من إجمالي الدين</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php foreach ($debt['payments'] as $index => $payment): ?>
                                                                <tr class="payment-row">
                                                                    <td><?= $index + 1 ?></td>
                                                                    <td><?= date('Y-m-d', strtotime($payment['date'])) ?></td>
                                                                    <td><?= number_format($payment['amount'], 2) ?> د.م</td>
                                                                    <td><?= number_format(($payment['amount'] / $debt['total_debt']) * 100, 1) ?>%</td>
                                                                </tr>
                                                            <?php endforeach; ?>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        <?php else: ?>
                                            <div class="text-center text-muted mt-3">
                                                <i class="bi bi-info-circle"></i> لا توجد دفعات مسجلة
                                            </div>
                                        <?php endif; ?>

                                        <div class="mt-3">
                                            <?php if ($debt['remaining_debt'] > 0): ?>
                                                <button type="button" class="btn btn-primary me-2" data-bs-toggle="modal" data-bs-target="#paymentModal<?= $debt['debt_id'] ?>">
                                                    <i class="bi bi-plus-circle"></i> تسجيل دفعة جديدة
                                                </button>
                                            <?php endif; ?>
                                            <button type="button" class="btn btn-outline-secondary" onclick="printPaymentHistory(<?= $debt['debt_id'] ?>)">
                                                <i class="bi bi-printer"></i> طباعة سجل الدفعات
                                            </button>
                                        </div>

                                        <!-- Payment Modal -->
                                        <div class="modal fade" id="paymentModal<?= $debt['debt_id'] ?>" tabindex="-1" aria-labelledby="paymentModalLabel<?= $debt['debt_id'] ?>" aria-hidden="true">
                                            <div class="modal-dialog">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h5 class="modal-title" id="paymentModalLabel<?= $debt['debt_id'] ?>">تسجيل دفعة جديدة</h5>
                                                        <button type="button" class="btn-close ms-0" data-bs-dismiss="modal" aria-label="Close"></button>
                                                    </div>
                                                    <form method="POST">
                                                        <div class="modal-body">
                                                            <input type="hidden" name="action" value="add_payment">
                                                            <input type="hidden" name="debt_id" value="<?= $debt['debt_id'] ?>">
                                                            
                                                            <div class="alert alert-info">
                                                                <strong>معلومات الدين:</strong><br>
                                                                إجمالي الدين: <?= number_format($debt['total_debt'], 2) ?> د.م<br>
                                                                المبلغ المتبقي: <?= number_format($debt['remaining_debt'], 2) ?> د.م
                                                            </div>

                                                            <div class="mb-3">
                                                                <label class="form-label">مبلغ الدفعة</label>
                                                                <div class="input-group">
                                                                    <input type="number" step="0.01" name="payment_amount" class="form-control" required max="<?= $debt['remaining_debt'] ?>" min="0.01">
                                                                    <span class="input-group-text">د.م</span>
                                                                </div>
                                                                <div class="form-text">الحد الأقصى: <?= number_format($debt['remaining_debt'], 2) ?> د.م</div>
                                                            </div>

                                                            <div class="mb-3">
                                                                <label class="form-label">تاريخ الدفع</label>
                                                                <input type="date" name="payment_date" class="form-control" required value="<?= date('Y-m-d') ?>">
                                                            </div>
                                                        </div>
                                                        <div class="modal-footer">
                                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                                                            <button type="submit" class="btn btn-primary">تسجيل الدفعة</button>
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Print Section -->
                                        <div id="printSection<?= $debt['debt_id'] ?>" class="d-none">
                                            <div class="print-section">
                                                <div class="print-header">
                                                    <h3>سجل الدفعات</h3>
                                                    <p>المشترك: <?= htmlspecialchars($debt['subscriber_name']) ?></p>
                                                    <p>رقم العداد: <?= htmlspecialchars($debt['meter_number']) ?></p>
                                                </div>
                                                
                                                <table class="print-table">
                                                    <thead>
                                                        <tr>
                                                            <th colspan="2">معلومات الدين</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <tr>
                                                            <td>مبلغ الاشتراك</td>
                                                            <td><?= number_format($debt['subscription_fee'], 2) ?> د.م</td>
                                                        </tr>
                                                        <tr>
                                                            <td>مبلغ التسبيق</td>
                                                            <td><?= number_format($debt['deposit_amount'], 2) ?> د.م</td>
                                                        </tr>
                                                        <tr>
                                                            <td>إجمالي الدين</td>
                                                            <td><?= number_format($debt['total_debt'], 2) ?> د.م</td>
                                                        </tr>
                                                        <tr>
                                                            <td>المبلغ المتبقي</td>
                                                            <td><?= number_format($debt['remaining_debt'], 2) ?> د.م</td>
                                                        </tr>
                                                        <tr>
                                                            <td>نسبة السداد</td>
                                                            <td><?= number_format($payment_percentage, 1) ?>%</td>
                                                        </tr>
                                                    </tbody>
                                                </table>

                                                <?php if (!empty($debt['payments'])): ?>
                                                    <table class="print-table">
                                                        <thead>
                                                            <tr>
                                                                <th>#</th>
                                                                <th>التاريخ</th>
                                                                <th>المبلغ</th>
                                                                <th>النسبة من إجمالي الدين</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php foreach ($debt['payments'] as $index => $payment): ?>
                                                                <tr>
                                                                    <td><?= $index + 1 ?></td>
                                                                    <td><?= date('Y-m-d', strtotime($payment['date'])) ?></td>
                                                                    <td><?= number_format($payment['amount'], 2) ?> د.م</td>
                                                                    <td><?= number_format(($payment['amount'] / $debt['total_debt']) * 100, 1) ?>%</td>
                                                                </tr>
                                                            <?php endforeach; ?>
                                                        </tbody>
                                                    </table>
                                                <?php else: ?>
                                                    <p class="text-center">لا توجد دفعات مسجلة</p>
                                                <?php endif; ?>

                                                <div class="print-footer">
                                                    <p>تاريخ الطباعة: <?= date('Y-m-d H:i') ?></p>
                                                </div>
                                            </div>
                                        </div>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function printPaymentHistory(debtId) {
            var printContent = document.getElementById('printSection' + debtId);
            var originalDisplay = printContent.style.display;
            
            printContent.classList.remove('d-none');
            window.print();
            printContent.classList.add('d-none');
        }
    </script>
</body>
</html>
