<?php

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

$action = $_GET['action'] ?? 'index';
$tenantId = Tenant::id();

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

// معالجة الحذف
if ($action === 'delete' && isset($_GET['id'])) {
    if (!($auth instanceof Auth) || !$auth->can('doctors.delete')) {
        http_response_code(403);
        echo 'غير مسموح بحذف الأطباء';
        return;
    }
    $delId = (int)$_GET['id'];
    if ($delId > 0) {
        try {
            $stmt = $db->prepare('SELECT id FROM doctors WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$delId, $tenantId]);
            $doctor = $stmt->fetch();
        } catch (Throwable $e) {
            try {
                $stmt = $db->prepare('SELECT id FROM doctors WHERE id = ?');
                $stmt->execute([$delId]);
                $doctor = $stmt->fetch();
            } catch (Throwable $e2) {
                $doctor = false;
            }
        }
        
        if ($doctor) {
            // التحقق من وجود طلبات مرتبطة
            $orderCount = 0;
            try {
                $stmt = $db->prepare('SELECT COUNT(*) FROM lab_orders WHERE doctor_id = ?');
                $stmt->execute([$delId]);
                $orderCount = (int)$stmt->fetchColumn();
            } catch (Throwable $e) {}
            
            if ($orderCount > 0) {
                $_SESSION['doctors_error'] = 'لا يمكن حذف الطبيب لأنه مرتبط بـ ' . $orderCount . ' طلب. يمكنك تعديل بياناته بدلاً من ذلك.';
                header('Location: index.php?page=doctors&action=view&id=' . $delId);
                exit;
            }
            
            // حذف الطبيب
            try {
                $stmt = $db->prepare('DELETE FROM doctors WHERE id = ? AND tenant_id = ?');
                $stmt->execute([$delId, $tenantId]);
            } catch (Throwable $e) {
                try {
                    $stmt = $db->prepare('DELETE FROM doctors WHERE id = ?');
                    $stmt->execute([$delId]);
                } catch (Throwable $e2) {}
            }
            
            if (isset($auditLog)) {
                $auditLog->log(
                    'doctor_deleted',
                    'doctor',
                    $delId,
                    json_encode(['id' => $delId], JSON_UNESCAPED_UNICODE),
                    null,
                    $_SESSION['user_id'] ?? null
                );
            }
            $_SESSION['doctors_msg'] = 'تم حذف الطبيب بنجاح';
        }
    }
    header('Location: index.php?page=doctors');
    exit;
}

// معالجة التعديل
if ($action === 'edit' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!($auth instanceof Auth) || !$auth->can('doctors.update')) {
        http_response_code(403);
        echo 'غير مسموح بتعديل الأطباء';
        return;
    }
    $editId = (int)($_POST['id'] ?? 0);
    if ($editId > 0) {
        try {
            $stmt = $db->prepare('SELECT * FROM doctors WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$editId, $tenantId]);
            $editDoctor = $stmt->fetch();
        } catch (Throwable $e) {
            try {
                $stmt = $db->prepare('SELECT * FROM doctors WHERE id = ?');
                $stmt->execute([$editId]);
                $editDoctor = $stmt->fetch();
            } catch (Throwable $e2) {
                $editDoctor = false;
            }
        }
        
        if ($editDoctor) {
            $fullName = trim($_POST['full_name'] ?? '');
            $specialty = trim($_POST['specialty'] ?? '');
            $phone = trim($_POST['phone'] ?? '');
            $clinic = trim($_POST['clinic_name'] ?? '');
            
            if ($fullName !== '') {
                try {
                    $stmt = $db->prepare(
                        'UPDATE doctors 
                         SET full_name = :name, specialty = :spec, phone = :phone, clinic_name = :clinic 
                         WHERE id = :id AND tenant_id = :tid'
                    );
                    $stmt->execute([
                        'name' => $fullName,
                        'spec' => $specialty !== '' ? $specialty : null,
                        'phone' => $phone !== '' ? $phone : null,
                        'clinic' => $clinic !== '' ? $clinic : null,
                        'id' => $editId,
                        'tid' => $tenantId
                    ]);
                } catch (Throwable $e) {
                    try {
                        $stmt = $db->prepare(
                            'UPDATE doctors 
                             SET full_name = :name, specialty = :spec, phone = :phone, clinic_name = :clinic 
                             WHERE id = :id'
                        );
                        $stmt->execute([
                            'name' => $fullName,
                            'spec' => $specialty !== '' ? $specialty : null,
                            'phone' => $phone !== '' ? $phone : null,
                            'clinic' => $clinic !== '' ? $clinic : null,
                            'id' => $editId
                        ]);
                    } catch (Throwable $e2) {}
                }
                
                if (isset($auditLog)) {
                    $auditLog->log(
                        'doctor_updated',
                        'doctor',
                        $editId,
                        json_encode([
                            'full_name' => $editDoctor['full_name'],
                            'specialty' => $editDoctor['specialty'] ?? '',
                            'phone' => $editDoctor['phone'] ?? ''
                        ], JSON_UNESCAPED_UNICODE),
                        json_encode([
                            'full_name' => $fullName,
                            'specialty' => $specialty,
                            'phone' => $phone
                        ], JSON_UNESCAPED_UNICODE),
                        $_SESSION['user_id'] ?? null
                    );
                }
                $_SESSION['doctors_msg'] = 'تم تحديث بيانات الطبيب بنجاح';
            }
        }
    }
    header('Location: index.php?page=doctors&action=view&id=' . $editId);
    exit;
}

// معالجة الإضافة
if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!($auth instanceof Auth) || !$auth->can('doctors.create')) {
        http_response_code(403);
        echo 'غير مسموح بإضافة الأطباء';
        return;
    }
    $fullName = trim($_POST['full_name'] ?? '');
    $specialty = trim($_POST['specialty'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $clinic = trim($_POST['clinic_name'] ?? '');

    if ($fullName !== '') {
        try {
            $stmt = $db->prepare('INSERT INTO doctors (full_name, specialty, phone, clinic_name, tenant_id) VALUES (:name, :spec, :phone, :clinic, :tid)');
            $stmt->execute([
                'name' => $fullName,
                'spec' => $specialty !== '' ? $specialty : null,
                'phone' => $phone !== '' ? $phone : null,
                'clinic' => $clinic !== '' ? $clinic : null,
                'tid' => $tenantId
            ]);
        } catch (Throwable $ex) {
            $stmt = $db->prepare('INSERT INTO doctors (full_name, specialty, phone, clinic_name) VALUES (:name, :spec, :phone, :clinic)');
            $stmt->execute([
                'name' => $fullName,
                'spec' => $specialty !== '' ? $specialty : null,
                'phone' => $phone !== '' ? $phone : null,
                'clinic' => $clinic !== '' ? $clinic : null
            ]);
        }
        if (isset($auditLog)) {
            $auditLog->log(
                'doctor_created',
                'doctor',
                (int)$db->lastInsertId(),
                null,
                json_encode([
                    'full_name' => $fullName,
                    'specialty' => $specialty,
                    'phone' => $phone
                ], JSON_UNESCAPED_UNICODE),
                $_SESSION['user_id'] ?? null
            );
        }
        $_SESSION['doctors_msg'] = 'تم إضافة الطبيب بنجاح';
    }

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

// صفحة عرض التفاصيل
$viewId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($viewId > 0 && ($action === 'view' || $action === 'profile')) {
    try {
        $stmt = $db->prepare('SELECT * FROM doctors WHERE id = ? AND tenant_id = ?');
        $stmt->execute([$viewId, $tenantId]);
        $doctor = $stmt->fetch();
    } catch (Throwable $e) {
        try {
            $stmt = $db->prepare('SELECT * FROM doctors WHERE id = ?');
            $stmt->execute([$viewId]);
            $doctor = $stmt->fetch();
        } catch (Throwable $e2) {
            $doctor = false;
        }
    }
    
    if (!$doctor) {
        header('Location: index.php?page=doctors');
        exit;
    }
    
    // إحصائيات الطبيب
    $stats = [
        'total_orders' => 0,
        'total_revenue' => 0,
        'recent_orders' => []
    ];
    
    try {
        $tenantOrd = '';
        try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $tenantOrd = ' AND o.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
        
        $stmt = $db->prepare('SELECT COUNT(*) FROM lab_orders WHERE doctor_id = ?' . ($tenantOrd ? ' AND tenant_id = ' . (int)$tenantId : ''));
        $stmt->execute([$viewId]);
        $stats['total_orders'] = (int)$stmt->fetchColumn();
        
        try {
            $stmt = $db->prepare('SELECT COALESCE(SUM(net_amount), 0) FROM lab_orders WHERE doctor_id = ?' . ($tenantOrd ? ' AND tenant_id = ' . (int)$tenantId : ''));
            $stmt->execute([$viewId]);
            $stats['total_revenue'] = (float)$stmt->fetchColumn();
        } catch (Throwable $e) {}
        
        // آخر الطلبات
        $stmt = $db->prepare(
            'SELECT o.id, o.order_number, o.order_date, o.status, o.net_amount, o.payment_status,
                    p.full_name AS patient_name, p.patient_code
             FROM lab_orders o
             LEFT JOIN patients p ON p.id = o.patient_id
             WHERE o.doctor_id = ?' . ($tenantOrd ? ' AND o.tenant_id = ' . (int)$tenantId : '') . '
             ORDER BY o.order_date DESC
             LIMIT 10'
        );
        $stmt->execute([$viewId]);
        $stats['recent_orders'] = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    ?>
    <div class="page-header">
        <h1>تفاصيل الطبيب</h1>
        <div class="actions-bar" style="flex-wrap:wrap;gap:12px;">
            <a href="index.php?page=doctors&action=edit&id=<?php echo (int)$viewId; ?>" class="btn-primary">تعديل</a>
            <?php if ($auth->can('doctors.delete')): ?>
            <a href="index.php?page=doctors&action=delete&id=<?php echo (int)$viewId; ?>" 
               class="btn-secondary" 
               onclick="return confirm('هل أنت متأكد من حذف هذا الطبيب؟');">حذف</a>
            <?php endif; ?>
            <a href="index.php?page=doctors" class="btn-secondary">← رجوع</a>
        </div>
    </div>
    
    <?php if (isset($_SESSION['doctors_msg'])): ?>
        <div class="alert alert-info" style="margin-bottom:20px;">
            <?php echo htmlspecialchars($_SESSION['doctors_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['doctors_msg']); ?>
        </div>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['doctors_error'])): ?>
        <div class="alert alert-danger" style="margin-bottom:20px;">
            <?php echo htmlspecialchars($_SESSION['doctors_error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['doctors_error']); ?>
        </div>
    <?php endif; ?>
    
    <div class="card" style="margin-bottom:20px;">
        <h2 style="margin-top:0;">المعلومات الأساسية</h2>
        <div class="form-grid">
            <div>
                <label><strong>الاسم الكامل:</strong></label>
                <div><?php echo htmlspecialchars($doctor['full_name'], ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div>
                <label><strong>الاختصاص:</strong></label>
                <div><?php echo htmlspecialchars($doctor['specialty'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div>
                <label><strong>رقم الهاتف:</strong></label>
                <div>
                    <?php if (!empty($doctor['phone'])): ?>
                        <a href="tel:<?php echo htmlspecialchars($doctor['phone'], ENT_QUOTES, 'UTF-8'); ?>">
                            <?php echo htmlspecialchars($doctor['phone'], ENT_QUOTES, 'UTF-8'); ?>
                        </a>
                    <?php else: ?>
                        غير محدد
                    <?php endif; ?>
                </div>
            </div>
            <div>
                <label><strong>اسم العيادة:</strong></label>
                <div><?php echo htmlspecialchars($doctor['clinic_name'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div>
                <label><strong>تاريخ الإضافة:</strong></label>
                <div><?php echo htmlspecialchars($doctor['created_at'] ?? '', ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
        </div>
    </div>
    
    <div class="card" style="margin-bottom:20px;">
        <h2 style="margin-top:0;">الإحصائيات</h2>
        <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:20px;">
            <div style="padding:15px;background:#f5f5f5;border-radius:8px;">
                <div style="font-size:24px;font-weight:bold;color:#2196F3;"><?php echo $stats['total_orders']; ?></div>
                <div style="color:#666;">إجمالي الطلبات</div>
            </div>
            <div style="padding:15px;background:#f5f5f5;border-radius:8px;">
                <div style="font-size:24px;font-weight:bold;color:#4CAF50;"><?php echo number_format($stats['total_revenue'], 2); ?> د.ع</div>
                <div style="color:#666;">إجمالي الإيرادات</div>
            </div>
        </div>
    </div>
    
    <?php if (!empty($stats['recent_orders'])): ?>
    <div class="card">
        <h2 style="margin-top:0;">آخر الطلبات</h2>
        <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 ($stats['recent_orders'] as $order): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($order['order_number'], ENT_QUOTES, 'UTF-8'); ?></td>
                        <td><?php echo htmlspecialchars($order['patient_name'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8'); ?></td>
                        <td><?php echo htmlspecialchars($order['order_date'], ENT_QUOTES, 'UTF-8'); ?></td>
                        <td>
                            <?php
                            $statusLabels = ['new' => 'جديد', 'in_progress' => 'قيد التنفيذ', 'completed' => 'مكتمل', 'cancelled' => 'ملغي'];
                            $statusColors = ['new' => '#2196F3', 'in_progress' => '#FF9800', 'completed' => '#4CAF50', 'cancelled' => '#f44336'];
                            $status = $order['status'] ?? 'new';
                            ?>
                            <span style="padding:4px 8px;background:<?php echo $statusColors[$status] ?? '#999'; ?>;color:white;border-radius:4px;font-size:12px;">
                                <?php echo $statusLabels[$status] ?? $status; ?>
                            </span>
                        </td>
                        <td><?php echo number_format((float)($order['net_amount'] ?? 0), 2); ?> د.ع</td>
                        <td>
                            <?php
                            $payLabels = ['unpaid' => 'غير مدفوع', 'partial' => 'جزئي', 'paid' => 'مدفوع'];
                            $payColors = ['unpaid' => '#f44336', 'partial' => '#FF9800', 'paid' => '#4CAF50'];
                            $payStatus = $order['payment_status'] ?? 'unpaid';
                            ?>
                            <span style="padding:4px 8px;background:<?php echo $payColors[$payStatus] ?? '#999'; ?>;color:white;border-radius:4px;font-size:12px;">
                                <?php echo $payLabels[$payStatus] ?? $payStatus; ?>
                            </span>
                        </td>
                        <td><a href="index.php?page=orders&action=view&id=<?php echo (int)$order['id']; ?>">عرض</a></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <div style="margin-top:15px;">
            <a href="index.php?page=orders&doctor_id=<?php echo (int)$viewId; ?>" class="btn-secondary">عرض جميع الطلبات</a>
        </div>
    </div>
    <?php endif; ?>
    
    <?php
    return;
}

// صفحة التعديل
if ($action === 'edit' && $viewId > 0) {
    try {
        $stmt = $db->prepare('SELECT * FROM doctors WHERE id = ? AND tenant_id = ?');
        $stmt->execute([$viewId, $tenantId]);
        $editDoctor = $stmt->fetch();
    } catch (Throwable $e) {
        try {
            $stmt = $db->prepare('SELECT * FROM doctors WHERE id = ?');
            $stmt->execute([$viewId]);
            $editDoctor = $stmt->fetch();
        } catch (Throwable $e2) {
            $editDoctor = false;
        }
    }
    
    if (!$editDoctor) {
        header('Location: index.php?page=doctors');
        exit;
    }
    ?>
    <div class="page-header">
        <h1>تعديل طبيب محوِّل</h1>
        <a href="index.php?page=doctors&action=view&id=<?php echo (int)$viewId; ?>" class="btn-secondary">← رجوع</a>
    </div>
    <div class="card">
        <form method="post" class="form-grid">
            <input type="hidden" name="id" value="<?php echo (int)$viewId; ?>">
            <div>
                <label>الاسم الكامل <span class="required">*</span></label>
                <input type="text" name="full_name" value="<?php echo htmlspecialchars($editDoctor['full_name'], ENT_QUOTES, 'UTF-8'); ?>" required>
            </div>
            <div>
                <label>الاختصاص</label>
                <input type="text" name="specialty" value="<?php echo htmlspecialchars($editDoctor['specialty'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
            </div>
            <div>
                <label>رقم الهاتف</label>
                <input type="tel" name="phone" value="<?php echo htmlspecialchars($editDoctor['phone'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
            </div>
            <div>
                <label>اسم العيادة</label>
                <input type="text" name="clinic_name" value="<?php echo htmlspecialchars($editDoctor['clinic_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
            </div>
            <div class="full-width form-actions">
                <button type="submit" class="btn-primary">حفظ التعديلات</button>
                <a href="index.php?page=doctors&action=view&id=<?php echo (int)$viewId; ?>" class="btn-secondary">إلغاء</a>
            </div>
        </form>
    </div>
    <?php
    return;
}

// صفحة الإضافة
if ($action === 'create') {
    ?>
    <div class="page-header">
        <h1>إضافة طبيب محوِّل</h1>
        <a href="index.php?page=doctors" class="btn-secondary">← رجوع</a>
    </div>
    <div class="card">
        <form method="post" class="form-grid">
            <div>
                <label>الاسم الكامل <span class="required">*</span></label>
                <input type="text" name="full_name" required placeholder="الاسم الكامل للطبيب">
            </div>
            <div>
                <label>الاختصاص</label>
                <input type="text" name="specialty" placeholder="مثال: طب عام، باطنية، جراحة...">
            </div>
            <div>
                <label>رقم الهاتف</label>
                <input type="tel" name="phone" placeholder="07XX XXX XXXX">
            </div>
            <div>
                <label>اسم العيادة</label>
                <input type="text" name="clinic_name" placeholder="اسم العيادة أو المستشفى">
            </div>
            <div class="full-width form-actions">
                <button type="submit" class="btn-primary">حفظ</button>
                <a href="index.php?page=doctors" class="btn-secondary">إلغاء</a>
            </div>
        </form>
    </div>
    <?php
    return;
}

// صفحة القائمة الرئيسية
$qDoctor = trim($_GET['q'] ?? '');
$doctors = [];

try {
    $sql = 'SELECT d.id, d.full_name, d.specialty, d.phone, d.clinic_name, d.created_at,
                   COUNT(o.id) AS orders_count
            FROM doctors d
            LEFT JOIN lab_orders o ON o.doctor_id = d.id';
    try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $sql .= ' AND o.tenant_id = d.tenant_id'; } catch (Throwable $e) {}
    $sql .= ' WHERE d.tenant_id = ?';
    $params = [$tenantId];
    if ($qDoctor !== '') {
        $sql .= ' AND (d.full_name LIKE ? OR d.specialty LIKE ? OR d.clinic_name LIKE ? OR d.phone LIKE ?)';
        $like = '%' . $qDoctor . '%';
        $params = array_merge($params, [$like, $like, $like, $like]);
    }
    $sql .= ' GROUP BY d.id ORDER BY d.full_name ASC LIMIT 200';
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $doctors = $stmt->fetchAll();
} catch (Throwable $e) {
    try {
        $sql = 'SELECT d.id, d.full_name, d.specialty, d.phone, d.clinic_name, d.created_at,
                       COUNT(o.id) AS orders_count
                FROM doctors d
                LEFT JOIN lab_orders o ON o.doctor_id = d.id';
        $sql .= ' WHERE 1=1';
        $params = [];
        if ($qDoctor !== '') {
            $sql .= ' AND (d.full_name LIKE ? OR d.specialty LIKE ? OR d.clinic_name LIKE ?)';
            $like = '%' . $qDoctor . '%';
            $params = [$like, $like, $like];
        }
        $sql .= ' GROUP BY d.id ORDER BY d.full_name ASC LIMIT 200';
        $stmt = $params ? $db->prepare($sql) : $db->query($sql);
        $params ? $stmt->execute($params) : null;
        $doctors = $stmt->fetchAll();
    } catch (Throwable $e2) {}
}

?>
<div class="page-header">
    <h1>الأطباء المحوِّلين</h1>
    <div class="actions-bar" style="flex-wrap:wrap;gap:12px;">
        <form method="get" style="display:inline-flex;gap:6px;">
            <input type="hidden" name="page" value="doctors">
            <input type="search" name="q" placeholder="بحث باسم، اختصاص، عيادة..." value="<?php echo htmlspecialchars($qDoctor, ENT_QUOTES, 'UTF-8'); ?>" style="min-width:180px;">
            <button type="submit">بحث</button>
            <?php if ($qDoctor): ?><a href="index.php?page=doctors" class="btn-secondary">إلغاء</a><?php endif; ?>
        </form>
        <?php if ($auth->can('doctors.create')): ?>
        <a href="index.php?page=doctors&action=create" class="btn-primary">+ طبيب جديد</a>
        <?php endif; ?>
        <a href="index.php?page=orders&action=create" class="btn-secondary">طلب فحوصات جديد</a>
    </div>
</div>

<?php if (isset($_SESSION['doctors_msg'])): ?>
    <div class="alert alert-info" style="margin-bottom:20px;">
        <?php echo htmlspecialchars($_SESSION['doctors_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['doctors_msg']); ?>
    </div>
<?php endif; ?>

<?php if (isset($_SESSION['doctors_error'])): ?>
    <div class="alert alert-danger" style="margin-bottom:20px;">
        <?php echo htmlspecialchars($_SESSION['doctors_error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['doctors_error']); ?>
    </div>
<?php endif; ?>

<?php if (empty($doctors)): ?>
    <div class="card">
        <p style="text-align:center;color:#666;padding:40px;">
            <?php if ($qDoctor): ?>
                لم يتم العثور على أطباء مطابقين للبحث.
            <?php else: ?>
                لا يوجد أطباء محوّلين مسجلين حالياً.
            <?php endif; ?>
        </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>
            <th>إجراءات</th>
        </tr>
    </thead>
    <tbody>
    <?php foreach ($doctors as $d): ?>
        <tr>
            <td>
                <strong><?php echo htmlspecialchars($d['full_name'], ENT_QUOTES, 'UTF-8'); ?></strong>
            </td>
            <td><?php echo htmlspecialchars($d['specialty'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8'); ?></td>
            <td>
                <?php if (!empty($d['phone'])): ?>
                    <a href="tel:<?php echo htmlspecialchars($d['phone'], ENT_QUOTES, 'UTF-8'); ?>">
                        <?php echo htmlspecialchars($d['phone'], ENT_QUOTES, 'UTF-8'); ?>
                    </a>
                <?php else: ?>
                    <span style="color:#999;">-</span>
                <?php endif; ?>
            </td>
            <td><?php echo htmlspecialchars($d['clinic_name'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8'); ?></td>
            <td>
                <a href="index.php?page=orders&doctor_id=<?php echo (int)$d['id']; ?>" style="color:#2196F3;">
                    <?php echo (int)($d['orders_count'] ?? 0); ?>
                </a>
            </td>
            <td><?php echo htmlspecialchars($d['created_at'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
            <td>
                <div style="display:flex;gap:8px;flex-wrap:wrap;">
                    <a href="index.php?page=doctors&action=view&id=<?php echo (int)$d['id']; ?>" style="padding:4px 12px;background:#2196F3;color:white;text-decoration:none;border-radius:4px;font-size:13px;">عرض</a>
                    <?php if ($auth->can('doctors.update')): ?>
                    <a href="index.php?page=doctors&action=edit&id=<?php echo (int)$d['id']; ?>" style="padding:4px 12px;background:#FF9800;color:white;text-decoration:none;border-radius:4px;font-size:13px;">تعديل</a>
                    <?php endif; ?>
                    <?php if ($auth->can('doctors.delete')): ?>
                    <a href="index.php?page=doctors&action=delete&id=<?php echo (int)$d['id']; ?>" 
                       style="padding:4px 12px;background:#f44336;color:white;text-decoration:none;border-radius:4px;font-size:13px;"
                       onclick="return confirm('هل أنت متأكد من حذف هذا الطبيب؟');">حذف</a>
                    <?php endif; ?>
                </div>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>
<?php endif; ?>
