<?php
/**
 * إدارة الحسابات المالية (الكشفية) للمرضى
 * كل مريض له كشفية بمبلغ بالدينار العراقي
 */
$tenantCond = ' AND o.tenant_id = ' . (int)$tenantId;
$doctorCond = ' AND o.doctor_id = ' . (int)$doctorId;

$patientId = (int)($_GET['patient_id'] ?? 0);
$accountId = (int)($_GET['account_id'] ?? 0);
$action = $_GET['action'] ?? 'list';

$account = null;
$patient = null;
$transactions = [];
$invoices = [];
$payments = [];
$stats = [
    'total_balance' => 0,
    'total_debt' => 0,
    'total_credit' => 0,
    'pending_invoices' => 0,
    'overdue_invoices' => 0
];

// جلب معلومات الحساب
if ($accountId > 0) {
    try {
        $db->query('SELECT id FROM patient_accounts LIMIT 1');
        $stmt = $db->prepare('SELECT pa.*, p.full_name, p.patient_code, p.phone 
            FROM patient_accounts pa 
            JOIN patients p ON p.id = pa.patient_id 
            WHERE pa.id = ? AND pa.tenant_id = ?');
        $stmt->execute([$accountId, $tenantId]);
        $account = $stmt->fetch();
        if ($account) {
            $patientId = (int)$account['patient_id'];
        }
    } catch (Throwable $e) {}
}

// جلب معلومات المريض
if ($patientId > 0) {
    try {
        $tenantPat = '';
        try { $db->query('SELECT tenant_id FROM patients LIMIT 1'); $tenantPat = ' AND p.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
        $stmt = $db->prepare("SELECT p.* FROM patients p WHERE p.id = ? $tenantPat");
        $stmt->execute([$patientId]);
        $patient = $stmt->fetch();
        
        // جلب أو إنشاء الحساب
        if ($patient) {
            try {
                $db->query('SELECT id FROM patient_accounts LIMIT 1');
                $stmt = $db->prepare('SELECT * FROM patient_accounts WHERE patient_id = ? AND tenant_id = ?');
                $stmt->execute([$patientId, $tenantId]);
                $account = $stmt->fetch();
                
                if (!$account) {
                    // إنشاء حساب جديد تلقائياً
                    $stmt = $db->prepare('INSERT INTO patient_accounts (patient_id, tenant_id, account_balance, currency, created_by) VALUES (?, ?, 0.00, "IQD", ?)');
                    $stmt->execute([$patientId, $tenantId, $doctorAuth->accountId()]);
                    $accountId = (int)$db->lastInsertId();
                    $stmt = $db->prepare('SELECT * FROM patient_accounts WHERE id = ?');
                    $stmt->execute([$accountId]);
                    $account = $stmt->fetch();
                } else {
                    $accountId = (int)$account['id'];
                }
            } catch (Throwable $e) {}
        }
    } catch (Throwable $e) {}
}

// جلب المعاملات المالية
if ($accountId > 0) {
    try {
        $db->query('SELECT id FROM account_transactions LIMIT 1');
        $stmt = $db->prepare('SELECT t.*, u.username AS created_by_name 
            FROM account_transactions t 
            LEFT JOIN users u ON u.id = t.created_by 
            WHERE t.account_id = ? 
            ORDER BY t.created_at DESC 
            LIMIT 100');
        $stmt->execute([$accountId]);
        $transactions = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    // جلب الفواتير
    try {
        $db->query('SELECT id FROM account_invoices LIMIT 1');
        $stmt = $db->prepare('SELECT * FROM account_invoices WHERE account_id = ? ORDER BY invoice_date DESC LIMIT 50');
        $stmt->execute([$accountId]);
        $invoices = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    // جلب الدفعات
    try {
        $db->query('SELECT id FROM account_payments LIMIT 1');
        $stmt = $db->prepare('SELECT p.*, u.username AS created_by_name 
            FROM account_payments p 
            LEFT JOIN users u ON u.id = p.created_by 
            WHERE p.account_id = ? 
            ORDER BY p.payment_date DESC 
            LIMIT 50');
        $stmt->execute([$accountId]);
        $payments = $stmt->fetchAll();
    } catch (Throwable $e) {}
}

// إحصائيات عامة
try {
    $db->query('SELECT id FROM patient_accounts LIMIT 1');
    $stmt = $db->prepare("SELECT 
        SUM(CASE WHEN account_balance > 0 THEN account_balance ELSE 0 END) AS total_credit,
        SUM(CASE WHEN account_balance < 0 THEN ABS(account_balance) ELSE 0 END) AS total_debt,
        SUM(account_balance) AS total_balance
        FROM patient_accounts pa
        JOIN patients p ON p.id = pa.patient_id
        WHERE pa.tenant_id = ? 
        AND EXISTS (SELECT 1 FROM lab_orders o WHERE o.patient_id = p.id $tenantCond $doctorCond)");
    $stmt->execute([$tenantId]);
    $row = $stmt->fetch();
    if ($row) {
        $stats['total_credit'] = (float)($row['total_credit'] ?? 0);
        $stats['total_debt'] = (float)($row['total_debt'] ?? 0);
        $stats['total_balance'] = (float)($row['total_balance'] ?? 0);
    }
    
    // الفواتير المعلقة
    try {
        $db->query('SELECT id FROM account_invoices LIMIT 1');
        $stmt = $db->prepare("SELECT COUNT(*) FROM account_invoices ai
            JOIN patient_accounts pa ON pa.id = ai.account_id
            JOIN patients p ON p.id = pa.patient_id
            WHERE ai.status IN ('pending', 'partial') 
            AND pa.tenant_id = ?
            AND EXISTS (SELECT 1 FROM lab_orders o WHERE o.patient_id = p.id $tenantCond $doctorCond)");
        $stmt->execute([$tenantId]);
        $stats['pending_invoices'] = (int)$stmt->fetchColumn();
        
        $stmt = $db->prepare("SELECT COUNT(*) FROM account_invoices ai
            JOIN patient_accounts pa ON pa.id = ai.account_id
            JOIN patients p ON p.id = pa.patient_id
            WHERE ai.status = 'overdue' 
            AND pa.tenant_id = ?
            AND EXISTS (SELECT 1 FROM lab_orders o WHERE o.patient_id = p.id $tenantCond $doctorCond)");
        $stmt->execute([$tenantId]);
        $stats['overdue_invoices'] = (int)$stmt->fetchColumn();
    } catch (Throwable $e) {}
} catch (Throwable $e) {}

// قائمة المرضى مع حساباتهم
$patientsWithAccounts = [];
try {
    $db->query('SELECT id FROM patient_accounts LIMIT 1');
    $stmt = $db->prepare("SELECT pa.*, p.full_name, p.patient_code, p.phone,
        (SELECT COUNT(*) FROM account_invoices ai WHERE ai.account_id = pa.id AND ai.status IN ('pending', 'partial')) AS pending_invoices_count,
        (SELECT SUM(remaining_amount) FROM account_invoices ai WHERE ai.account_id = pa.id AND ai.status IN ('pending', 'partial')) AS total_pending
        FROM patient_accounts pa
        JOIN patients p ON p.id = pa.patient_id
        WHERE pa.tenant_id = ?
        AND EXISTS (SELECT 1 FROM lab_orders o WHERE o.patient_id = p.id $tenantCond $doctorCond)
        ORDER BY pa.account_balance ASC, p.full_name
        LIMIT 200");
    $stmt->execute([$tenantId]);
    $patientsWithAccounts = $stmt->fetchAll();
} catch (Throwable $e) {
    // إذا لم تكن الجداول موجودة، نعرض رسالة
}

$transactionTypes = [
    'deposit' => 'إيداع',
    'withdrawal' => 'سحب',
    'payment' => 'دفعة',
    'refund' => 'استرداد',
    'adjustment' => 'تسوية',
    'invoice' => 'فاتورة',
    'discount' => 'خصم'
];

$paymentMethods = [
    'cash' => 'نقدي',
    'card' => 'بطاقة',
    'transfer' => 'تحويل',
    'check' => 'شيك',
    'other' => 'أخرى'
];

$statusLabels = [
    'active' => 'نشط',
    'suspended' => 'معلق',
    'closed' => 'مغلق'
];

$invoiceStatusLabels = [
    'pending' => 'معلق',
    'partial' => 'جزئي',
    'paid' => 'مدفوع',
    'overdue' => 'متأخر',
    'cancelled' => 'ملغي'
];
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/svg+xml" href="favicon.svg">
    <title>الحسابات المالية - Smart Doctor</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="doctor.css">
</head>
<body>
<?php include __DIR__ . '/_layout.php'; ?>
<main class="content doctor-accounts-page">
    <div class="page-header" style="margin-bottom:24px;">
        <div>
            <h1 style="margin:0 0 8px;">💰 الحسابات المالية (الكشفية)</h1>
            <p style="color:var(--text-muted);margin:0;">إدارة حسابات المرضى المالية بالدينار العراقي</p>
        </div>
        <div style="display:flex;gap:12px;flex-wrap:wrap;">
            <a href="doctor.php?page=patients" class="btn-secondary">👥 المرضى</a>
            <button type="button" onclick="document.getElementById('createAccountModal').classList.add('show')" class="btn-primary">
                ➕ إنشاء كشفية جديدة
            </button>
        </div>
    </div>

    <?php if (isset($_SESSION['doctor_account_msg'])): ?>
    <div class="alert alert-success"><?php echo htmlspecialchars($_SESSION['doctor_account_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['doctor_account_msg']); ?></div>
    <?php endif; ?>
    <?php if (isset($_SESSION['doctor_account_error'])): ?>
    <div class="alert alert-danger"><?php echo htmlspecialchars($_SESSION['doctor_account_error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['doctor_account_error']); ?></div>
    <?php endif; ?>

    <!-- إحصائيات عامة -->
    <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:16px;margin-bottom:24px;">
        <div class="card" style="border-right:4px solid #22c55e;background:linear-gradient(135deg, #f0fdf4 0%, #ffffff 100%);">
            <div style="display:flex;align-items:center;gap:12px;">
                <div style="width:48px;height:48px;border-radius:12px;background:#22c55e;display:flex;align-items:center;justify-content:center;font-size:1.5rem;">
                    💰
                </div>
                <div>
                    <div style="font-size:1.5rem;font-weight:bold;color:#22c55e;line-height:1;">
                        <?php echo number_format($stats['total_balance'], 2); ?>
                    </div>
                    <div style="color:var(--text-muted);font-size:0.85rem;margin-top:4px;">الرصيد الإجمالي (د.ع)</div>
                </div>
            </div>
        </div>

        <div class="card" style="border-right:4px solid #dc2626;background:linear-gradient(135deg, #fef2f2 0%, #ffffff 100%);">
            <div style="display:flex;align-items:center;gap:12px;">
                <div style="width:48px;height:48px;border-radius:12px;background:#dc2626;display:flex;align-items:center;justify-content:center;font-size:1.5rem;">
                    📉
                </div>
                <div>
                    <div style="font-size:1.5rem;font-weight:bold;color:#dc2626;line-height:1;">
                        <?php echo number_format($stats['total_debt'], 2); ?>
                    </div>
                    <div style="color:var(--text-muted);font-size:0.85rem;margin-top:4px;">إجمالي الديون (د.ع)</div>
                </div>
            </div>
        </div>

        <div class="card" style="border-right:4px solid #3b82f6;background:linear-gradient(135deg, #eff6ff 0%, #ffffff 100%);">
            <div style="display:flex;align-items:center;gap:12px;">
                <div style="width:48px;height:48px;border-radius:12px;background:#3b82f6;display:flex;align-items:center;justify-content:center;font-size:1.5rem;">
                    📋
                </div>
                <div>
                    <div style="font-size:1.5rem;font-weight:bold;color:#3b82f6;line-height:1;">
                        <?php echo number_format($stats['pending_invoices']); ?>
                    </div>
                    <div style="color:var(--text-muted);font-size:0.85rem;margin-top:4px;">فواتير معلقة</div>
                </div>
            </div>
        </div>

        <div class="card" style="border-right:4px solid #f59e0b;background:linear-gradient(135deg, #fffbeb 0%, #ffffff 100%);">
            <div style="display:flex;align-items:center;gap:12px;">
                <div style="width:48px;height:48px;border-radius:12px;background:#f59e0b;display:flex;align-items:center;justify-content:center;font-size:1.5rem;">
                    ⚠️
                </div>
                <div>
                    <div style="font-size:1.5rem;font-weight:bold;color:#f59e0b;line-height:1;">
                        <?php echo number_format($stats['overdue_invoices']); ?>
                    </div>
                    <div style="color:var(--text-muted);font-size:0.85rem;margin-top:4px;">فواتير متأخرة</div>
                </div>
            </div>
        </div>
    </div>

    <?php if ($account && $patient): ?>
    <!-- عرض حساب مريض محدد -->
    <div class="card" style="margin-bottom:24px;background:linear-gradient(135deg, #0f172a 0%, #1e3a5f 100%);color:white;border:none;">
        <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:16px;">
            <div>
                <h2 style="margin:0 0 8px;color:white;font-size:1.5rem;">
                    <?php echo htmlspecialchars($patient['full_name'], ENT_QUOTES, 'UTF-8'); ?>
                </h2>
                <div style="display:flex;gap:16px;flex-wrap:wrap;font-size:0.9rem;color:rgba(255,255,255,0.8);">
                    <span>الكود: <?php echo htmlspecialchars($patient['patient_code'], ENT_QUOTES, 'UTF-8'); ?></span>
                    <?php if (!empty($patient['phone'])): ?>
                    <span>📞 <?php echo htmlspecialchars($patient['phone'], ENT_QUOTES, 'UTF-8'); ?></span>
                    <?php endif; ?>
                    <span>الحالة: <?php echo $statusLabels[$account['account_status']] ?? $account['account_status']; ?></span>
                </div>
            </div>
            <div style="text-align:left;">
                <div style="font-size:2.5rem;font-weight:bold;color:<?php echo $account['account_balance'] >= 0 ? '#22c55e' : '#dc2626'; ?>;line-height:1;">
                    <?php echo number_format($account['account_balance'], 2); ?>
                </div>
                <div style="color:rgba(255,255,255,0.8);font-size:0.9rem;margin-top:4px;">دينار عراقي</div>
            </div>
        </div>
    </div>

    <!-- إجراءات سريعة -->
    <div class="card" style="margin-bottom:24px;">
        <h3 style="margin-top:0;display:flex;align-items:center;gap:8px;">
            <span>⚡</span> إجراءات سريعة
        </h3>
        <div style="display:flex;gap:12px;flex-wrap:wrap;">
            <button type="button" onclick="document.getElementById('addPaymentModal').classList.add('show')" class="btn-primary">
                💰 إضافة دفعة
            </button>
            <button type="button" onclick="document.getElementById('addTransactionModal').classList.add('show')" class="btn-secondary">
                ➕ معاملة مالية
            </button>
            <button type="button" onclick="document.getElementById('adjustBalanceModal').classList.add('show')" class="btn-secondary">
                🔧 تسوية الرصيد
            </button>
            <a href="doctor.php?page=results&patient_id=<?php echo (int)$patientId; ?>" class="btn-secondary">
                📋 نتائج المريض
            </a>
            <a href="doctor.php?page=accounts&patient_id=<?php echo (int)$patientId; ?>&export=statement" class="btn-secondary" target="_blank">
                📄 كشف حساب
            </a>
        </div>
    </div>

    <!-- ملخص الحساب -->
    <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:16px;margin-bottom:24px;">
        <div class="card" style="border-right:4px solid #22c55e;">
            <div style="font-size:0.85rem;color:var(--text-muted);margin-bottom:8px;">الرصيد الحالي</div>
            <div style="font-size:1.8rem;font-weight:bold;color:<?php echo $account['account_balance'] >= 0 ? '#22c55e' : '#dc2626'; ?>;">
                <?php echo number_format($account['account_balance'], 2); ?> د.ع
            </div>
        </div>
        <div class="card" style="border-right:4px solid #3b82f6;">
            <div style="font-size:0.85rem;color:var(--text-muted);margin-bottom:8px;">الفواتير المعلقة</div>
            <div style="font-size:1.8rem;font-weight:bold;color:#3b82f6;">
                <?php echo count(array_filter($invoices, function($i) { return in_array($i['status'], ['pending', 'partial']); })); ?>
            </div>
        </div>
        <div class="card" style="border-right:4px solid #f59e0b;">
            <div style="font-size:0.85rem;color:var(--text-muted);margin-bottom:8px;">إجمالي المدفوع</div>
            <div style="font-size:1.8rem;font-weight:bold;color:#f59e0b;">
                <?php echo number_format(array_sum(array_column($payments, 'amount')), 2); ?> د.ع
            </div>
        </div>
        <div class="card" style="border-right:4px solid #8b5cf6;">
            <div style="font-size:0.85rem;color:var(--text-muted);margin-bottom:8px;">عدد المعاملات</div>
            <div style="font-size:1.8rem;font-weight:bold;color:#8b5cf6;">
                <?php echo count($transactions); ?>
            </div>
        </div>
    </div>

    <!-- الفواتير -->
    <?php if (!empty($invoices)): ?>
    <div class="card" style="margin-bottom:24px;">
        <h3 style="margin-top:0;display:flex;align-items:center;gap:8px;">
            <span>📋</span> الفواتير
        </h3>
        <div class="table-wrapper">
            <table class="table">
                <thead>
                    <tr>
                        <th>رقم الفاتورة</th>
                        <th>التاريخ</th>
                        <th>المبلغ الإجمالي</th>
                        <th>المدفوع</th>
                        <th>المتبقي</th>
                        <th>الحالة</th>
                        <th>إجراء</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($invoices as $inv): ?>
                <tr>
                    <td><?php echo htmlspecialchars($inv['invoice_number'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo date('Y-m-d', strtotime($inv['invoice_date'])); ?></td>
                    <td><strong><?php echo number_format($inv['total_amount'], 2); ?> د.ع</strong></td>
                    <td><?php echo number_format($inv['paid_amount'], 2); ?> د.ع</td>
                    <td><strong style="color:<?php echo $inv['remaining_amount'] > 0 ? '#dc2626' : '#22c55e'; ?>">
                        <?php echo number_format($inv['remaining_amount'], 2); ?> د.ع
                    </strong></td>
                    <td>
                        <span style="padding:4px 10px;background:<?php 
                            echo $inv['status'] === 'paid' ? '#22c55e' : 
                                ($inv['status'] === 'overdue' ? '#dc2626' : 
                                ($inv['status'] === 'partial' ? '#f59e0b' : '#6b7280')); ?>20;
                            color:<?php 
                            echo $inv['status'] === 'paid' ? '#22c55e' : 
                                ($inv['status'] === 'overdue' ? '#dc2626' : 
                                ($inv['status'] === 'partial' ? '#f59e0b' : '#6b7280')); ?>;
                            border-radius:12px;font-size:0.85rem;font-weight:500;">
                            <?php echo $invoiceStatusLabels[$inv['status']] ?? $inv['status']; ?>
                        </span>
                    </td>
                    <td>
                        <?php if ($inv['remaining_amount'] > 0): ?>
                        <button type="button" onclick="addPaymentForInvoice(<?php echo (int)$inv['id']; ?>, <?php echo $inv['remaining_amount']; ?>)" class="btn-primary btn-sm">
                            💰 دفع
                        </button>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <!-- المعاملات المالية -->
    <div class="card" style="margin-bottom:24px;">
        <h3 style="margin-top:0;display:flex;align-items:center;gap:8px;">
            <span>📊</span> سجل المعاملات المالية
        </h3>
        <div class="table-wrapper" style="max-height:500px;overflow-y:auto;">
            <table class="table">
                <thead style="position:sticky;top:0;background:var(--bg-card);z-index:10;">
                    <tr>
                        <th>التاريخ</th>
                        <th>النوع</th>
                        <th>المبلغ</th>
                        <th>الرصيد قبل</th>
                        <th>الرصيد بعد</th>
                        <th>الوصف</th>
                        <th>طريقة الدفع</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($transactions)): ?>
                <tr>
                    <td colspan="7" style="text-align:center;padding:40px;color:var(--text-muted);">
                        لا توجد معاملات مالية
                    </td>
                </tr>
                <?php else: ?>
                <?php foreach ($transactions as $t): ?>
                <tr>
                    <td><?php echo date('Y-m-d H:i', strtotime($t['created_at'])); ?></td>
                    <td>
                        <span style="padding:4px 10px;background:var(--bg-secondary);border-radius:12px;font-size:0.85rem;">
                            <?php echo $transactionTypes[$t['transaction_type']] ?? $t['transaction_type']; ?>
                        </span>
                    </td>
                    <td>
                        <strong style="color:<?php echo in_array($t['transaction_type'], ['deposit', 'payment', 'refund']) ? '#22c55e' : '#dc2626'; ?>">
                            <?php echo in_array($t['transaction_type'], ['deposit', 'payment', 'refund']) ? '+' : '-'; ?>
                            <?php echo number_format($t['amount'], 2); ?> د.ع
                        </strong>
                    </td>
                    <td><?php echo number_format($t['balance_before'], 2); ?> د.ع</td>
                    <td><strong><?php echo number_format($t['balance_after'], 2); ?> د.ع</strong></td>
                    <td><?php echo htmlspecialchars($t['description'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo $t['payment_method'] ? ($paymentMethods[$t['payment_method']] ?? $t['payment_method']) : '-'; ?></td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <?php else: ?>
    <!-- قائمة المرضى مع حساباتهم -->
    <div class="card">
        <h3 style="margin-top:0;display:flex;align-items:center;gap:8px;">
            <span>👥</span> قائمة المرضى مع حساباتهم المالية
        </h3>
        <?php if (empty($patientsWithAccounts)): ?>
        <div style="text-align:center;padding:60px 24px;">
            <div style="font-size:4rem;margin-bottom:20px;opacity:0.3;">💰</div>
            <h3 style="margin:0 0 12px;color:var(--text-primary);">لا توجد حسابات مالية</h3>
            <p style="color:var(--text-muted);margin:0;">
                سيتم إنشاء حسابات تلقائياً عند فتح حساب لأي مريض
            </p>
        </div>
        <?php else: ?>
        <div class="table-wrapper">
            <table class="table">
                <thead>
                    <tr>
                        <th>المريض</th>
                        <th>الكود</th>
                        <th>الرصيد</th>
                        <th>الفواتير المعلقة</th>
                        <th>الحالة</th>
                        <th>إجراء</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($patientsWithAccounts as $pa): ?>
                <tr style="<?php echo $pa['account_balance'] < 0 ? 'background:rgba(220,38,38,0.05);' : ''; ?>">
                    <td>
                        <a href="doctor.php?page=accounts&patient_id=<?php echo (int)$pa['patient_id']; ?>" style="font-weight:600;color:var(--text-primary);text-decoration:none;">
                            <?php echo htmlspecialchars($pa['full_name'], ENT_QUOTES, 'UTF-8'); ?>
                        </a>
                    </td>
                    <td><?php echo htmlspecialchars($pa['patient_code'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td>
                        <strong style="color:<?php echo $pa['account_balance'] >= 0 ? '#22c55e' : '#dc2626'; ?>;font-size:1.1rem;">
                            <?php echo number_format($pa['account_balance'], 2); ?> د.ع
                        </strong>
                    </td>
                    <td>
                        <?php if ((int)($pa['pending_invoices_count'] ?? 0) > 0): ?>
                        <span style="padding:4px 10px;background:#f59e0b;color:white;border-radius:12px;font-size:0.85rem;font-weight:600;">
                            <?php echo (int)$pa['pending_invoices_count']; ?> فاتورة
                        </span>
                        <div style="font-size:0.85rem;color:var(--text-muted);margin-top:4px;">
                            <?php echo number_format((float)($pa['total_pending'] ?? 0), 2); ?> د.ع
                        </div>
                        <?php else: ?>
                        <span style="color:var(--text-muted);">-</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span style="padding:4px 10px;background:<?php 
                            echo $pa['account_status'] === 'active' ? '#22c55e' : 
                                ($pa['account_status'] === 'suspended' ? '#f59e0b' : '#6b7280'); ?>20;
                            color:<?php 
                            echo $pa['account_status'] === 'active' ? '#22c55e' : 
                                ($pa['account_status'] === 'suspended' ? '#f59e0b' : '#6b7280'); ?>;
                            border-radius:12px;font-size:0.85rem;font-weight:500;">
                            <?php echo $statusLabels[$pa['account_status']] ?? $pa['account_status']; ?>
                        </span>
                    </td>
                    <td>
                        <a href="doctor.php?page=accounts&patient_id=<?php echo (int)$pa['patient_id']; ?>" class="btn-primary btn-sm">
                            عرض الحساب
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</main>

<!-- Modal: إضافة دفعة -->
<div id="addPaymentModal" class="doctor-modal-overlay" onclick="if(event.target===this)this.classList.remove('show')">
    <div class="doctor-modal" onclick="event.stopPropagation()">
        <div class="doctor-modal-header">
            <h3>💰 إضافة دفعة</h3>
            <button type="button" onclick="document.getElementById('addPaymentModal').classList.remove('show')" style="background:transparent;border:none;font-size:1.5rem;cursor:pointer;">&times;</button>
        </div>
        <form method="post" action="doctor.php?page=accounts&action=add_payment" class="doctor-modal-body">
            <input type="hidden" name="account_id" value="<?php echo (int)$accountId; ?>">
            <div class="form-group">
                <label>المبلغ (دينار عراقي) <span class="required">*</span></label>
                <input type="number" name="amount" step="0.01" min="0.01" required placeholder="0.00" style="font-size:1.2rem;font-weight:600;">
            </div>
            <div class="form-group">
                <label>طريقة الدفع <span class="required">*</span></label>
                <select name="payment_method" required>
                    <option value="cash">نقدي</option>
                    <option value="card">بطاقة</option>
                    <option value="transfer">تحويل</option>
                    <option value="check">شيك</option>
                    <option value="other">أخرى</option>
                </select>
            </div>
            <div class="form-group">
                <label>رقم الإيصال</label>
                <input type="text" name="receipt_number" placeholder="رقم الإيصال (اختياري)">
            </div>
            <div class="form-group">
                <label>ملاحظات</label>
                <textarea name="notes" rows="3" placeholder="ملاحظات إضافية (اختياري)"></textarea>
            </div>
            <div class="doctor-modal-footer">
                <button type="submit" class="btn-primary">حفظ الدفعة</button>
                <button type="button" onclick="document.getElementById('addPaymentModal').classList.remove('show')" class="btn-secondary">إلغاء</button>
            </div>
        </form>
    </div>
</div>

<!-- Modal: معاملة مالية -->
<div id="addTransactionModal" class="doctor-modal-overlay" onclick="if(event.target===this)this.classList.remove('show')">
    <div class="doctor-modal" onclick="event.stopPropagation()">
        <div class="doctor-modal-header">
            <h3>➕ معاملة مالية</h3>
            <button type="button" onclick="document.getElementById('addTransactionModal').classList.remove('show')" style="background:transparent;border:none;font-size:1.5rem;cursor:pointer;">&times;</button>
        </div>
        <form method="post" action="doctor.php?page=accounts&action=add_transaction" class="doctor-modal-body">
            <input type="hidden" name="account_id" value="<?php echo (int)$accountId; ?>">
            <div class="form-group">
                <label>نوع المعاملة <span class="required">*</span></label>
                <select name="transaction_type" required>
                    <option value="deposit">إيداع</option>
                    <option value="withdrawal">سحب</option>
                    <option value="refund">استرداد</option>
                    <option value="adjustment">تسوية</option>
                    <option value="discount">خصم</option>
                </select>
            </div>
            <div class="form-group">
                <label>المبلغ (دينار عراقي) <span class="required">*</span></label>
                <input type="number" name="amount" step="0.01" min="0.01" required placeholder="0.00">
            </div>
            <div class="form-group">
                <label>الوصف</label>
                <textarea name="description" rows="3" placeholder="وصف المعاملة"></textarea>
            </div>
            <div class="doctor-modal-footer">
                <button type="submit" class="btn-primary">حفظ المعاملة</button>
                <button type="button" onclick="document.getElementById('addTransactionModal').classList.remove('show')" class="btn-secondary">إلغاء</button>
            </div>
        </form>
    </div>
</div>

<!-- Modal: تسوية الرصيد -->
<div id="adjustBalanceModal" class="doctor-modal-overlay" onclick="if(event.target===this)this.classList.remove('show')">
    <div class="doctor-modal" onclick="event.stopPropagation()">
        <div class="doctor-modal-header">
            <h3>🔧 تسوية الرصيد</h3>
            <button type="button" onclick="document.getElementById('adjustBalanceModal').classList.remove('show')" style="background:transparent;border:none;font-size:1.5rem;cursor:pointer;">&times;</button>
        </div>
        <form method="post" action="doctor.php?page=accounts&action=adjust_balance" class="doctor-modal-body">
            <input type="hidden" name="account_id" value="<?php echo (int)$accountId; ?>">
            <div class="alert alert-warning" style="margin-bottom:16px;">
                ⚠️ الرصيد الحالي: <strong><?php echo number_format($account['account_balance'] ?? 0, 2); ?> د.ع</strong>
            </div>
            <div class="form-group">
                <label>الرصيد الجديد (دينار عراقي) <span class="required">*</span></label>
                <input type="number" name="new_balance" step="0.01" value="<?php echo number_format($account['account_balance'] ?? 0, 2, '.', ''); ?>" required>
            </div>
            <div class="form-group">
                <label>سبب التسوية <span class="required">*</span></label>
                <textarea name="description" rows="3" required placeholder="سبب تعديل الرصيد"></textarea>
            </div>
            <div class="doctor-modal-footer">
                <button type="submit" class="btn-primary">تسوية الرصيد</button>
                <button type="button" onclick="document.getElementById('adjustBalanceModal').classList.remove('show')" class="btn-secondary">إلغاء</button>
            </div>
        </form>
    </div>
</div>

<script>
function addPaymentForInvoice(invoiceId, amount) {
    document.getElementById('addPaymentModal').classList.add('show');
    var form = document.querySelector('#addPaymentModal form');
    if (form) {
        var hiddenInput = document.createElement('input');
        hiddenInput.type = 'hidden';
        hiddenInput.name = 'invoice_id';
        hiddenInput.value = invoiceId;
        form.appendChild(hiddenInput);
        form.querySelector('input[name="amount"]').value = amount.toFixed(2);
    }
}

// إغلاق الـ Modals عند الضغط على Esc
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        document.querySelectorAll('.doctor-modal-overlay.show').forEach(function(modal) {
            modal.classList.remove('show');
        });
    }
});
</script>

<!-- Modal: إنشاء كشفية جديدة -->
<div id="createAccountModal" class="doctor-modal-overlay" onclick="if(event.target===this)this.classList.remove('show')">
    <div class="doctor-modal" onclick="event.stopPropagation()" style="max-width:600px;">
        <div class="doctor-modal-header">
            <h3>➕ إنشاء كشفية جديدة لمريض</h3>
            <button type="button" onclick="document.getElementById('createAccountModal').classList.remove('show')" style="background:transparent;border:none;font-size:1.5rem;cursor:pointer;">&times;</button>
        </div>
        <form method="post" action="doctor.php?page=accounts&action=create_account" class="doctor-modal-body">
            <div class="form-group">
                <label>اختر المريض <span class="required">*</span></label>
                <select name="patient_id" required style="width:100%;">
                    <option value="">-- اختر مريض --</option>
                    <?php
                    // جلب قائمة المرضى الذين ليس لديهم حساب
                    try {
                        $stmt = $db->prepare("SELECT p.id, p.full_name, p.patient_code 
                            FROM patients p
                            WHERE p.tenant_id = ?
                            AND EXISTS (SELECT 1 FROM lab_orders o WHERE o.patient_id = p.id $tenantCond $doctorCond)
                            AND NOT EXISTS (SELECT 1 FROM patient_accounts pa WHERE pa.patient_id = p.id AND pa.tenant_id = ?)
                            ORDER BY p.full_name
                            LIMIT 100");
                        $stmt->execute([$tenantId, $tenantId]);
                        $patientsWithoutAccount = $stmt->fetchAll();
                        foreach ($patientsWithoutAccount as $pwa) {
                            echo '<option value="' . (int)$pwa['id'] . '">' . htmlspecialchars($pwa['full_name'] . ' (' . $pwa['patient_code'] . ')', ENT_QUOTES, 'UTF-8') . '</option>';
                        }
                    } catch (Throwable $e) {}
                    ?>
                </select>
                <small style="color:var(--text-muted);margin-top:4px;display:block;">
                    💡 إذا لم يظهر المريض في القائمة، فربما لديه حساب مالي بالفعل. يمكنك البحث عنه في القائمة أعلاه.
                </small>
            </div>
            <div class="form-group">
                <label>الرصيد الابتدائي (دينار عراقي)</label>
                <input type="number" name="initial_balance" step="0.01" value="0.00" placeholder="0.00">
                <small style="color:var(--text-muted);margin-top:4px;display:block;">
                    يمكنك ترك الرصيد صفراً وستتم إضافة المبالغ لاحقاً
                </small>
            </div>
            <div class="form-group">
                <label>ملاحظات (اختياري)</label>
                <textarea name="notes" rows="3" placeholder="ملاحظات على الحساب"></textarea>
            </div>
            <div class="doctor-modal-footer">
                <button type="submit" class="btn-primary">إنشاء الكشفية</button>
                <button type="button" onclick="document.getElementById('createAccountModal').classList.remove('show')" class="btn-secondary">إلغاء</button>
            </div>
        </form>
    </div>
</div>
</body>
</html>
