<?php
/**
 * Dashboard خاص بالطبيب
 */

// التحقق من تسجيل دخول الطبيب
if (!isset($_SESSION['doctor_id']) || !isset($_SESSION['user_type']) || $_SESSION['user_type'] !== 'doctor') {
    header('Location: index.php?page=doctor_login');
    exit;
}

$doctorId = (int)$_SESSION['doctor_id'];
$clinicId = (int)$_SESSION['doctor_clinic_id'];
$tenantId = (int)$_SESSION['doctor_tenant_id'];

// جلب معلومات الطبيب
try {
    $stmt = $db->prepare(
        'SELECT cd.*, c.name as clinic_name 
         FROM clinic_doctors cd 
         LEFT JOIN clinics c ON cd.clinic_id = c.id
         WHERE cd.id = ? AND cd.tenant_id = ?'
    );
    $stmt->execute([$doctorId, $tenantId]);
    $doctor = $stmt->fetch();
} catch (Throwable $e) {
    $doctor = null;
}

if (!$doctor) {
    echo '<div class="alert alert-danger">الطبيب غير موجود</div>';
    echo '<a href="index.php?page=doctor_logout" class="btn">تسجيل الخروج</a>';
    exit;
}

// إحصائيات اليوم
$today = date('Y-m-d');
$stats = [
    'appointments_today' => 0,
    'appointments_completed' => 0,
    'appointments_pending' => 0,
    'visits_today' => 0,
    'patients_total' => 0,
    'lab_results_pending' => 0
];

