<?php
/**
 * صفحة التنبيهات - Smart Doctor
 */
$page = 'alerts';
$filter = $_GET['filter'] ?? 'all'; // all, unread, critical, urgent
$pageNum = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($pageNum - 1) * $perPage;

$alerts = [];
$totalAlerts = 0;
$unreadCount = 0;

try {
    $db->query('SELECT id FROM doctor_alerts LIMIT 1');
    
    // عدد التنبيهات غير المقروءة
    $stmt = $db->prepare('SELECT COUNT(*) FROM doctor_alerts WHERE doctor_account_id = ? AND is_read = 0');
    $stmt->execute([$doctorAuth->accountId()]);
    $unreadCount = (int)$stmt->fetchColumn();
    
    // بناء الاستعلام
    $where = 'doctor_account_id = ?';
    $params = [$doctorAuth->accountId()];
    
    if ($filter === 'unread') {
        $where .= ' AND is_read = 0';
    } elseif ($filter === 'critical') {
        $where .= ' AND alert_type = "critical"';
    } elseif ($filter === 'urgent') {
        $where .= ' AND priority = "urgent"';
    }
    
    // عدد التنبيهات
    $stmt = $db->prepare("SELECT COUNT(*) FROM doctor_alerts WHERE $where");
    $stmt->execute($params);
    $totalAlerts = (int)$stmt->fetchColumn();
    
    // جلب التنبيهات
    $stmt = $db->prepare("SELECT * FROM doctor_alerts WHERE $where ORDER BY created_at DESC LIMIT ? OFFSET ?");
    $params[] = $perPage;
    $params[] = $offset;
    $stmt->execute($params);
    $alerts = $stmt->fetchAll();
} catch (Throwable $e) {}

// تحديث التنبيهات المقروءة عند فتح الصفحة
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mark_all_read'])) {
    try {
        $db->prepare('UPDATE doctor_alerts SET is_read = 1, read_at = NOW() WHERE doctor_account_id = ? AND is_read = 0')->execute([$doctorAuth->accountId()]);
        $_SESSION['doctor_msg'] = 'تم تحديد جميع التنبيهات كمقروءة.';
        header('Location: doctor.php?page=alerts');
        exit;
    } catch (Throwable $e) {}
}

// تحديد تنبيه كمقروء
if (isset($_GET['mark_read']) && $_GET['mark_read'] > 0) {
    $alertId = (int)$_GET['mark_read'];
    try {
        $stmt = $db->prepare('UPDATE doctor_alerts SET is_read = 1, read_at = NOW() WHERE id = ? AND doctor_account_id = ?');
        $stmt->execute([$alertId, $doctorAuth->accountId()]);
        if (isset($_GET['redirect'])) {
            header('Location: ' . urldecode($_GET['redirect']));
        } else {
            header('Location: doctor.php?page=alerts');
        }
        exit;
    } catch (Throwable $e) {}
}

