<?php
session_start();
require_once 'config/database.php';
require_once 'includes/auth.php';
require_once 'includes/translation.php';
require_once 'includes/functions.php';

if (!isset($_SESSION['user_id'])) {
    redirect('login.php');
}

$db = new Database();
$conn = $db->getConnection();

$message = '';
$error = '';

// Handle actions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';
    
    try {
        switch($action) {
            case 'mark_read':
                $notification_id = intval($_POST['notification_id']);
                $stmt = $conn->prepare("UPDATE notifications SET is_read = 1, read_at = NOW() WHERE id = ? AND user_id = ?");
                $stmt->execute([$notification_id, $_SESSION['user_id']]);
                $message = __('notification_marked_read');
                break;
                
            case 'mark_all_read':
                $stmt = $conn->prepare("UPDATE notifications SET is_read = 1, read_at = NOW() WHERE user_id = ? AND is_read = 0");
                $stmt->execute([$_SESSION['user_id']]);
                $message = __('all_notifications_read');
                break;
                
            case 'delete':
                $notification_id = intval($_POST['notification_id']);
                $stmt = $conn->prepare("DELETE FROM notifications WHERE id = ? AND user_id = ?");
                $stmt->execute([$notification_id, $_SESSION['user_id']]);
                $message = __('notification_deleted');
                break;
                
            case 'delete_all_read':
                $stmt = $conn->prepare("DELETE FROM notifications WHERE user_id = ? AND is_read = 1");
                $stmt->execute([$_SESSION['user_id']]);
                $message = __('all_read_notifications_deleted');
                break;
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

// Get filter
$filter = $_GET['filter'] ?? 'all';

// Build query based on filter
$query = "SELECT * FROM notifications WHERE user_id = ?";
$params = [$_SESSION['user_id']];

if ($filter == 'unread') {
    $query .= " AND is_read = 0";
} elseif ($filter == 'read') {
    $query .= " AND is_read = 1";
}

$query .= " ORDER BY created_at DESC LIMIT 100";

$stmt = $conn->prepare($query);
$stmt->execute($params);
$notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get counts
$stmt = $conn->prepare("SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = 0");
$stmt->execute([$_SESSION['user_id']]);
$unread_count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];

$stmt = $conn->prepare("SELECT COUNT(*) as count FROM notifications WHERE user_id = ?");
$stmt->execute([$_SESSION['user_id']]);
$total_count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];

// Set page title
$page_title = __('notifications_page') . ' - ' . __('system_name');

// Include header
include 'includes/header.php';
?>

<style>
.notification-item {
    border-left: 4px solid #dee2e6;
    transition: all 0.3s ease;
}

.notification-item.unread {
    border-left-color: #007bff;
    background-color: #f8f9fa;
}

.notification-item:hover {
    background-color: #f1f3f4;
}

.notification-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.2rem;
}