try {
    // مواعيد اليوم
    $stmt = $db->prepare(
        'SELECT COUNT(*) FROM appointments 
         WHERE doctor_id = ? AND appointment_date = ?'
    );
    $stmt->execute([$doctorId, $today]);
    $stats['appointments_today'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->prepare(
        'SELECT COUNT(*) FROM appointments 
         WHERE doctor_id = ? AND appointment_date = ? AND status = "completed"'
    );
    $stmt->execute([$doctorId, $today]);
    $stats['appointments_completed'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->prepare(
        'SELECT COUNT(*) FROM appointments 
         WHERE doctor_id = ? AND appointment_date = ? AND status IN ("scheduled", "confirmed")'
    );
    $stmt->execute([$doctorId, $today]);
    $stats['appointments_pending'] = (int)$stmt->fetchColumn();
    
    // زيارات اليوم
    $stmt = $db->prepare(
        'SELECT COUNT(*) FROM patient_visits 
         WHERE doctor_id = ? AND DATE(visit_date) = ?'
    );
    $stmt->execute([$doctorId, $today]);
    $stats['visits_today'] = (int)$stmt->fetchColumn();
    
    // إجمالي المرضى
    $stmt = $db->prepare(
        'SELECT COUNT(DISTINCT patient_id) FROM patient_visits WHERE doctor_id = ?'
    );
    $stmt->execute([$doctorId]);
    $stats['patients_total'] = (int)$stmt->fetchColumn();
    
    // تحاليل معلقة
    $stmt = $db->prepare(
        'SELECT COUNT(*) FROM clinic_lab_requests 
         WHERE doctor_id = ? AND status IN ("pending", "sent", "received")'
    );
    $stmt->execute([$doctorId]);
    $stats['lab_results_pending'] = (int)$stmt->fetchColumn();
} catch (Throwable $e) {}

// جلب المواعيد القادمة
$upcomingAppointments = [];
try {
    $stmt = $db->prepare(
        'SELECT a.*, p.full_name as patient_name, p.phone as patient_phone
         FROM appointments a
         JOIN patients p ON a.patient_id = p.id
         WHERE a.doctor_id = ? AND a.appointment_date >= ? 
         AND a.status IN ("scheduled", "confirmed")
         ORDER BY a.appointment_date, a.appointment_time
         LIMIT 10'
    );
    $stmt->execute([$doctorId, $today]);
    $upcomingAppointments = $stmt->fetchAll();
} catch (Throwable $e) {}

// جلب آخر الزيارات
$recentVisits = [];
try {
    $stmt = $db->prepare(
        'SELECT v.*, p.full_name as patient_name
         FROM patient_visits v
         JOIN patients p ON v.patient_id = p.id
         WHERE v.doctor_id = ?
         ORDER BY v.visit_date DESC
         LIMIT 10'
    );
    $stmt->execute([$doctorId]);
    $recentVisits = $stmt->fetchAll();
} catch (Throwable $e) {}

?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>لوحة الطبيب - <?= htmlspecialchars($doctor['full_name']) ?></title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="portal.css">
    <style>
        .doctor-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 12px;
            margin-bottom: 30px;
        }
        .doctor-header h1 {
            margin: 0 0 10px 0;
            font-size: 28px;
        }
        .doctor-header p {
            margin: 0;
            opacity: 0.9;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border-right: 4px solid #667eea;
        }
        .stat-card h3 {
            margin: 0 0 10px 0;
            color: #666;
            font-size: 14px;
        }
        .stat-card .value {
            font-size: 32px;
            font-weight: bold;
            color: #333;
        }
        .section-card {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .section-card h2 {
            margin: 0 0 20px 0;
            color: #333;
            border-bottom: 2px solid #f0f0f0;
            padding-bottom: 10px;
        }
        .appointment-item, .visit-item {
            padding: 15px;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .appointment-item:last-child, .visit-item:last-child {
            border-bottom: none;
        }
        .appointment-item .time {
            font-weight: bold;
            color: #667eea;
        }
        .visit-item .date {
            color: #666;
            font-size: 14px;
        }
        .nav-menu {
            background: white;
            padding: 15px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        .nav-menu a {
            padding: 10px 20px;
            background: #f0f0f0;
            border-radius: 8px;
            text-decoration: none;
            color: #333;
            transition: all 0.3s;
        }
        .nav-menu a:hover {
            background: #667eea;
            color: white;
        }
    </style>
</head>
<body>
    <div class="doctor-header">
        <h1>👨‍⚕️ مرحباً، د. <?= htmlspecialchars($doctor['full_name']) ?></h1>
        <p>العيادة: <?= htmlspecialchars($doctor['clinic_name'] ?? '-') ?> | الاختصاص: <?= htmlspecialchars($doctor['specialty'] ?? '-') ?></p>
    </div>
    
    <div class="nav-menu">
        <a href="index.php?page=doctor_dashboard">🏠 الرئيسية</a>
        <a href="index.php?page=doctor_patients">👥 مرضاي</a>
        <a href="index.php?page=doctor_appointments">📅 مواعيدي</a>
        <a href="index.php?page=doctor_visits">📋 زياراتي</a>
        <a href="index.php?page=doctor_lab_results">🔬 التحاليل</a>
        <a href="index.php?page=doctor_logout" style="background: #dc3545; color: white;">تسجيل الخروج</a>
    </div>
    
    <div class="stats-grid">
        <div class="stat-card">
            <h3>مواعيد اليوم</h3>
            <div class="value"><?= $stats['appointments_today'] ?></div>
        </div>
        <div class="stat-card">
            <h3>مواعيد مكتملة</h3>
            <div class="value"><?= $stats['appointments_completed'] ?></div>
        </div>
        <div class="stat-card">
            <h3>مواعيد معلقة</h3>
            <div class="value"><?= $stats['appointments_pending'] ?></div>
        </div>
        <div class="stat-card">
            <h3>زيارات اليوم</h3>
            <div class="value"><?= $stats['visits_today'] ?></div>
        </div>
        <div class="stat-card">
            <h3>إجمالي المرضى</h3>
            <div class="value"><?= $stats['patients_total'] ?></div>
        </div>
        <div class="stat-card">
            <h3>تحاليل معلقة</h3>
            <div class="value"><?= $stats['lab_results_pending'] ?></div>
        </div>
    </div>
    
    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
        <div class="section-card">
            <h2>📅 المواعيد القادمة</h2>
            <?php if (empty($upcomingAppointments)): ?>
                <p style="color: #666; text-align: center; padding: 20px;">لا توجد مواعيد قادمة</p>
            <?php else: ?>
                <?php foreach ($upcomingAppointments as $apt): ?>
                    <div class="appointment-item">
                        <div>
                            <div class="time"><?= date('H:i', strtotime($apt['appointment_time'])) ?></div>
                            <div style="font-weight: bold; margin-top: 5px;"><?= htmlspecialchars($apt['patient_name']) ?></div>
                            <div style="font-size: 12px; color: #666;"><?= htmlspecialchars($apt['patient_phone'] ?? '-') ?></div>
                        </div>
                        <div>
                            <span class="badge badge-<?= $apt['status'] === 'confirmed' ? 'success' : 'warning' ?>">
                                <?= $apt['status'] === 'confirmed' ? 'مؤكد' : 'مجدول' ?>
                            </span>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        
        <div class="section-card">
            <h2>📋 آخر الزيارات</h2>
            <?php if (empty($recentVisits)): ?>
                <p style="color: #666; text-align: center; padding: 20px;">لا توجد زيارات سابقة</p>
            <?php else: ?>
                <?php foreach ($recentVisits as $visit): ?>
                    <div class="visit-item">
                        <div>
                            <div style="font-weight: bold;"><?= htmlspecialchars($visit['patient_name']) ?></div>
                            <div class="date"><?= date('Y-m-d H:i', strtotime($visit['visit_date'])) ?></div>
                            <?php if ($visit['diagnosis']): ?>
                                <div style="font-size: 12px; color: #666; margin-top: 5px;">
                                    <?= htmlspecialchars(mb_substr($visit['diagnosis'], 0, 50)) ?>...
                                </div>
                            <?php endif; ?>
                        </div>
                        <div>
                            <a href="index.php?page=doctor_visits&action=view&id=<?= $visit['id'] ?>" class="btn btn-sm">عرض</a>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