// حذف تنبيه
if (isset($_GET['delete']) && $_GET['delete'] > 0) {
    $alertId = (int)$_GET['delete'];
    try {
        $db->prepare('DELETE FROM doctor_alerts WHERE id = ? AND doctor_account_id = ?')->execute([$alertId, $doctorAuth->accountId()]);
        $_SESSION['doctor_msg'] = 'تم حذف التنبيه.';
        header('Location: doctor.php?page=alerts');
        exit;
    } 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">
    <link rel="icon" type="image/svg+xml" href="favicon.svg">
    <title>التنبيهات - Smart Doctor</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
<?php include __DIR__ . '/_layout.php'; ?>
<main class="content">
    <div class="page-header" style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:16px;margin-bottom:24px;">
        <div>
            <h1>🔔 التنبيهات</h1>
            <p style="color:var(--text-muted);margin:4px 0 0;">إدارة جميع التنبيهات والإشعارات</p>
        </div>
        <div style="display:flex;gap:8px;flex-wrap:wrap;">
            <?php if ($unreadCount > 0): ?>
            <form method="post" style="margin:0;">
                <button type="submit" name="mark_all_read" class="btn-secondary">✓ تحديد الكل كمقروء</button>
            </form>
            <?php endif; ?>
            <a href="doctor.php?page=profile&tab=alert_settings" class="btn-secondary">⚙️ إعدادات التنبيهات</a>
        </div>
    </div>

    <!-- فلاتر -->
    <div class="card" style="margin-bottom:20px;">
        <div style="display:flex;gap:8px;flex-wrap:wrap;padding:12px;">
            <a href="doctor.php?page=alerts&filter=all" class="btn-secondary <?php echo $filter === 'all' ? 'active' : ''; ?>" style="<?php echo $filter === 'all' ? 'background:var(--primary);color:white;' : ''; ?>">الكل (<?php echo $totalAlerts; ?>)</a>
            <a href="doctor.php?page=alerts&filter=unread" class="btn-secondary <?php echo $filter === 'unread' ? 'active' : ''; ?>" style="<?php echo $filter === 'unread' ? 'background:var(--primary);color:white;' : ''; ?>">
                غير مقروءة <?php if ($unreadCount > 0): ?><span style="background:#ef4444;color:white;padding:2px 6px;border-radius:10px;font-size:0.75rem;margin-right:4px;"><?php echo $unreadCount; ?></span><?php endif; ?>
            </a>
            <a href="doctor.php?page=alerts&filter=critical" class="btn-secondary <?php echo $filter === 'critical' ? 'active' : ''; ?>" style="<?php echo $filter === 'critical' ? 'background:var(--primary);color:white;' : ''; ?>">حرجة</a>
            <a href="doctor.php?page=alerts&filter=urgent" class="btn-secondary <?php echo $filter === 'urgent' ? 'active' : ''; ?>" style="<?php echo $filter === 'urgent' ? 'background:var(--primary);color:white;' : ''; ?>">عاجلة</a>
        </div>
    </div>

    <!-- قائمة التنبيهات -->
    <?php if (empty($alerts)): ?>
    <div class="card" style="text-align:center;padding:48px 24px;">
        <div style="font-size:3rem;margin-bottom:16px;opacity:0.5;">🔔</div>
        <h3 style="margin:0 0 8px;">لا توجد تنبيهات</h3>
        <p style="color:var(--text-muted);margin:0;">جميع التنبيهات محدثة</p>
    </div>
    <?php else: ?>
    <div class="card">
        <div style="display:flex;flex-direction:column;gap:0;">
            <?php foreach ($alerts as $alert): ?>
            <div class="doctor-alert-item" style="padding:16px;border-bottom:1px solid var(--border);display:flex;gap:16px;align-items:flex-start;transition:background 0.2s;<?php echo $alert['is_read'] == 0 ? 'background:rgba(13,148,136,0.05);' : ''; ?>">
                <div style="flex-shrink:0;">
                    <?php
                    $icons = ['critical' => '⚠️', 'reminder' => '⏰', 'appointment' => '📅', 'system' => '⚙️', 'info' => 'ℹ️'];
                    $colors = ['critical' => '#ef4444', 'reminder' => '#f59e0b', 'appointment' => '#3b82f6', 'system' => '#6b7280', 'info' => '#0d9488'];
                    $priorityColors = ['low' => '#6b7280', 'medium' => '#3b82f6', 'high' => '#f59e0b', 'urgent' => '#ef4444'];
                    $icon = $icons[$alert['alert_type']] ?? 'ℹ️';
                    $color = $colors[$alert['alert_type']] ?? '#0d9488';
                    ?>
                    <div style="width:40px;height:40px;border-radius:50%;background:<?php echo $color; ?>20;display:flex;align-items:center;justify-content:center;font-size:1.5rem;">
                        <?php echo $icon; ?>
                    </div>
                </div>
                <div style="flex:1;min-width:0;">
                    <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;margin-bottom:6px;">
                        <h3 style="margin:0;font-size:1.05rem;<?php echo $alert['is_read'] == 0 ? 'font-weight:600;' : ''; ?>">
                            <?php echo htmlspecialchars($alert['title'], ENT_QUOTES, 'UTF-8'); ?>
                        </h3>
                        <div style="display:flex;gap:6px;flex-shrink:0;">
                            <?php if ($alert['priority'] !== 'low'): ?>
                            <span style="padding:4px 8px;background:<?php echo $priorityColors[$alert['priority']]; ?>20;color:<?php echo $priorityColors[$alert['priority']]; ?>;border-radius:6px;font-size:0.75rem;font-weight:500;">
                                <?php echo $alert['priority'] === 'urgent' ? 'عاجل' : ($alert['priority'] === 'high' ? 'مهم' : 'متوسط'); ?>
                            </span>
                            <?php endif; ?>
                            <?php if ($alert['is_read'] == 0): ?>
                            <span style="width:8px;height:8px;background:#0d9488;border-radius:50%;margin-top:6px;"></span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php if ($alert['message']): ?>
                    <p style="margin:0 0 8px;color:var(--text-secondary);line-height:1.5;">
                        <?php echo nl2br(htmlspecialchars($alert['message'], ENT_QUOTES, 'UTF-8')); ?>
                    </p>
                    <?php endif; ?>
                    <div style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;font-size:0.85rem;color:var(--text-muted);">
                        <span>🕐 <?php echo date('Y-m-d H:i', strtotime($alert['created_at'])); ?></span>
                        <?php if ($alert['action_url']): ?>
                        <a href="<?php echo htmlspecialchars($alert['action_url'], ENT_QUOTES, 'UTF-8'); ?>" class="btn-sm" style="padding:4px 10px;">عرض ←</a>
                        <?php endif; ?>
                    </div>
                </div>
                <div style="flex-shrink:0;display:flex;flex-direction:column;gap:6px;">
                    <?php if ($alert['is_read'] == 0): ?>
                    <a href="doctor.php?page=alerts&mark_read=<?php echo $alert['id']; ?>" class="btn-sm" style="padding:4px 10px;white-space:nowrap;" title="تحديد كمقروء">✓</a>
                    <?php endif; ?>
                    <a href="doctor.php?page=alerts&delete=<?php echo $alert['id']; ?>" onclick="return confirm('هل أنت متأكد من حذف هذا التنبيه؟');" style="padding:4px 10px;color:#ef4444;font-size:0.85rem;" title="حذف">🗑️</a>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        
        <!-- Pagination -->
        <?php if ($totalAlerts > $perPage): ?>
        <div style="padding:16px;border-top:1px solid var(--border);display:flex;justify-content:center;gap:8px;">
            <?php
            $totalPages = ceil($totalAlerts / $perPage);
            if ($pageNum > 1):
            ?>
            <a href="doctor.php?page=alerts&filter=<?php echo $filter; ?>&page=<?php echo $pageNum - 1; ?>" class="btn-secondary">← السابق</a>
            <?php endif; ?>
            <span style="padding:8px 16px;color:var(--text-muted);">صفحة <?php echo $pageNum; ?> من <?php echo $totalPages; ?></span>
            <?php if ($pageNum < $totalPages): ?>
            <a href="doctor.php?page=alerts&filter=<?php echo $filter; ?>&page=<?php echo $pageNum + 1; ?>" class="btn-secondary">التالي →</a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</main>
</body>
</html>
