<?php
/**
 * User Notifications Page
 * View all alerts and notifications
 */

define('APP_RUNNING', true);
require_once 'db_connect.php';
require_once 'includes/auth.php';
require_once 'includes/AlertService.php';

initSecureSession();

if(!isAuthenticated() || !validateSession()) {
    header('Location: login');
    exit;
}

$user_id = $_SESSION['user_id'];
$alertService = new AlertService($conn);

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'mark_read' && isset($_POST['notification_id'])) {
        $alertService->markAsRead(intval($_POST['notification_id']), $user_id);
    }

    if ($action === 'mark_all_read') {
        $alertService->markAllAsRead($user_id);
    }

    header('Location: notifications');
    exit;
}

// Get filter
$filter = $_GET['filter'] ?? 'all';
$unreadOnly = ($filter === 'unread');

// Get notifications
$notifications = $alertService->getNotifications($user_id, 50, $unreadOnly);
$unreadCount = $alertService->getUnreadCount($user_id);

// Group notifications by date
$groupedNotifications = [];
foreach ($notifications as $notif) {
    $date = date('Y-m-d', strtotime($notif['created_at']));
    $groupedNotifications[$date][] = $notif;
}

// Get notification type icons and colors
function getNotificationStyle($type) {
    $styles = [
        'satellite_alert' => ['icon' => 'fa-satellite', 'color' => '#ef4444', 'bg' => 'rgba(239, 68, 68, 0.1)'],
        'neighbor_change' => ['icon' => 'fa-map-marker-alt', 'color' => '#f59e0b', 'bg' => 'rgba(245, 158, 11, 0.1)'],
        'neighbor_confirmation' => ['icon' => 'fa-user-check', 'color' => '#3b82f6', 'bg' => 'rgba(59, 130, 246, 0.1)'],
        'neighbor_confirmed' => ['icon' => 'fa-check-circle', 'color' => '#22c55e', 'bg' => 'rgba(34, 197, 94, 0.1)'],
        'neighbor_disputed' => ['icon' => 'fa-exclamation-triangle', 'color' => '#ef4444', 'bg' => 'rgba(239, 68, 68, 0.1)'],
        'overlap_detected' => ['icon' => 'fa-layer-group', 'color' => '#f59e0b', 'bg' => 'rgba(245, 158, 11, 0.1)'],
        'status_change' => ['icon' => 'fa-sync-alt', 'color' => '#8b5cf6', 'bg' => 'rgba(139, 92, 246, 0.1)'],
        'new_land' => ['icon' => 'fa-plus-circle', 'color' => '#22c55e', 'bg' => 'rgba(34, 197, 94, 0.1)'],
        'payment_received' => ['icon' => 'fa-money-bill-wave', 'color' => '#22c55e', 'bg' => 'rgba(34, 197, 94, 0.1)'],
        'certificate_issued' => ['icon' => 'fa-certificate', 'color' => '#d4af37', 'bg' => 'rgba(212, 175, 55, 0.1)'],
        'dispute_raised' => ['icon' => 'fa-gavel', 'color' => '#ef4444', 'bg' => 'rgba(239, 68, 68, 0.1)'],
        'verification_request' => ['icon' => 'fa-clipboard-check', 'color' => '#3b82f6', 'bg' => 'rgba(59, 130, 246, 0.1)'],
        // Fraud report notification types
        'fraud_report' => ['icon' => 'fa-exclamation-triangle', 'color' => '#dc2626', 'bg' => 'rgba(220, 38, 38, 0.1)'],
        'fraud_report_admin' => ['icon' => 'fa-shield-alt', 'color' => '#dc2626', 'bg' => 'rgba(220, 38, 38, 0.1)'],
        'fraud_report_official' => ['icon' => 'fa-user-shield', 'color' => '#dc2626', 'bg' => 'rgba(220, 38, 38, 0.1)'],
        'fraud_report_update' => ['icon' => 'fa-file-alt', 'color' => '#3b82f6', 'bg' => 'rgba(59, 130, 246, 0.1)'],
        'fraud_investigation' => ['icon' => 'fa-search', 'color' => '#f59e0b', 'bg' => 'rgba(245, 158, 11, 0.1)'],
    ];

    return $styles[$type] ?? ['icon' => 'fa-bell', 'color' => '#64748b', 'bg' => 'rgba(100, 116, 139, 0.1)'];
}

