<?php
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

$page_title = 'Notifications';

if (!$auth->isLoggedIn() || $auth->isAdmin()) {
    header('Location: ../login.php');
    exit;
}

$current_user = $auth->getCurrentUser();

// Mark notification as read
if (isset($_GET['read']) && isset($_GET['id'])) {
    $notif_id = (int)$_GET['id'];
    $sql = "UPDATE notifications SET is_read = 1, read_at = NOW() WHERE id = ? AND user_id = ?";
    $db->execute($sql, [$notif_id, $current_user['id']]);
    header('Location: notifications.php');
    exit;
}

// Mark all as read
if (isset($_GET['read_all'])) {
    $sql = "UPDATE notifications SET is_read = 1, read_at = NOW() WHERE user_id = ? AND is_read = 0";
    $db->execute($sql, [$current_user['id']]);
    $_SESSION['success'] = "All notifications marked as read";
    header('Location: notifications.php');
    exit;
}

// Delete notification
if (isset($_GET['delete']) && isset($_GET['id'])) {
    $notif_id = (int)$_GET['id'];
    $sql = "DELETE FROM notifications WHERE id = ? AND user_id = ?";
    $db->execute($sql, [$notif_id, $current_user['id']]);
    $_SESSION['success'] = "Notification deleted";
    header('Location: notifications.php');
    exit;
}

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

// Build query
$sql = "SELECT * FROM notifications WHERE user_id = ?";
$params = [$current_user['id']];

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

$sql .= " ORDER BY created_at DESC LIMIT 50";

$notifications = $db->fetchAll($sql, $params);

// Get counts
$unread_count = $db->fetchOne("SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = 0", [$current_user['id']])['count'];
$total_count = $db->fetchOne("SELECT COUNT(*) as count FROM notifications WHERE user_id = ?", [$current_user['id']])['count'];

include 'includes/header.php';
?>

<style>
    .notification-item {
        transition: all 0.3s;
        border-left: 4px solid transparent;
    }
    
    .notification-item:hover {
        background: #f8f9fa;
        border-left-color: var(--primary);
    }
    
    .notification-item.unread {
        background: rgba(212, 160, 23, 0.05);
        border-left-color: var(--primary);
    }
    
    .notification-icon {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.5rem;
    }
    
    .notification-icon.info {
        background: rgba(23, 162, 184, 0.1);
        color: #17a2b8;
    }
    
    .notification-icon.success {
        background: rgba(40, 167, 69, 0.1);
        color: #28a745;
    }
    
    .notification-icon.warning {
        background: rgba(255, 193, 7, 0.1);
        color: #ffc107;
    }
    
    .notification-icon.danger {
        background: rgba(220, 53, 69, 0.1);
        color: #dc3545;
    }
</style>

<div class="page-header d-flex justify-content-between align-items-center">
    <div>
        <h1>Notifications</h1>
        <p class="text-muted mb-0"><?php echo $unread_count; ?> unread notifications</p>
    </div>
    
    <?php if ($unread_count > 0): ?>
    <a href="?read_all=1" class="btn btn-primary">
        <i class="fas fa-check-double"></i> Mark All as Read
    </a>
    <?php endif; ?>
</div>

<!-- Statistics -->
<div class="row mb-4">
    <div class="col-md-6">
        <div class="card">
            <div class="card-body d-flex align-items-center">
                <div class="me-3">
                    <div class="notification-icon warning">
                        <i class="fas fa-bell"></i>
                    </div>
                </div>
                <div>
                    <h3 class="mb-0"><?php echo $unread_count; ?></h3>
                    <p class="text-muted mb-0">Unread Notifications</p>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-6">
        <div class="card">
            <div class="card-body d-flex align-items-center">
                <div class="me-3">
                    <div class="notification-icon info">
                        <i class="fas fa-envelope"></i>
                    </div>
                </div>
                <div>
                    <h3 class="mb-0"><?php echo $total_count; ?></h3>
                    <p class="text-muted mb-0">Total Notifications</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Filters -->
<div class="card mb-4">
    <div class="card-body">
        <div class="btn-group" role="group">
            <a href="?filter=all" class="btn btn-outline-primary <?php echo $filter === 'all' ? 'active' : ''; ?>">
                <i class="fas fa-list"></i> All (<?php echo $total_count; ?>)
            </a>
            <a href="?filter=unread" class="btn btn-outline-warning <?php echo $filter === 'unread' ? 'active' : ''; ?>">
                <i class="fas fa-exclamation-circle"></i> Unread (<?php echo $unread_count; ?>)
            </a>
            <a href="?filter=read" class="btn btn-outline-success <?php echo $filter === 'read' ? 'active' : ''; ?>">
                <i class="fas fa-check-circle"></i> Read
            </a>
        </div>
    </div>
</div>

<!-- Notifications List -->
<?php if (empty($notifications)): ?>
<div class="card">
    <div class="card-body text-center py-5">
        <i class="fas fa-bell-slash fa-5x text-muted mb-4"></i>
        <h4 class="text-muted">No Notifications</h4>
        <p class="text-muted mb-4">You're all caught up!</p>
    </div>