.notification-icon.info { background-color: #d1ecf1; color: #0c5460; }
.notification-icon.success { background-color: #d4edda; color: #155724; }
.notification-icon.warning { background-color: #fff3cd; color: #856404; }
.notification-icon.danger { background-color: #f8d7da; color: #721c24; }

.notification-time {
    font-size: 0.85rem;
    color: #6c757d;
}

.mark-read-btn {
    opacity: 0;
    transition: opacity 0.3s ease;
}

.notification-item:hover .mark-read-btn {
    opacity: 1;
}
</style>

<!-- Main Content -->

    <!-- Success/Error Messages -->
    <?php if ($message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i>
            <?php echo $message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle me-2"></i>
            <?php echo $error; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-0">
                <i class="fas fa-bell me-2"></i>
                <?php echo Translation::getDirection() == 'rtl' ? 'الإشعارات' : 'Notifications'; ?>
                <?php if ($unread_count > 0): ?>
                    <span class="badge bg-danger"><?php echo $unread_count; ?></span>
                <?php endif; ?>
            </h1>
            <p class="text-muted mb-0">
                <?php echo Translation::getDirection() == 'rtl' ? 'الإجمالي' : 'Total'; ?>: <?php echo $total_count; ?> | 
                <?php echo Translation::getDirection() == 'rtl' ? 'غير مقروءة' : 'Unread'; ?>: <?php echo $unread_count; ?>
            </p>
        </div>
        <div>
            <?php if ($unread_count > 0): ?>
                <form method="POST" class="d-inline">
                    <input type="hidden" name="action" value="mark_all_read">
                    <button type="submit" class="btn btn-primary me-2">
                        <i class="fas fa-check-double"></i> 
                        <?php echo Translation::getDirection() == 'rtl' ? 'تحديد الكل كمقروء' : 'Mark All as Read'; ?>
                    </button>
                </form>
            <?php endif; ?>
            <?php if ($total_count > $unread_count && $total_count > 0): ?>
                <button type="button" class="btn btn-danger me-2" onclick="confirmDeleteAllRead()">
                    <i class="fas fa-trash"></i> 
                    <?php echo Translation::getDirection() == 'rtl' ? 'حذف المقروءة' : 'Delete Read'; ?>
                </button>
            <?php endif; ?>
            <a href="index.php" class="btn btn-secondary">
                <i class="fas fa-arrow-<?php echo Translation::getDirection() == 'rtl' ? 'right' : 'left'; ?>"></i> 
                <?php echo Translation::getDirection() == 'rtl' ? 'رجوع' : 'Back'; ?>
            </a>
        </div>
    </div>

    <!-- Filter Tabs -->
    <ul class="nav nav-pills mb-4">
        <li class="nav-item">
            <a class="nav-link <?php echo $filter == 'all' ? 'active' : ''; ?>" href="?filter=all">
                <i class="fas fa-list me-1"></i> 
                <?php echo Translation::getDirection() == 'rtl' ? 'الكل' : 'all'; ?> 
                (<?php echo $total_count; ?>)
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link <?php echo $filter == 'unread' ? 'active' : ''; ?>" href="?filter=unread">
                <i class="fas fa-envelope me-1"></i> 
                <?php echo Translation::getDirection() == 'rtl' ? 'غير مقروءة' : 'unread'; ?> 
                (<?php echo $unread_count; ?>)
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link <?php echo $filter == 'read' ? 'active' : ''; ?>" href="?filter=read">
                <i class="fas fa-envelope-open me-1"></i> 
                <?php echo Translation::getDirection() == 'rtl' ? 'مقروءة' : 'read'; ?> 
                (<?php echo $total_count - $unread_count; ?>)
            </a>
        </li>
    </ul>

    <!-- Notifications List -->
    <div class="card shadow">
        <div class="card-body p-0">
            <?php if (empty($notifications)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-bell-slash fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted">
                        <?php echo Translation::getDirection() == 'rtl' ? 'لا توجد إشعارات' : 'No Notifications'; ?>
                    </h5>
                    <p class="text-muted">
                        <?php echo Translation::getDirection() == 'rtl' ? 'ستظهر الإشعارات هنا عند توفرها' : 'Notifications will appear here when available'; ?>
                    </p>
                </div>
            <?php else: ?>
                <div class="list-group list-group-flush">
                    <?php foreach ($notifications as $notification): ?>
                        <div class="list-group-item notification-item <?php echo !$notification['is_read'] ? 'unread' : ''; ?>">
                            <div class="d-flex align-items-start">
                                <div class="notification-icon <?php echo $notification['type']; ?> me-3">
                                    <?php
                                    $icons = [
                                        'info' => 'fas fa-info',
                                        'success' => 'fas fa-check',
                                        'warning' => 'fas fa-exclamation-triangle',
                                        'danger' => 'fas fa-times-circle'
                                    ];
                                    echo '<i class="' . ($icons[$notification['type']] ?? 'fas fa-bell') . '"></i>';
                                    ?>
                                </div>
                                
                                <div class="flex-grow-1">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div class="flex-grow-1">
                                            <?php
                                            // Translate notification titles
                                            $title = $notification['title'];
                                            $message = $notification['message'];
                                            
                                            if (Translation::getDirection() == 'ltr') {
                                                // Translate common Arabic titles to English
                                                $translations = [
                                                    'مراجعة في النظام' => 'System Review',
                                                    'تقرير جديد' => 'New Report',
                                                    'تنبيه مهم' => 'Important Alert',
                                                    'تم تسجيل دخولك بنجاح إلى نظام إدارة الاستعدادات الجديدة' => 'You have successfully logged into the new preparedness management system',
                                                    'تم إضافة تقرير جديد يحتاج إلى مراجعة' => 'A new report has been added that needs review',
                                                    'يوجد تقرير مهم يحتاج إلى متابعة' => 'There is an important report that needs follow-up'
                                                ];
                                                
                                                $title = $translations[$title] ?? $title;
                                                $message = $translations[$message] ?? $message;
                                            }
                                            ?>
                                            <h6 class="mb-1 <?php echo !$notification['is_read'] ? 'fw-bold' : ''; ?>">
                                                <?php echo htmlspecialchars($title); ?>
                                            </h6>
                                            <p class="mb-1 text-muted">
                                                <?php echo htmlspecialchars($message); ?>
                                            </p>
                                            <small class="notification-time">
                                                <i class="fas fa-clock me-1"></i>
                                                <?php echo formatTimeAgo($notification['created_at']); ?>
                                            </small>
                                        </div>
                                        
                                        <div class="d-flex gap-1 ms-3">
                                            <?php if (!$notification['is_read']): ?>
                                                <form method="POST" class="d-inline">
                                                    <input type="hidden" name="action" value="mark_read">
                                                    <input type="hidden" name="notification_id" value="<?php echo $notification['id']; ?>">
                                                    <button type="submit" class="btn btn-sm btn-outline-success" title="<?php echo Translation::getDirection() == 'rtl' ? 'تحديد كمقروء' : 'Mark as Read'; ?>">
                                                        <i class="fas fa-check"></i>
                                                    </button>
                                                </form>
                                            <?php endif; ?>
                                            <form method="POST" class="d-inline" onsubmit="return confirm('<?php echo Translation::getDirection() == 'rtl' ? 'هل تريد حذف هذا الإشعار؟' : 'Delete this notification?'; ?>')">
                                                <input type="hidden" name="action" value="delete">
                                                <input type="hidden" name="notification_id" value="<?php echo $notification['id']; ?>">
                                                <button type="submit" class="btn btn-sm btn-outline-danger" title="<?php echo Translation::getDirection() == 'rtl' ? 'حذف' : 'Delete'; ?>">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Notification Settings -->
    <div class="card shadow mt-4">
        <div class="card-header bg-primary text-white">
            <h6 class="mb-0">
                <i class="fas fa-cog me-2"></i>
                <?php echo Translation::getDirection() == 'rtl' ? 'إعدادات الإشعارات' : 'Notification Settings'; ?>
            </h6>
        </div>
        <div class="card-body">
            <p class="text-muted mb-4">
                <i class="fas fa-info-circle me-2"></i>
                <?php echo Translation::getDirection() == 'rtl' ? 'اختر أنواع الإشعارات التي تريد استلامها' : 'Choose the types of notifications you want to receive'; ?>
            </p>
            
            <form method="POST">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-check form-switch mb-3 p-3 border rounded">
                            <input class="form-check-input" type="checkbox" id="email_notifications" checked>
                            <label class="form-check-label fw-bold" for="email_notifications">
                                <i class="fas fa-envelope text-primary me-2"></i>
                                <?php echo Translation::getDirection() == 'rtl' ? 'إشعارات البريد الإلكتروني' : 'Email Notifications'; ?>
                            </label>
                            <small class="d-block text-muted mt-1">
                                <?php echo Translation::getDirection() == 'rtl' ? 'استلام إشعارات عبر البريد الإلكتروني' : 'Receive notifications via email'; ?>
                            </small>
                        </div>
                        
                        <div class="form-check form-switch mb-3 p-3 border rounded">
                            <input class="form-check-input" type="checkbox" id="report_notifications" checked>
                            <label class="form-check-label fw-bold" for="report_notifications">
                                <i class="fas fa-file-medical text-success me-2"></i>
                                <?php echo Translation::getDirection() == 'rtl' ? 'إشعارات التقارير' : 'Report Notifications'; ?>
                            </label>
                            <small class="d-block text-muted mt-1">
                                <?php echo Translation::getDirection() == 'rtl' ? 'إشعارات عند إضافة تقارير جديدة' : 'Notifications when new reports are added'; ?>
                            </small>
                        </div>
                        
                        <div class="form-check form-switch mb-3 p-3 border rounded">
                            <input class="form-check-input" type="checkbox" id="patient_notifications" checked>
                            <label class="form-check-label fw-bold" for="patient_notifications">
                                <i class="fas fa-user-injured text-info me-2"></i>
                                <?php echo Translation::getDirection() == 'rtl' ? 'إشعارات المرضى' : 'Patient Notifications'; ?>
                            </label>
                            <small class="d-block text-muted mt-1">
                                <?php echo Translation::getDirection() == 'rtl' ? 'إشعارات عند إضافة أو تحديث بيانات المرضى' : 'Notifications when patient data is added or updated'; ?>
                            </small>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="form-check form-switch mb-3 p-3 border rounded">
                            <input class="form-check-input" type="checkbox" id="system_notifications" checked>
                            <label class="form-check-label fw-bold" for="system_notifications">
                                <i class="fas fa-cogs text-secondary me-2"></i>
                                <?php echo Translation::getDirection() == 'rtl' ? 'إشعارات النظام' : 'System Notifications'; ?>
                            </label>
                            <small class="d-block text-muted mt-1">
                                <?php echo Translation::getDirection() == 'rtl' ? 'إشعارات النظام والتحديثات' : 'System notifications and updates'; ?>
                            </small>
                        </div>
                        
                        <div class="form-check form-switch mb-3 p-3 border rounded">
                            <input class="form-check-input" type="checkbox" id="urgent_notifications" checked>
                            <label class="form-check-label fw-bold" for="urgent_notifications">
                                <i class="fas fa-exclamation-triangle text-warning me-2"></i>
                                <?php echo Translation::getDirection() == 'rtl' ? 'الإشعارات العاجلة' : 'Urgent Notifications'; ?>
                            </label>
                            <small class="d-block text-muted mt-1">
                                <?php echo Translation::getDirection() == 'rtl' ? 'إشعارات الحالات العاجلة والمهمة' : 'Notifications for urgent and important cases'; ?>
                            </small>
                        </div>
                        
                        <div class="form-check form-switch mb-3 p-3 border rounded">
                            <input class="form-check-input" type="checkbox" id="antibiotic_notifications" checked>
                            <label class="form-check-label fw-bold" for="antibiotic_notifications">
                                <i class="fas fa-pills text-danger me-2"></i>
                                <?php echo Translation::getDirection() == 'rtl' ? 'إشعارات المضادات الحيوية' : 'Antibiotic Notifications'; ?>
                            </label>
                            <small class="d-block text-muted mt-1">
                                <?php echo Translation::getDirection() == 'rtl' ? 'إشعارات عند إضافة أو تعديل المضادات الحيوية' : 'Notifications when antibiotics are added or modified'; ?>
                            </small>
                        </div>
                    </div>
                </div>
                
                <div class="text-center mt-3">
                    <button type="submit" class="btn btn-primary btn-lg">
                        <i class="fas fa-save me-2"></i> 
                        <?php echo Translation::getDirection() == 'rtl' ? 'حفظ الإعدادات' : 'Save Settings'; ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete All Read Confirmation Form -->
<form id="deleteAllReadForm" method="POST" style="display: none;">
    <input type="hidden" name="action" value="delete_all_read">
</form>

<script>
function confirmDeleteAllRead() {
    if (confirm('<?php echo Translation::getDirection() == 'rtl' ? 'هل تريد حذف جميع الإشعارات المقروءة؟' : 'Delete all read notifications?'; ?>')) {
        document.getElementById('deleteAllReadForm').submit();
    }
}

// Auto-refresh notifications every 60 seconds
setInterval(function() {
    fetch('api/check_notifications.php')
        .then(response => response.json())
        .then(data => {
            if (data.new_notifications > 0) {
                // Show notification badge update
                const badge = document.querySelector('.badge.bg-danger');
                if (badge) {
                    const currentCount = parseInt(badge.textContent);
                    badge.textContent = currentCount + data.new_notifications;
                }
            }
        })
        .catch(error => console.log('Error checking notifications:', error));
}, 60000);
</script>

<?php include 'includes/footer.php'; ?>
