<?php
/**
 * الملف الشخصي للطبيب
 */
$accountInfo = null;
try {
    $stmt = $db->prepare('SELECT da.*, d.full_name, d.specialty, d.phone, d.clinic_name, t.name AS tenant_name FROM doctor_accounts da JOIN doctors d ON d.id = da.doctor_id AND d.tenant_id = da.tenant_id JOIN tenants t ON t.id = da.tenant_id WHERE da.id = ?');
    $stmt->execute([$doctorAuth->accountId()]);
    $accountInfo = $stmt->fetch();
} catch (Throwable $e) {}

$myStats = ['patients' => 0, 'orders' => 0, 'notes' => 0, 'appointments' => 0, 'reminders' => 0, 'critical_results' => 0];
$activityLog = [];
$weeklyStats = ['orders' => [], 'patients' => []];
$monthlyStats = ['orders' => 0, 'patients' => 0, 'notes' => 0];

try {
    $stmt = $db->prepare("SELECT COUNT(DISTINCT patient_id) FROM lab_orders WHERE doctor_id = ? AND tenant_id = ?");
    $stmt->execute([$doctorId, $tenantId]);
    $myStats['patients'] = (int)$stmt->fetchColumn();
    $stmt = $db->prepare("SELECT COUNT(*) FROM lab_orders WHERE doctor_id = ? AND tenant_id = ?");
    $stmt->execute([$doctorId, $tenantId]);
    $myStats['orders'] = (int)$stmt->fetchColumn();
    $stmt = $db->prepare("SELECT COUNT(*) FROM patient_medical_notes WHERE doctor_account_id = ?");
    $stmt->execute([$doctorAuth->accountId()]);
    $myStats['notes'] = (int)$stmt->fetchColumn();
    
    // إحصائيات المواعيد
    try {
        $db->query('SELECT id FROM doctor_appointments LIMIT 1');
        $stmt = $db->prepare("SELECT COUNT(*) FROM doctor_appointments WHERE doctor_account_id = ?");
        $stmt->execute([$doctorAuth->accountId()]);
        $myStats['appointments'] = (int)$stmt->fetchColumn();
    } catch (Throwable $e) {}
    
    // إحصائيات التذكيرات
    try {
        $db->query('SELECT id FROM doctor_follow_up_reminders LIMIT 1');
        $stmt = $db->prepare("SELECT COUNT(*) FROM doctor_follow_up_reminders WHERE doctor_account_id = ? AND is_done = 0");
        $stmt->execute([$doctorAuth->accountId()]);
        $myStats['reminders'] = (int)$stmt->fetchColumn();
    } catch (Throwable $e) {}
    
    // النتائج الحرجة
    try {
        $stmt = $db->prepare("SELECT COUNT(*) FROM results r 
            JOIN order_items oi ON oi.id = r.order_item_id 
            JOIN lab_orders o ON o.id = oi.order_id 
            WHERE o.doctor_id = ? AND o.tenant_id = ? AND r.flag = 'C' 
            AND o.order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)");
        $stmt->execute([$doctorId, $tenantId]);
        $myStats['critical_results'] = (int)$stmt->fetchColumn();
    } catch (Throwable $e) {}
    
    // إحصائيات الأسبوع (آخر 7 أيام)
    for ($i = 6; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-$i days"));
        $stmt = $db->prepare("SELECT COUNT(*) FROM lab_orders WHERE doctor_id = ? AND tenant_id = ? AND DATE(order_date) = ?");
        $stmt->execute([$doctorId, $tenantId, $date]);
        $weeklyStats['orders'][] = ['date' => $date, 'count' => (int)$stmt->fetchColumn()];
        
        $stmt = $db->prepare("SELECT COUNT(DISTINCT patient_id) FROM lab_orders WHERE doctor_id = ? AND tenant_id = ? AND DATE(order_date) = ?");
        $stmt->execute([$doctorId, $tenantId, $date]);
        $weeklyStats['patients'][] = ['date' => $date, 'count' => (int)$stmt->fetchColumn()];
    }
    
    // إحصائيات الشهر الحالي
    $monthStart = date('Y-m-01');
    $stmt = $db->prepare("SELECT COUNT(*) FROM lab_orders WHERE doctor_id = ? AND tenant_id = ? AND order_date >= ?");
    $stmt->execute([$doctorId, $tenantId, $monthStart]);
    $monthlyStats['orders'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->prepare("SELECT COUNT(DISTINCT patient_id) FROM lab_orders WHERE doctor_id = ? AND tenant_id = ? AND order_date >= ?");
    $stmt->execute([$doctorId, $tenantId, $monthStart]);
    $monthlyStats['patients'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->prepare("SELECT COUNT(*) FROM patient_medical_notes WHERE doctor_account_id = ? AND created_at >= ?");
    $stmt->execute([$doctorAuth->accountId(), $monthStart]);
    $monthlyStats['notes'] = (int)$stmt->fetchColumn();
} catch (Throwable $e) {}
try {
    $db->query('SELECT id FROM doctor_activity_log LIMIT 1');
    $stmt = $db->prepare('SELECT action, entity_type, entity_id, created_at FROM doctor_activity_log WHERE doctor_account_id = ? ORDER BY created_at DESC LIMIT 30');
    $stmt->execute([$doctorAuth->accountId()]);
    $activityLog = $stmt->fetchAll();
} catch (Throwable $e) {}
$actionLabels = ['view_results' => 'عرض نتائج', 'view_patient' => 'عرض مريض', 'search' => 'بحث', 'login' => 'تسجيل دخول', 'export' => 'تصدير'];
?>
<!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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
</head>
<body>
<?php include __DIR__ . '/_layout.php'; ?>
<main class="content doctor-profile-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>

    <?php if ($accountInfo): ?>
    <!-- بطاقة المعلومات الشخصية -->
    <div class="card" style="margin-bottom:24px;background:linear-gradient(135deg, #0f172a 0%, #1e3a5f 100%);color:white;border:none;">
        <div style="display:flex;gap:24px;align-items:center;flex-wrap:wrap;">
            <div style="width:100px;height:100px;border-radius:50%;background:rgba(255,255,255,0.2);display:flex;align-items:center;justify-content:center;font-size:3rem;flex-shrink:0;">
                👨‍⚕️
            </div>
            <div style="flex:1;min-width:200px;">
                <h2 style="margin:0 0 8px;color:white;font-size:1.5rem;">د. <?php echo htmlspecialchars($accountInfo['full_name'], ENT_QUOTES, 'UTF-8'); ?></h2>
                <p style="margin:0 0 12px;color:rgba(255,255,255,0.8);font-size:1rem;">
                    <?php echo htmlspecialchars($accountInfo['specialty'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8'); ?>
                    <?php if (!empty($accountInfo['clinic_name'])): ?>
                    <span style="color:rgba(255,255,255,0.6);"> · </span>
                    <span style="color:rgba(255,255,255,0.7);"><?php echo htmlspecialchars($accountInfo['clinic_name'], ENT_QUOTES, 'UTF-8'); ?></span>
                    <?php endif; ?>
                </p>
                <div style="display:flex;gap:16px;flex-wrap:wrap;font-size:0.9rem;color:rgba(255,255,255,0.8);">
                    <div style="display:flex;align-items:center;gap:6px;">
                        <span>🏥</span>
                        <span><?php echo htmlspecialchars($accountInfo['tenant_name'], ENT_QUOTES, 'UTF-8'); ?></span>
                    </div>
                    <?php if (!empty($accountInfo['phone'])): ?>
                    <div style="display:flex;align-items:center;gap:6px;">
                        <span>📞</span>
                        <span><?php echo htmlspecialchars($accountInfo['phone'], ENT_QUOTES, 'UTF-8'); ?></span>
                    </div>
                    <?php endif; ?>
                    <div style="display:flex;align-items:center;gap:6px;">
                        <span>👤</span>
                        <span><?php echo htmlspecialchars($accountInfo['username'], ENT_QUOTES, 'UTF-8'); ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- الإحصائيات الرئيسية -->
    <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:16px;margin-bottom:24px;">
        <div class="card doctor-profile-stat-card" style="border-right:4px solid #0d9488;background:linear-gradient(135deg, #f0fdfa 0%, #ffffff 100%);">
            <div style="display:flex;align-items:center;gap:12px;margin-bottom:12px;">
                <div style="width:48px;height:48px;border-radius:12px;background:#0d9488;display:flex;align-items:center;justify-content:center;font-size:1.5rem;">
                    👥
                </div>
                <div>
                    <div style="font-size:2rem;font-weight:bold;color:#0d9488;line-height:1;"><?php echo number_format($myStats['patients']); ?></div>
                    <div style="color:var(--text-muted);font-size:0.85rem;margin-top:4px;">المرضى</div>
                </div>
            </div>
            <div style="padding-top:12px;border-top:1px solid var(--border);font-size:0.8rem;color:var(--text-muted);">
                هذا الشهر: <?php echo number_format($monthlyStats['patients']); ?>
            </div>
        </div>

        <div class="card doctor-profile-stat-card" style="border-right:4px solid #3b82f6;background:linear-gradient(135deg, #eff6ff 0%, #ffffff 100%);">
            <div style="display:flex;align-items:center;gap:12px;margin-bottom: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:2rem;font-weight:bold;color:#3b82f6;line-height:1;"><?php echo number_format($myStats['orders']); ?></div>
                    <div style="color:var(--text-muted);font-size:0.85rem;margin-top:4px;">الطلبات</div>
                </div>
            </div>
            <div style="padding-top:12px;border-top:1px solid var(--border);font-size:0.8rem;color:var(--text-muted);">
                هذا الشهر: <?php echo number_format($monthlyStats['orders']); ?>
            </div>
        </div>

        <div class="card doctor-profile-stat-card" style="border-right:4px solid #22c55e;background:linear-gradient(135deg, #f0fdf4 0%, #ffffff 100%);">
            <div style="display:flex;align-items:center;gap:12px;margin-bottom: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:2rem;font-weight:bold;color:#22c55e;line-height:1;"><?php echo number_format($myStats['notes']); ?></div>
                    <div style="color:var(--text-muted);font-size:0.85rem;margin-top:4px;">الملاحظات</div>
                </div>
            </div>
            <div style="padding-top:12px;border-top:1px solid var(--border);font-size:0.8rem;color:var(--text-muted);">
                هذا الشهر: <?php echo number_format($monthlyStats['notes']); ?>
            </div>
        </div>

        <div class="card doctor-profile-stat-card" style="border-right:4px solid #f59e0b;background:linear-gradient(135deg, #fffbeb 0%, #ffffff 100%);">
            <div style="display:flex;align-items:center;gap:12px;margin-bottom: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:2rem;font-weight:bold;color:#f59e0b;line-height:1;"><?php echo number_format($myStats['appointments']); ?></div>
                    <div style="color:var(--text-muted);font-size:0.85rem;margin-top:4px;">المواعيد</div>
                </div>
            </div>
            <div style="padding-top:12px;border-top:1px solid var(--border);font-size:0.8rem;color:var(--text-muted);">
                تذكيرات نشطة: <?php echo number_format($myStats['reminders']); ?>
            </div>
        </div>

        <?php if ($myStats['critical_results'] > 0): ?>
        <div class="card doctor-profile-stat-card" style="border-right:4px solid #dc2626;background:linear-gradient(135deg, #fef2f2 0%, #ffffff 100%);">
            <div style="display:flex;align-items:center;gap:12px;margin-bottom: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:2rem;font-weight:bold;color:#dc2626;line-height:1;"><?php echo number_format($myStats['critical_results']); ?></div>
                    <div style="color:var(--text-muted);font-size:0.85rem;margin-top:4px;">نتائج حرجة</div>
                </div>
            </div>
            <div style="padding-top:12px;border-top:1px solid var(--border);font-size:0.8rem;color:var(--text-muted);">
                آخر 30 يوم
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- معلومات إضافية -->
    <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(300px, 1fr));gap:20px;margin-bottom:24px;">
        <div class="card">
            <h3 style="margin-top:0;display:flex;align-items:center;gap:8px;">
                <span>ℹ️</span> معلومات الحساب
            </h3>
            <div style="display:flex;flex-direction:column;gap:14px;">
                <div style="display:flex;justify-content:space-between;align-items:center;padding:10px;background:var(--bg-secondary);border-radius:8px;">
                    <span style="color:var(--text-muted);font-size:0.9rem;">اسم المستخدم:</span>
                    <code style="background:white;padding:4px 8px;border-radius:4px;font-weight:600;"><?php echo htmlspecialchars($accountInfo['username'], ENT_QUOTES, 'UTF-8'); ?></code>
                </div>
                <div style="display:flex;justify-content:space-between;align-items:center;padding:10px;background:var(--bg-secondary);border-radius:8px;">
                    <span style="color:var(--text-muted);font-size:0.9rem;">المختبر:</span>
                    <strong><?php echo htmlspecialchars($accountInfo['tenant_name'], ENT_QUOTES, 'UTF-8'); ?></strong>
                </div>
                <div style="display:flex;justify-content:space-between;align-items:center;padding:10px;background:var(--bg-secondary);border-radius:8px;">
                    <span style="color:var(--text-muted);font-size:0.9rem;">آخر دخول:</span>
                    <span><?php echo $accountInfo['last_login_at'] ? date('Y-m-d H:i', strtotime($accountInfo['last_login_at'])) : 'لم يسجل'; ?></span>
                </div>
                <div style="display:flex;justify-content:space-between;align-items:center;padding:10px;background:var(--bg-secondary);border-radius:8px;">
                    <span style="color:var(--text-muted);font-size:0.9rem;">حالة الحساب:</span>
                    <span style="padding:4px 10px;background:#22c55e;color:white;border-radius:12px;font-size:0.8rem;font-weight:600;"><?php echo $accountInfo['is_active'] ? 'نشط' : 'غير نشط'; ?></span>
                </div>
            </div>
        </div>

        <div class="card">
            <h3 style="margin-top:0;display:flex;align-items:center;gap:8px;">
                <span>📊</span> نشاط الأسبوع
            </h3>
            <canvas id="weeklyActivityChart" style="max-height:200px;"></canvas>
        </div>
    </div>
    <!-- تغيير كلمة المرور -->
    <div class="card" style="margin-bottom:24px;">
        <h3 style="margin-top:0;display:flex;align-items:center;gap:8px;">
            <span>🔐</span> تغيير كلمة المرور
        </h3>
        <?php if (isset($_SESSION['doctor_profile_msg'])): ?><div class="alert alert-success"><?php echo htmlspecialchars($_SESSION['doctor_profile_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['doctor_profile_msg']); ?></div><?php endif; ?>
        <?php if (isset($_SESSION['doctor_profile_error'])): ?><div class="alert alert-danger"><?php echo htmlspecialchars($_SESSION['doctor_profile_error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['doctor_profile_error']); ?></div><?php endif; ?>
        <form method="post" action="doctor.php?page=profile&action=change_password" style="max-width:400px;">
            <div class="form-group">
                <label>كلمة المرور الحالية</label>
                <input type="password" name="current_password" required>
            </div>
            <div class="form-group">
                <label>كلمة المرور الجديدة</label>
                <input type="password" name="new_password" required minlength="6">
            </div>
            <div class="form-group">
                <label>تأكيد كلمة المرور الجديدة</label>
                <input type="password" name="confirm_password" required minlength="6">
            </div>
            <button type="submit" class="btn-primary">تغيير كلمة المرور</button>
        </form>
        <div style="margin-top:16px;padding:12px;background:#ecfdf5;border-radius:8px;border-right:4px solid #0d9488;">
            <p style="margin:0;color:#047857;font-size:0.9rem;">
                <strong>💡 ملاحظة:</strong> لتحديث بياناتك الشخصية (الاسم، التخصص، الهاتف، العيادة)، تواصل مع مدير المختبر.
            </p>
        </div>
    </div>
    <!-- سجل النشاط -->
    <?php if (!empty($activityLog)): ?>
    <div class="card">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
            <h3 style="margin:0;display:flex;align-items:center;gap:8px;">
                <span>📋</span> سجل النشاط الأخير
            </h3>
            <span style="font-size:0.85rem;color:var(--text-muted);">آخر 30 عملية</span>
        </div>
        <div class="table-wrapper" style="max-height:400px;overflow-y:auto;border-radius:8px;">
            <table class="table" style="margin:0;">
                <thead style="position:sticky;top:0;background:var(--bg-card);z-index:10;">
                    <tr>
                        <th style="padding:12px;">الإجراء</th>
                        <th style="padding:12px;">النوع</th>
                        <th style="padding:12px;">التاريخ والوقت</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($activityLog as $log): 
                    $actionIcon = [
                        'view_results' => '📄',
                        'view_patient' => '👤',
                        'search' => '🔍',
                        'login' => '🔐',
                        'export' => '📥',
                        'add_note' => '📝',
                        'add_appointment' => '📅'
                    ];
                    $icon = $actionIcon[$log['action']] ?? '⚙️';
                ?>
                <tr style="transition:background 0.2s;">
                    <td style="padding:12px;">
                        <div style="display:flex;align-items:center;gap:8px;">
                            <span style="font-size:1.2rem;"><?php echo $icon; ?></span>
                            <span><?php echo htmlspecialchars($actionLabels[$log['action']] ?? $log['action'], ENT_QUOTES, 'UTF-8'); ?></span>
                        </div>
                    </td>
                    <td style="padding:12px;">
                        <span style="padding:4px 10px;background:var(--bg-secondary);border-radius:12px;font-size:0.85rem;">
                            <?php echo htmlspecialchars($log['entity_type'] ?? '-', ENT_QUOTES, 'UTF-8'); ?>
                            <?php if ($log['entity_id']): ?>
                            <span style="color:var(--primary);font-weight:600;">#<?php echo (int)$log['entity_id']; ?></span>
                            <?php endif; ?>
                        </span>
                    </td>
                    <td style="padding:12px;color:var(--text-muted);font-size:0.9rem;">
                        <?php echo date('Y-m-d', strtotime($log['created_at'])); ?>
                        <span style="color:var(--text-muted);opacity:0.7;"><?php echo date('H:i', strtotime($log['created_at'])); ?></span>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>
    <?php else: ?>
    <div class="card">
        <p style="color:var(--text-muted);">تعذر تحميل البيانات.</p>
    </div>
    <?php endif; ?>
</main>

<script>
// رسم بياني لنشاط الأسبوع
(function(){
    var ctx = document.getElementById('weeklyActivityChart');
    if (!ctx) return;
    
    var weeklyData = <?php echo json_encode($weeklyStats['orders']); ?>;
    var labels = weeklyData.map(function(d) {
        var date = new Date(d.date);
        var days = ['أحد', 'اثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت'];
        return days[date.getDay()] + ' ' + date.getDate();
    });
    var ordersData = weeklyData.map(function(d) { return d.count; });
    var patientsData = <?php echo json_encode($weeklyStats['patients']); ?>.map(function(d) { return d.count; });
    
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: 'الطلبات',
                data: ordersData,
                borderColor: '#3b82f6',
                backgroundColor: 'rgba(59, 130, 246, 0.1)',
                tension: 0.4,
                fill: true
            }, {
                label: 'المرضى',
                data: patientsData,
                borderColor: '#0d9488',
                backgroundColor: 'rgba(13, 148, 136, 0.1)',
                tension: 0.4,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    position: 'top',
                    rtl: true
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            }
        }
    });
})();
</script>
</body>
</html>