</div>
<?php else: ?>
<div class="card">
    <div class="list-group list-group-flush">
        <?php foreach ($notifications as $notif): ?>
        <div class="list-group-item notification-item <?php echo !$notif['is_read'] ? 'unread' : ''; ?>">
            <div class="d-flex align-items-start">
                <div class="me-3">
                    <?php
                    $icon_type = [
                        'info' => ['icon' => 'fa-info-circle', 'class' => 'info'],
                        'success' => ['icon' => 'fa-check-circle', 'class' => 'success'],
                        'warning' => ['icon' => 'fa-exclamation-triangle', 'class' => 'warning'],
                        'danger' => ['icon' => 'fa-times-circle', 'class' => 'danger']
                    ][$notif['type']] ?? ['icon' => 'fa-bell', 'class' => 'info'];
                    ?>
                    <div class="notification-icon <?php echo $icon_type['class']; ?>">
                        <i class="fas <?php echo $icon_type['icon']; ?>"></i>
                    </div>
                </div>
                
                <div class="flex-grow-1">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <h6 class="mb-1">
                            <?php echo htmlspecialchars($notif['title']); ?>
                            <?php if (!$notif['is_read']): ?>
                            <span class="badge bg-primary ms-2">New</span>
                            <?php endif; ?>
                        </h6>
                        
                        <div class="dropdown">
                            <button class="btn btn-sm btn-link text-muted" data-bs-toggle="dropdown">
                                <i class="fas fa-ellipsis-v"></i>
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end">
                                <?php if (!$notif['is_read']): ?>
                                <li>
                                    <a class="dropdown-item" href="?read=1&id=<?php echo $notif['id']; ?>">
                                        <i class="fas fa-check"></i> Mark as Read
                                    </a>
                                </li>
                                <?php endif; ?>
                                <li>
                                    <a class="dropdown-item text-danger" href="?delete=1&id=<?php echo $notif['id']; ?>"
                                       onclick="return confirm('Delete this notification?')">
                                        <i class="fas fa-trash"></i> Delete
                                    </a>
                                </li>
                            </ul>
                        </div>
                    </div>
                    
                    <p class="mb-2"><?php echo nl2br(htmlspecialchars($notif['message'])); ?></p>
                    
                    <div class="d-flex justify-content-between align-items-center">
                        <small class="text-muted">
                            <i class="far fa-clock"></i>
                            <?php
                            $time_diff = time() - strtotime($notif['created_at']);
                            if ($time_diff < 60) {
                                echo 'Just now';
                            } elseif ($time_diff < 3600) {
                                echo floor($time_diff / 60) . ' minutes ago';
                            } elseif ($time_diff < 86400) {
                                echo floor($time_diff / 3600) . ' hours ago';
                            } else {
                                echo date('M d, Y H:i', strtotime($notif['created_at']));
                            }
                            ?>
                        </small>
                        
                        <?php if (!empty($notif['link'])): ?>
                        <a href="<?php echo htmlspecialchars($notif['link']); ?>" class="btn btn-sm btn-outline-primary">
                            <i class="fas fa-arrow-right"></i> View
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<!-- Notification Settings -->
<div class="card mt-4">
    <div class="card-header">
        <h5 class="mb-0"><i class="fas fa-cog"></i> Notification Settings</h5>
    </div>
    <div class="card-body">
        <p class="text-muted mb-3">Choose how you want to receive notifications</p>
        
        <div class="row">
            <div class="col-md-6">
                <h6 class="mb-3">Email Notifications</h6>
                <div class="form-check mb-2">
                    <input class="form-check-input" type="checkbox" id="emailApp" checked>
                    <label class="form-check-label" for="emailApp">
                        Application updates
                    </label>
                </div>
                <div class="form-check mb-2">
                    <input class="form-check-input" type="checkbox" id="emailPayment" checked>
                    <label class="form-check-label" for="emailPayment">
                        Payment reminders
                    </label>
                </div>
                <div class="form-check mb-2">
                    <input class="form-check-input" type="checkbox" id="emailMessages" checked>
                    <label class="form-check-label" for="emailMessages">
                        New messages
                    </label>
                </div>
            </div>
            
            <div class="col-md-6">
                <h6 class="mb-3">Push Notifications</h6>
                <div class="form-check mb-2">
                    <input class="form-check-input" type="checkbox" id="pushApp">
                    <label class="form-check-label" for="pushApp">
                        Application updates
                    </label>
                </div>
                <div class="form-check mb-2">
                    <input class="form-check-input" type="checkbox" id="pushPayment">
                    <label class="form-check-label" for="pushPayment">
                        Payment reminders
                    </label>
                </div>
                <div class="form-check mb-2">
                    <input class="form-check-input" type="checkbox" id="pushMessages">
                    <label class="form-check-label" for="pushMessages">
                        New messages
                    </label>
                </div>
            </div>
        </div>
        
        <button class="btn btn-primary mt-3">
            <i class="fas fa-save"></i> Save Preferences
        </button>
    </div>
</div>

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