<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
    header('Location: admin-login.php');
    exit;
}

// Get admin data
$stmt = $pdo->prepare("SELECT a.*, u.email FROM admins a JOIN users u ON a.id = u.id WHERE a.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin) {
    die("Admin profile not found.");
}

// Get notification filters
$type_filter = $_GET['type'] ?? '';
$status_filter = $_GET['status'] ?? '';
$user_filter = $_GET['user'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$search = $_GET['search'] ?? '';

// Build query
$sql = "SELECT n.*, u.email, 
        CASE 
            WHEN u.user_type = 'student' THEN CONCAT(s.first_name, ' ', s.last_name)
            WHEN u.user_type = 'counselor' THEN CONCAT(c.first_name, ' ', c.last_name)
            WHEN u.user_type = 'admin' THEN CONCAT(ad.first_name, ' ', ad.last_name)
            ELSE u.email
        END as user_name,
        u.user_type
        FROM notifications n
        JOIN users u ON n.user_id = u.id
        LEFT JOIN students s ON u.id = s.id
        LEFT JOIN counselors c ON u.id = c.id
        LEFT JOIN admins ad ON u.id = ad.id";

$conditions = [];
$params = [];

if ($type_filter) {
    $conditions[] = "n.notification_type = ?";
    $params[] = $type_filter;
}

if ($status_filter) {
    $conditions[] = "n.is_read = ?";
    $params[] = $status_filter === 'unread' ? 0 : 1;
}

if ($user_filter) {
    $conditions[] = "n.user_id = ?";
    $params[] = $user_filter;
}

if ($date_from) {
    $conditions[] = "n.created_at >= ?";
    $params[] = $date_from;
}

if ($date_to) {
    $conditions[] = "n.created_at <= ?";
    $params[] = $date_to;
}

if ($search) {
    $conditions[] = "(n.message LIKE ? OR n.title LIKE ? OR u.email LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($conditions) {
    $sql .= " WHERE " . implode(" AND ", $conditions);
}

$sql .= " ORDER BY n.is_read ASC, n.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$notifications = $stmt->fetchAll();

// Get stats
$stats = [
    'total' => $pdo->query("SELECT COUNT(*) FROM notifications")->fetchColumn(),
    'unread' => $pdo->query("SELECT COUNT(*) FROM notifications WHERE is_read = 0")->fetchColumn(),
    'read' => $pdo->query("SELECT COUNT(*) FROM notifications WHERE is_read = 1")->fetchColumn(),
    'by_type' => $pdo->query("SELECT notification_type, COUNT(*) as count FROM notifications GROUP BY notification_type ORDER BY count DESC")->fetchAll(),
];

// Get users for filter
$users = $pdo->query("SELECT u.id, u.email, u.user_type, 
                     CONCAT(s.first_name, ' ', s.last_name) as student_name,
                     CONCAT(c.first_name, ' ', c.last_name) as counselor_name,
                     CONCAT(ad.first_name, ' ', ad.last_name) as admin_name
                     FROM users u
                     LEFT JOIN students s ON u.id = s.id
                     LEFT JOIN counselors c ON u.id = c.id
                     LEFT JOIN admins ad ON u.id = ad.id
                     WHERE u.user_type IN ('student', 'counselor', 'admin')
                     ORDER BY u.user_type, u.email")->fetchAll();

// Handle mark as read
if (isset($_GET['mark_read']) && $_GET['mark_read'] == 'all') {
    $pdo->query("UPDATE notifications SET is_read = 1 WHERE is_read = 0");
    header('Location: admin-notifications.php');
    exit;
}

// Handle mark as unread
if (isset($_GET['mark_unread']) && $_GET['mark_unread'] == 'all') {
    $pdo->query("UPDATE notifications SET is_read = 0 WHERE is_read = 1");
    header('Location: admin-notifications.php');
    exit;
}

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Notifications - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .stat-card {
            border-left: 5px solid #3fb7fe;
            margin-bottom: 20px;
        }
        .notification-item {
            border-left: 3px solid #3fb7fe;
            padding-left: 15px;
            margin-bottom: 15px;
            opacity: 1;
        }
        .notification-item.unread {
            opacity: 1;
            background: #f8f9ff;
        }
        .notification-item .title {
            font-weight: 600;
        }
        .notification-item .user-info {
            font-size: 0.9em;
            color: #6c757d;
        }
        .notification-type {
            font-size: 0.8em;
            padding: 3px 8px;
            border-radius: 15px;
            font-weight: 600;
        }
        .type-system {
            background: #d6d8d9;
            color: #383d41;
        }
        .type-application {
            background: #d4edda;
            color: #155724;
        }
        .type-payment {
            background: #fff3cd;
            color: #856404;
        }
        .type-document {
            background: #f8d7da;
            color: #721c24;
        }
        .type-appointment {
            background: #d1ecf1;
            color: #0c5460;
        }
    </style>
</head>
<body>

<?php include 'admin-navbar.php'; ?>

<div class="container py-5">
    <div class="section-title position-relative mb-4">
        <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">System</h6>
        <h1 class="display-5">Notifications</h1>
    </div>

    <!-- Search and Filter -->
    <div class="row mb-4">
        <div class="col-lg-8">
            <form method="GET" class="d-flex">
                <div class="flex-grow-1 mr-2">
                    <input type="text" name="search" class="form-control" placeholder="Search by message, title, or user" 
                           value="<?= htmlspecialchars($search) ?>">
                </div>
                <button type="submit" class="btn btn-primary">Search</button>
            </form>
        </div>
        <div class="col-lg-4">
            <div class="row">
                <div class="col-md-6 mb-2">
                    <select name="type" class="form-control" onchange="window.location='admin-notifications.php?type='+this.value<?= $status_filter ? '&status='.urlencode($status_filter) : '' ?><?= $user_filter ? '&user='.urlencode($user_filter) : '' ?><?= $date_from ? '&date_from='.urlencode($date_from) : '' ?><?= $date_to ? '&date_to='.urlencode($date_to) : '' ?><?= $search ? '&search='.urlencode($search) : '' ?>">
                        <option value="">All Types</option>
                        <option value="system" <?= $type_filter === 'system' ? 'selected' : '' ?>>System</option>
                        <option value="application" <?= $type_filter === 'application' ? 'selected' : '' ?>>Applications</option>
                        <option value="payment" <?= $type_filter === 'payment' ? 'selected' : '' ?>>Payments</option>
                        <option value="document" <?= $type_filter === 'document' ? 'selected' : '' ?>>Documents</option>
                        <option value="appointment" <?= $type_filter === 'appointment' ? 'selected' : '' ?>>Appointments</option>
                    </select>
                </div>
                <div class="col-md-6 mb-2">
                    <select name="status" class="form-control" onchange="window.location='admin-notifications.php<?= $type_filter ? '&type='.urlencode($type_filter) : '' ?>&status='+this.value<?= $user_filter ? '&user='.urlencode($user_filter) : '' ?><?= $date_from ? '&date_from='.urlencode($date_from) : '' ?><?= $date_to ? '&date_to='.urlencode($date_to) : '' ?><?= $search ? '&search='.urlencode($search) : '' ?>">
                        <option value="">All Statuses</option>
                        <option value="unread" <?= $status_filter === 'unread' ? 'selected' : '' ?>>Unread (<?= $stats['unread'] ?>)</option>
                        <option value="read" <?= $status_filter === 'read' ? 'selected' : '' ?>>Read (<?= $stats['read'] ?>)</option>
                    </select>
                </div>
            </div>
        </div>
    </div>

    <!-- Date Filter -->
    <div class="row mb-4">
        <div class="col-lg-6">
            <form method="GET" class="d-flex">
                <div class="flex-grow-1 mr-2">
                    <label>Date From</label>
                    <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($date_from) ?>">
                </div>
                <div class="flex-grow-1 mr-2">
                    <label>Date To</label>
                    <input type="date" name="date_to" class="form-control" value="<?= htmlspecialchars($date_to) ?>">
                </div>
                <div class="align-self-end">
                    <button type="submit" class="btn btn-primary">Filter</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Stats -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="stat-card">
                <div class="card-body">
                    <h6>Total Notifications</h6>
                    <h3><?= $stats['total'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="stat-card" style="border-left-color: #ffc107;">
                <div class="card-body">
                    <h6>Unread</h6>
                    <h3><?= $stats['unread'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="stat-card" style="border-left-color: #28a745;">
                <div class="card-body">
                    <h6>Read</h6>
                    <h3><?= $stats['read'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="text-right">
                <?php if ($stats['unread'] > 0): ?>
                <a href="admin-notifications.php?mark_read=all" class="btn btn-warning btn-sm">Mark All Read</a>
                <?php else: ?>
                <a href="admin-notifications.php?mark_unread=all" class="btn btn-secondary btn-sm">Mark All Unread</a>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Notifications List -->
    <div class="bg-white p-4 rounded">
        <?php if (empty($notifications)): ?>
        <div class="text-center py-5">
            <i class="fas fa-bell fa-3x text-muted mb-3"></i>
            <p>No notifications found for the selected criteria.</p>
        </div>
        <?php else: ?>
        <?php foreach ($notifications as $notification): ?>
        <div class="notification-item <?= $notification['is_read'] ? '' : 'unread' ?>">
            <div class="d-flex justify-content-between">
                <div>
                    <div class="title"><?= htmlspecialchars($notification['title']) ?></div>
                    <div class="user-info">
                        <i class="fas fa-user"></i> 
                        <?= htmlspecialchars($notification['user_name'] ?? $notification['email']) ?>
                        <span class="notification-type type-<?= $notification['notification_type'] ?>">
                            <?= ucfirst($notification['notification_type']) ?>
                        </span>
                    </div>
                </div>
                <small class="text-muted">
                    <?= date('M j, Y H:i', strtotime($notification['created_at'])) ?>
                </small>
            </div>
            <p class="mb-0"><?= htmlspecialchars($notification['message']) ?></p>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<?php include 'footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<script>
    document.getElementById('year').textContent = new Date().getFullYear();
</script>
</body>
</html>