function getDateLabel($date) {
    $today = date('Y-m-d');
    $yesterday = date('Y-m-d', strtotime('-1 day'));

    if ($date === $today) return 'Leo / Today';
    if ($date === $yesterday) return 'Jana / Yesterday';

    return date('F j, Y', strtotime($date));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notifications - Land Secure</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/font-awesome/css/all.min.css">
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .app-main {
            margin-left: 280px;
            padding: 24px;
            min-height: 100vh;
            background: #f0f2f5;
        }

        @media (max-width: 1024px) {
            .app-main { margin-left: 0; padding-top: 80px; }
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
            flex-wrap: wrap;
            gap: 16px;
        }

        .page-title {
            font-size: 28px;
            font-weight: 700;
            color: #1e293b;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .unread-badge {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 600;
        }

        .header-actions {
            display: flex;
            gap: 12px;
        }

        .filter-tabs {
            display: flex;
            gap: 8px;
            margin-bottom: 24px;
        }

        .filter-tab {
            padding: 10px 20px;
            border-radius: 10px;
            background: white;
            color: #64748b;
            text-decoration: none;
            font-weight: 500;
            font-size: 14px;
            border: 1px solid #e2e8f0;
            transition: all 0.3s;
        }

        .filter-tab:hover {
            border-color: #667eea;
            color: #667eea;
        }

        .filter-tab.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-color: transparent;
        }

        .notifications-container {
            max-width: 800px;
        }

        .date-group {
            margin-bottom: 32px;
        }

        .date-label {
            font-size: 14px;
            font-weight: 600;
            color: #64748b;
            margin-bottom: 16px;
            padding-left: 4px;
        }

        .notification-card {
            background: white;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.04);
            display: flex;
            gap: 16px;
            transition: all 0.3s;
            border-left: 4px solid transparent;
            position: relative;
        }

        .notification-card:hover {
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            transform: translateY(-2px);
        }

        .notification-card.unread {
            background: #fefce8;
            border-left-color: #f59e0b;
        }

        .notification-card.unread::after {
            content: '';
            position: absolute;
            top: 20px;
            right: 20px;
            width: 10px;
            height: 10px;
            background: #f59e0b;
            border-radius: 50%;
        }

        .notification-icon {
            width: 50px;
            height: 50px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            flex-shrink: 0;
        }

        .notification-content {
            flex: 1;
            min-width: 0;
        }

        .notification-title {
            font-size: 15px;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 6px;
            line-height: 1.4;
        }

        .notification-message {
            font-size: 14px;
            color: #64748b;
            line-height: 1.5;
            margin-bottom: 10px;
        }

        .notification-meta {
            display: flex;
            align-items: center;
            gap: 16px;
            font-size: 12px;
            color: #94a3b8;
        }

        .notification-meta i {
            margin-right: 4px;
        }

        .notification-land {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 4px 10px;
            background: #f1f5f9;
            border-radius: 6px;
            font-size: 12px;
            color: #475569;
            text-decoration: none;
        }

        .notification-land:hover {
            background: #e2e8f0;
            color: #1e293b;
        }

        .notification-actions {
            display: flex;
            gap: 8px;
            margin-top: 12px;
        }

        .btn-action {
            padding: 6px 14px;
            border-radius: 8px;
            font-size: 12px;
            font-weight: 500;
            cursor: pointer;
            border: none;
            transition: all 0.3s;
        }

        .btn-mark-read {
            background: #f1f5f9;
            color: #64748b;
        }

        .btn-mark-read:hover {
            background: #e2e8f0;
            color: #1e293b;
        }

        .btn-view {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-view:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        .empty-state {
            text-align: center;
            padding: 80px 20px;
            color: #64748b;
        }

        .empty-state i {
            font-size: 80px;
            color: #cbd5e1;
            margin-bottom: 24px;
        }

        .empty-state h3 {
            font-size: 20px;
            font-weight: 600;
            color: #475569;
            margin-bottom: 8px;
        }

        .btn-mark-all {
            padding: 10px 20px;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 500;
            color: #64748b;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-mark-all:hover {
            border-color: #22c55e;
            color: #22c55e;
        }

        .severity-critical { border-left-color: #ef4444 !important; }
        .severity-high { border-left-color: #f59e0b !important; }
        .severity-medium { border-left-color: #3b82f6 !important; }
        .severity-low { border-left-color: #22c55e !important; }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="app-main">
        <div class="page-header">
            <div>
                <h1 class="page-title">
                    <i class="fas fa-bell"></i>
                    Notifications
                    <?php if($unreadCount > 0): ?>
                    <span class="unread-badge"><?php echo $unreadCount; ?> unread</span>
                    <?php endif; ?>
                </h1>
            </div>
            <div class="header-actions">
                <?php if($unreadCount > 0): ?>
                <form method="POST" style="display: inline;">
                    <input type="hidden" name="action" value="mark_all_read">
                    <button type="submit" class="btn-mark-all">
                        <i class="fas fa-check-double"></i> Mark All Read
                    </button>
                </form>
                <?php endif; ?>
            </div>
        </div>

        <div class="filter-tabs">
            <a href="notifications" class="filter-tab <?php echo $filter === 'all' ? 'active' : ''; ?>">
                <i class="fas fa-list"></i> All
            </a>
            <a href="notifications?filter=unread" class="filter-tab <?php echo $filter === 'unread' ? 'active' : ''; ?>">
                <i class="fas fa-envelope"></i> Unread
                <?php if($unreadCount > 0): ?>
                <span style="background: rgba(255,255,255,0.2); padding: 2px 8px; border-radius: 10px; margin-left: 6px;">
                    <?php echo $unreadCount; ?>
                </span>
                <?php endif; ?>
            </a>
        </div>

        <div class="notifications-container">
            <?php if(empty($notifications)): ?>
            <div class="empty-state">
                <i class="fas fa-bell-slash"></i>
                <h3>Hakuna Arifa / No Notifications</h3>
                <p>You don't have any <?php echo $unreadOnly ? 'unread ' : ''; ?>notifications yet.</p>
            </div>
            <?php else: ?>

            <?php foreach($groupedNotifications as $date => $dateNotifications): ?>
            <div class="date-group">
                <div class="date-label"><?php echo getDateLabel($date); ?></div>

                <?php foreach($dateNotifications as $notif):
                    $style = getNotificationStyle($notif['notification_type']);
                    $metadata = $notif['metadata'] ? json_decode($notif['metadata'], true) : [];
                    $severity = $metadata['severity'] ?? null;
                ?>
                <div class="notification-card <?php echo !$notif['is_read'] ? 'unread' : ''; ?> <?php echo $severity ? 'severity-' . $severity : ''; ?>">
                    <div class="notification-icon" style="background: <?php echo $style['bg']; ?>; color: <?php echo $style['color']; ?>;">
                        <i class="fas <?php echo $style['icon']; ?>"></i>
                    </div>
                    <div class="notification-content">
                        <div class="notification-title"><?php echo htmlspecialchars($notif['title']); ?></div>
                        <div class="notification-message"><?php echo htmlspecialchars($notif['message']); ?></div>

                        <div class="notification-meta">
                            <span><i class="fas fa-clock"></i> <?php echo date('g:i A', strtotime($notif['created_at'])); ?></span>
                            <?php if($notif['land_name']): ?>
                            <a href="view-land/<?php echo $notif['land_id']; ?>" class="notification-land">
                                <i class="fas fa-map"></i> <?php echo htmlspecialchars($notif['land_name']); ?>
                            </a>
                            <?php endif; ?>
                        </div>

                        <div class="notification-actions">
                            <?php if(!$notif['is_read']): ?>
                            <form method="POST" style="display: inline;">
                                <input type="hidden" name="action" value="mark_read">
                                <input type="hidden" name="notification_id" value="<?php echo $notif['id']; ?>">
                                <button type="submit" class="btn-action btn-mark-read">
                                    <i class="fas fa-check"></i> Mark Read
                                </button>
                            </form>
                            <?php endif; ?>
                            <?php if($notif['land_id']): ?>
                            <a href="view-land/<?php echo $notif['land_id']; ?>" class="btn-action btn-view">
                                <i class="fas fa-eye"></i> View Land
                            </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endforeach; ?>

            <?php endif; ?>
        </div>
    </main>

    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
