<?php
/**
 * Trang Quản Lý Thông Báo - Admin Panel
 * Yêu cầu: Admin (level 9)
 */

session_start();
require_once __DIR__ . '/hethong/ketnoi.php';


// Kiểm tra đăng nhập và quyền admin
if (!isset($_SESSION['session']) || !isset($_SESSION['user']) || $_SESSION['user']['level'] != '9') {
    header('Location: /auth/login');
    exit;
}

// Xử lý form đăng thông báo
$success_msg = '';
$error_msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = isset($_POST['title']) ? trim($_POST['title']) : '';
    $content = isset($_POST['content']) ? trim($_POST['content']) : '';
    $target = isset($_POST['target']) ? $_POST['target'] : 'all';
    $priority = isset($_POST['priority']) ? $_POST['priority'] : 'normal';
    $type = isset($_POST['type']) ? $_POST['type'] : 'info';
    $expires_at = isset($_POST['expires_at']) ? $_POST['expires_at'] : null;
    $is_pinned = isset($_POST['is_pinned']) ? 1 : 0;

    if (empty($title) || empty($content)) {
        $error_msg = 'Vui lòng điền đầy đủ tiêu đề và nội dung thông báo!';
    } else {
        try {
            $stmt = $conn->prepare("INSERT INTO notifications (title, content, target, priority, type, created_by, expires_at, is_pinned, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([
                $title,
                $content,
                $target,
                $priority,
                $type,
                $_SESSION['user']['id'],
                $expires_at ?: null,
                $is_pinned
            ]);
            $success_msg = 'Thông báo đã được đăng thành công!';
        } catch (PDOException $e) {
            $error_msg = 'Có lỗi xảy ra: ' . $e->getMessage();
        }
    }
}

// Lấy danh sách thông báo gần đây
$notifications = [];
try {
    $stmt = $conn->query("SELECT n.*, u.username as author_name FROM notifications n LEFT JOIN users u ON n.created_by = u.id ORDER BY n.created_at DESC LIMIT 20");
    $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // Bảng chưa tồn tại, bỏ qua
}

// Thống kê
try {
    $total_notif = $conn->query("SELECT COUNT(*) FROM notifications")->fetchColumn();
    $today_notif = $conn->query("SELECT COUNT(*) FROM notifications WHERE DATE(created_at) = CURDATE()")->fetchColumn();
    $pinned_notif = $conn->query("SELECT COUNT(*) FROM notifications WHERE is_pinned = 1")->fetchColumn();
    $active_notif = $conn->query("SELECT COUNT(*) FROM notifications WHERE expires_at IS NULL OR expires_at > NOW()")->fetchColumn();
} catch (PDOException $e) {
    $total_notif = $today_notif = $pinned_notif = $active_notif = 0;
}

?><!DOCTYPE html>
<html lang="vi" data-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quản Lý Thông Báo - Admin Panel</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.quilljs.com/1.3.7/quill.snow.css" rel="stylesheet">
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --success-gradient: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            --warning-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            --info-gradient: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            --danger-gradient: linear-gradient(135deg, #eb3349 0%, #f45c43 100%);
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }

        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #e4e8ec 100%);
            min-height: 100vh;
            color: #2d3748;
        }

        @keyframes fadeInDown {
            from { opacity: 0; transform: translateY(-30px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @keyframes fadeInUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @keyframes slideInLeft {
            from { opacity: 0; transform: translateX(-30px); }
            to { opacity: 1; transform: translateX(0); }
        }

        @keyframes scaleIn {
            from { opacity: 0; transform: scale(0.8); }
            to { opacity: 1; transform: scale(1); }
        }

        @keyframes float {
            0%, 100% { transform: translateY(0) rotate(0deg); }
            50% { transform: translateY(-15px) rotate(2deg); }
        }

        @keyframes pulse-glow {
            0%, 100% { box-shadow: 0 0 0 0 rgba(102, 126, 234, 0.4); }
            50% { box-shadow: 0 0 20px 10px rgba(102, 126, 234, 0.1); }
        }

        @keyframes shimmer {
            0% { background-position: -200% 0; }
            100% { background-position: 200% 0; }
        }

        @keyframes rotate-slow {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }

        @keyframes slideDown {
            from { opacity: 0; max-height: 0; transform: translateY(-10px); }
            to { opacity: 1; max-height: 500px; transform: translateY(0); }
        }

        /* ========== HEADER ========== */
        .page-header {
            background: var(--primary-gradient);
            border-radius: 20px;
            padding: 2.5rem;
            margin-bottom: 2rem;
            position: relative;
            overflow: hidden;
            animation: fadeInDown 0.8s ease-out;
            box-shadow: 0 20px 60px rgba(102, 126, 234, 0.3);
        }

        .page-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -10%;
            width: 400px;
            height: 400px;
            background: rgba(255,255,255,0.1);
            border-radius: 50%;
            animation: float 6s ease-in-out infinite;
        }

        .page-header::after {
            content: '';
            position: absolute;
            bottom: -30%;
            left: -5%;
            width: 300px;
            height: 300px;
            background: rgba(255,255,255,0.05);
            border-radius: 50%;
            animation: float 8s ease-in-out infinite reverse;
        }

        .header-content { position: relative; z-index: 1; }
        .header-title { font-size: 2.2rem; font-weight: 800; color: white; margin-bottom: 0.5rem; text-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .header-subtitle { color: rgba(255,255,255,0.9); font-size: 1.05rem; }
        .header-icon { font-size: 4rem; color: rgba(255,255,255,0.2); position: absolute; right: 2rem; top: 50%; transform: translateY(-50%); animation: float 4s ease-in-out infinite; }

        /* ========== STATS ========== */
        .stats-row { margin-bottom: 2rem; }
        .stat-card {
            background: white;
            border-radius: 16px;
            padding: 1.5rem;
            box-shadow: 0 4px 20px rgba(0,0,0,0.06);
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
            animation: fadeInUp 0.6s ease-out backwards;
            border: 1px solid rgba(0,0,0,0.04);
        }
        .stat-card:nth-child(1) { animation-delay: 0.1s; }
        .stat-card:nth-child(2) { animation-delay: 0.2s; }
        .stat-card:nth-child(3) { animation-delay: 0.3s; }
        .stat-card:nth-child(4) { animation-delay: 0.4s; }
        .stat-card:hover { transform: translateY(-8px); box-shadow: 0 12px 40px rgba(0,0,0,0.12); }
        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
            border-radius: 16px 0 0 16px;
        }
        .stat-card.primary::before { background: var(--primary-gradient); }
        .stat-card.success::before { background: var(--success-gradient); }
        .stat-card.warning::before { background: var(--warning-gradient); }
        .stat-card.info::before { background: var(--info-gradient); }

        .stat-icon {
            width: 50px; height: 50px; border-radius: 12px;
            display: flex; align-items: center; justify-content: center;
            font-size: 1.3rem; margin-bottom: 1rem;
            transition: transform 0.3s ease;
        }
        .stat-card:hover .stat-icon { transform: scale(1.1) rotate(5deg); }
        .stat-icon.primary { background: linear-gradient(135deg, rgba(102,126,234,0.15), rgba(118,75,162,0.15)); color: #667eea; }
        .stat-icon.success { background: linear-gradient(135deg, rgba(17,153,142,0.15), rgba(56,239,125,0.15)); color: #11998e; }
        .stat-icon.warning { background: linear-gradient(135deg, rgba(240,147,251,0.15), rgba(245,87,108,0.15)); color: #f5576c; }
        .stat-icon.info { background: linear-gradient(135deg, rgba(79,172,254,0.15), rgba(0,242,254,0.15)); color: #4facfe; }

        .stat-value { font-size: 1.8rem; font-weight: 800; color: #2d3748; margin-bottom: 0.25rem; }
        .stat-label { color: #718096; font-size: 0.9rem; font-weight: 500; }

        /* ========== CONTENT CARDS ========== */
        .content-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.06);
            overflow: hidden;
            animation: fadeInUp 0.7s ease-out;
            border: 1px solid rgba(0,0,0,0.04);
        }
        .card-header-custom {
            padding: 1.5rem 2rem;
            border-bottom: 1px solid rgba(0,0,0,0.05);
            display: flex; align-items: center; justify-content: space-between;
            background: linear-gradient(to right, rgba(102,126,234,0.03), transparent);
        }
        .card-title-custom { font-size: 1.2rem; font-weight: 700; color: #2d3748; display: flex; align-items: center; gap: 0.75rem; }
        .card-title-icon { width: 40px; height: 40px; border-radius: 10px; background: var(--primary-gradient); display: flex; align-items: center; justify-content: center; color: white; font-size: 1rem; }
        .card-body-custom { padding: 2rem; }

        /* ========== FORM ========== */
        .form-group-custom { margin-bottom: 1.5rem; }
        .form-label-custom { font-weight: 600; color: #4a5568; margin-bottom: 0.5rem; display: flex; align-items: center; gap: 0.5rem; }
        .form-label-custom i { color: #667eea; font-size: 0.9rem; }
        .form-control-custom {
            border: 2px solid #e2e8f0; border-radius: 12px; padding: 0.875rem 1rem;
            font-size: 0.95rem; transition: all 0.3s ease; background: #fafbfc;
        }
        .form-control-custom:focus { border-color: #667eea; box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1); background: white; transform: translateY(-1px); }
        .form-control-custom:hover { border-color: #cbd5e0; }

        /* Quill Editor */
        .ql-toolbar { border-radius: 12px 12px 0 0 !important; border: 2px solid #e2e8f0 !important; border-bottom: none !important; background: #fafbfc; }
        .ql-container { border-radius: 0 0 12px 12px !important; border: 2px solid #e2e8f0 !important; border-top: none !important; min-height: 200px; font-size: 0.95rem; }
        .ql-editor { min-height: 200px; }
        .ql-editor:focus { background: white; }

        /* Target Selector */
        .target-option {
            cursor: pointer; padding: 1rem; border-radius: 12px;
            border: 2px solid #e2e8f0; transition: all 0.3s ease;
            text-align: center; background: white;
        }
        .target-option:hover { border-color: #667eea; transform: translateY(-3px); box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15); }
        .target-option.active { border-color: #667eea; background: linear-gradient(135deg, rgba(102,126,234,0.08), rgba(118,75,162,0.08)); box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15); }
        .target-option.active .target-icon { background: var(--primary-gradient); color: white; }
        .target-icon { width: 50px; height: 50px; border-radius: 50%; background: linear-gradient(135deg, rgba(102,126,234,0.1), rgba(118,75,162,0.1)); color: #667eea; display: flex; align-items: center; justify-content: center; font-size: 1.2rem; margin: 0 auto 0.75rem; transition: all 0.3s ease; }
        .target-title { font-weight: 600; color: #2d3748; font-size: 0.95rem; }
        .target-desc { font-size: 0.8rem; color: #718096; margin-top: 0.25rem; }

        /* Priority */
        .priority-badge { cursor: pointer; padding: 0.5rem 1rem; border-radius: 20px; font-weight: 600; font-size: 0.85rem; transition: all 0.3s ease; border: 2px solid transparent; display: inline-flex; align-items: center; gap: 0.5rem; }
        .priority-badge:hover { transform: scale(1.05); }
        .priority-badge.active { box-shadow: 0 4px 15px rgba(0,0,0,0.15); transform: scale(1.08); }
        .priority-low { background: linear-gradient(135deg, #e6fffa 0%, #b2f5ea 100%); color: #234e52; border-color: #81e6d9; }
        .priority-normal { background: linear-gradient(135deg, #ebf8ff 0%, #bee3f8 100%); color: #2a4365; border-color: #90cdf4; }
        .priority-high { background: linear-gradient(135deg, #fffaf0 0%, #feebc8 100%); color: #744210; border-color: #f6ad55; }
        .priority-urgent { background: linear-gradient(135deg, #fff5f5 0%, #fed7d7 100%); color: #742a2a; border-color: #fc8181; }

        /* Buttons */
        .btn-custom-primary {
            background: var(--primary-gradient); color: white; border: none;
            padding: 0.875rem 2rem; border-radius: 12px; font-weight: 600;
            font-size: 0.95rem; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative; overflow: hidden; box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }
        .btn-custom-primary:hover { transform: translateY(-2px); box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4); color: white; }
        .btn-custom-primary:active { transform: translateY(0); }
        .btn-custom-secondary { background: white; color: #4a5568; border: 2px solid #e2e8f0; padding: 0.875rem 2rem; border-radius: 12px; font-weight: 600; font-size: 0.95rem; transition: all 0.3s ease; }
        .btn-custom-secondary:hover { border-color: #667eea; color: #667eea; background: rgba(102,126,234,0.05); }

        /* Notification List */
        .notification-list { max-height: 600px; overflow-y: auto; padding-right: 0.5rem; }
        .notification-list::-webkit-scrollbar { width: 6px; }
        .notification-list::-webkit-scrollbar-track { background: transparent; }
        .notification-list::-webkit-scrollbar-thumb { background: #cbd5e0; border-radius: 3px; }
        .notification-item {
            padding: 1.25rem; border-radius: 14px; margin-bottom: 0.75rem;
            transition: all 0.3s ease; cursor: pointer; position: relative;
            overflow: hidden; border: 1px solid rgba(0,0,0,0.04);
            animation: slideInLeft 0.4s ease-out backwards;
        }
        .notification-item:nth-child(1) { animation-delay: 0.1s; }
        .notification-item:nth-child(2) { animation-delay: 0.15s; }
        .notification-item:nth-child(3) { animation-delay: 0.2s; }
        .notification-item:nth-child(4) { animation-delay: 0.25s; }
        .notification-item:hover { transform: translateX(8px); box-shadow: 0 4px 15px rgba(0,0,0,0.08); }
        .notification-item.pinned { background: linear-gradient(to right, rgba(102,126,234,0.05), white); border-left: 3px solid #667eea; }
        .notification-item.read { background: white; opacity: 0.8; }
        .notification-dot { width: 8px; height: 8px; border-radius: 50%; position: absolute; top: 1.25rem; right: 1.25rem; }
        .notification-dot.urgent { background: var(--danger-gradient); box-shadow: 0 0 8px rgba(235,51,73,0.4); }
        .notification-dot.high { background: var(--warning-gradient); }
        .notification-dot.normal { background: var(--info-gradient); }
        .notification-dot.low { background: var(--success-gradient); }
        .notification-icon { width: 45px; height: 45px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.1rem; flex-shrink: 0; }
        .notification-content { flex: 1; min-width: 0; }
        .notification-title { font-weight: 600; color: #2d3748; margin-bottom: 0.25rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .notification-meta { color: #a0aec0; font-size: 0.8rem; }
        .notification-actions { display: flex; gap: 0.5rem; opacity: 0; transition: opacity 0.3s ease; }
        .notification-item:hover .notification-actions { opacity: 1; }
        .action-btn { width: 32px; height: 32px; border-radius: 8px; border: none; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.2s ease; font-size: 0.8rem; }
        .action-btn:hover { transform: scale(1.1); }
        .action-btn.edit { background: rgba(102,126,234,0.1); color: #667eea; }
        .action-btn.delete { background: rgba(235,51,73,0.1); color: #eb3349; }
        .action-btn.pin { background: rgba(245,183,89,0.1); color: #f5b759; }

        .empty-state { text-align: center; padding: 3rem 2rem; animation: fadeInUp 0.6s ease-out; }
        .empty-state i { font-size: 3rem; color: #cbd5e0; margin-bottom: 1rem; }
        .empty-state h5 { font-size: 1.2rem; font-weight: 600; color: #4a5568; margin-bottom: 0.5rem; }
        .empty-state p { color: #a0aec0; }

        /* Type Selector */
        .type-option { cursor: pointer; padding: 0.75rem 1rem; border-radius: 10px; border: 2px solid #e2e8f0; transition: all 0.3s ease; display: flex; align-items: center; gap: 0.5rem; font-weight: 500; font-size: 0.9rem; }
        .type-option:hover { border-color: #667eea; transform: translateY(-2px); }
        .type-option.active { border-color: #667eea; background: rgba(102,126,234,0.08); }
        .type-option i { font-size: 1rem; }

        /* Alert */
        .alert-custom { border-radius: 12px; border: none; padding: 1rem 1.25rem; animation: scaleIn 0.3s ease-out; }
        .alert-success-custom { background: linear-gradient(135deg, #c6f6d5 0%, #9ae6b4 100%); color: #22543d; }
        .alert-danger-custom { background: linear-gradient(135deg, #fed7d7 0%, #feb2b2 100%); color: #742a2a; }

        /* Toggle Switch */
        .toggle-switch { position: relative; width: 50px; height: 26px; }
        .toggle-switch input { opacity: 0; width: 0; height: 0; }
        .toggle-slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background: #e2e8f0; transition: 0.3s; border-radius: 26px; }
        .toggle-slider:before { position: absolute; content: ""; height: 20px; width: 20px; left: 3px; bottom: 3px; background: white; transition: 0.3s; border-radius: 50%; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .toggle-switch input:checked + .toggle-slider { background: var(--primary-gradient); }
        .toggle-switch input:checked + .toggle-slider:before { transform: translateX(24px); }

        /* Preview */
        .preview-box { background: linear-gradient(135deg, #fafbfc 0%, #f7fafc 100%); border-radius: 12px; padding: 1.25rem; margin-top: 1rem; border: 1px dashed rgba(102,126,234,0.3); animation: slideDown 0.4s ease-out; }

        /* Loading */
        .spinner-custom { width: 20px; height: 20px; border: 2px solid rgba(255,255,255,0.3); border-top-color: white; border-radius: 50%; animation: rotate-slow 0.8s linear infinite; display: inline-block; }

        /* ========== RESPONSIVE ========== */
        @media (max-width: 991.98px) {
            .page-header { padding: 1.5rem; border-radius: 16px; }
            .header-title { font-size: 1.8rem; }
            .header-icon { font-size: 2.5rem; right: 1rem; }
            .stat-card { margin-bottom: 1rem; }
            .card-body-custom { padding: 1.25rem; }
            .target-option { margin-bottom: 0.75rem; }
            .notification-actions { opacity: 1; }
        }

        @media (max-width: 767.98px) {
            .header-title { font-size: 1.5rem; }
            .header-icon { display: none; }
            .card-header-custom { padding: 1rem 1.25rem; flex-direction: column; gap: 0.75rem; align-items: flex-start; }
            .form-control-custom { padding: 0.75rem; }
            .btn-custom-primary, .btn-custom-secondary { width: 100%; margin-bottom: 0.5rem; }
            .priority-badge { margin-bottom: 0.5rem; }
        }

        /* Dark Mode */
        [data-theme="dark"] body { background: linear-gradient(135deg, #1a202c 0%, #2d3748 100%); color: #e2e8f0; }
        [data-theme="dark"] .stat-card, [data-theme="dark"] .content-card { background: #2d3748; border-color: rgba(255,255,255,0.05); }
        [data-theme="dark"] .stat-value, [data-theme="dark"] .card-title-custom, [data-theme="dark"] .target-title, [data-theme="dark"] .notification-title { color: #e2e8f0; }
        [data-theme="dark"] .stat-label, [data-theme="dark"] .target-desc, [data-theme="dark"] .notification-meta { color: #a0aec0; }
        [data-theme="dark"] .form-control-custom { background: #4a5568; border-color: #4a5568; color: #e2e8f0; }
        [data-theme="dark"] .form-control-custom:focus { background: #4a5568; }
        [data-theme="dark"] .ql-toolbar { background: #4a5568 !important; border-color: #4a5568 !important; }
        [data-theme="dark"] .ql-container { background: #4a5568 !important; border-color: #4a5568 !important; color: #e2e8f0; }
        [data-theme="dark"] .target-option { background: #2d3748; border-color: #4a5568; }
        [data-theme="dark"] .target-option.active { background: linear-gradient(135deg, rgba(102,126,234,0.15), rgba(118,75,162,0.15)); }
        [data-theme="dark"] .notification-item { background: #2d3748; border-color: rgba(255,255,255,0.05); }
        [data-theme="dark"] .notification-item.pinned { background: linear-gradient(to right, rgba(102,126,234,0.1), #2d3748); }
        [data-theme="dark"] .notification-item.read { background: #2d3748; }
        [data-theme="dark"] .empty-state h5 { color: #e2e8f0; }
        [data-theme="dark"] .btn-custom-secondary { background: #2d3748; border-color: #4a5568; color: #e2e8f0; }
        [data-theme="dark"] .btn-custom-secondary:hover { border-color: #667eea; }
        [data-theme="dark"] .preview-box { background: linear-gradient(135deg, #2d3748 0%, #4a5568 100%); }
        [data-theme="dark"] .type-option { background: #2d3748; border-color: #4a5568; color: #e2e8f0; }
    </style>
</head>
<body>

<div class="container-fluid py-4 px-3 px-lg-4">

    <!-- Header -->
    <div class="page-header">
        <div class="header-content">
            <h1 class="header-title"><i class="fas fa-bullhorn me-3"></i>Quản Lý Thông Báo</h1>
            <p class="header-subtitle">Tạo và quản lý thông báo gửi đến người dùng hệ thống</p>
        </div>
        <i class="fas fa-paper-plane header-icon"></i>
    </div>

    <!-- Stats -->
    <div class="row stats-row g-3">
        <div class="col-6 col-lg-3">
            <div class="stat-card primary">
                <div class="stat-icon primary"><i class="fas fa-bell"></i></div>
                <div class="stat-value"><?= number_format($total_notif) ?></div>
                <div class="stat-label">Tổng thông báo</div>
            </div>
        </div>
        <div class="col-6 col-lg-3">
            <div class="stat-card success">
                <div class="stat-icon success"><i class="fas fa-calendar-day"></i></div>
                <div class="stat-value"><?= number_format($today_notif) ?></div>
                <div class="stat-label">Hôm nay</div>
            </div>
        </div>
        <div class="col-6 col-lg-3">
            <div class="stat-card warning">
                <div class="stat-icon warning"><i class="fas fa-thumbtack"></i></div>
                <div class="stat-value"><?= number_format($pinned_notif) ?></div>
                <div class="stat-label">Đã ghim</div>
            </div>
        </div>
        <div class="col-6 col-lg-3">
            <div class="stat-card info">
                <div class="stat-icon info"><i class="fas fa-check-circle"></i></div>
                <div class="stat-value"><?= number_format($active_notif) ?></div>
                <div class="stat-label">Đang hoạt động</div>
            </div>
        </div>
    </div>

    <div class="row g-4">
        <!-- Form đăng thông báo -->
        <div class="col-lg-7">
            <div class="content-card">
                <div class="card-header-custom">
                    <div class="card-title-custom">
                        <div class="card-title-icon"><i class="fas fa-plus"></i></div>
                        Đăng Thông Báo Mới
                    </div>
                    <span class="badge bg-primary bg-opacity-10 text-primary px-3 py-2 rounded-pill">
                        <i class="fas fa-shield-alt me-1"></i>Admin
                    </span>
                </div>
                <div class="card-body-custom">

                    <?php if ($success_msg): ?>
                    <div class="alert alert-success-custom alert-custom mb-4">
                        <i class="fas fa-check-circle me-2"></i><?= htmlspecialchars($success_msg) ?>
                    </div>
                    <?php endif; ?>

                    <?php if ($error_msg): ?>
                    <div class="alert alert-danger-custom alert-custom mb-4">
                        <i class="fas fa-exclamation-circle me-2"></i><?= htmlspecialchars($error_msg) ?>
                    </div>
                    <?php endif; ?>

                    <form method="POST" action="" id="notificationForm">

                        <!-- Tiêu đề -->
                        <div class="form-group-custom">
                            <label class="form-label-custom"><i class="fas fa-heading"></i> Tiêu đề thông báo</label>
                            <input type="text" name="title" class="form-control form-control-custom" placeholder="Nhập tiêu đề thông báo..." required maxlength="200">
                        </div>

                        <!-- Loại thông báo -->
                        <div class="form-group-custom">
                            <label class="form-label-custom"><i class="fas fa-tag"></i> Loại thông báo</label>
                            <div class="row g-2">
                                <div class="col-6 col-md-3">
                                    <div class="type-option active" data-type="info" onclick="selectType(this)">
                                        <i class="fas fa-info-circle text-info"></i> Thông tin
                                    </div>
                                </div>
                                <div class="col-6 col-md-3">
                                    <div class="type-option" data-type="success" onclick="selectType(this)">
                                        <i class="fas fa-check-circle text-success"></i> Thành công
                                    </div>
                                </div>
                                <div class="col-6 col-md-3">
                                    <div class="type-option" data-type="warning" onclick="selectType(this)">
                                        <i class="fas fa-exclamation-triangle text-warning"></i> Cảnh báo
                                    </div>
                                </div>
                                <div class="col-6 col-md-3">
                                    <div class="type-option" data-type="danger" onclick="selectType(this)">
                                        <i class="fas fa-times-circle text-danger"></i> Khẩn cấp
                                    </div>
                                </div>
                            </div>
                            <input type="hidden" name="type" id="typeInput" value="info">
                        </div>

                        <!-- Nội dung -->
                        <div class="form-group-custom">
                            <label class="form-label-custom"><i class="fas fa-align-left"></i> Nội dung</label>
                            <div id="editor"></div>
                            <input type="hidden" name="content" id="contentInput">
                        </div>

                        <!-- Đối tượng -->
                        <div class="form-group-custom">
                            <label class="form-label-custom"><i class="fas fa-users"></i> Đối tượng nhận</label>
                            <div class="row g-3">
                                <div class="col-6 col-md-3">
                                    <div class="target-option active" data-target="all" onclick="selectTarget(this)">
                                        <div class="target-icon"><i class="fas fa-globe"></i></div>
                                        <div class="target-title">Tất cả</div>
                                        <div class="target-desc">Mọi người dùng</div>
                                    </div>
                                </div>
                                <div class="col-6 col-md-3">
                                    <div class="target-option" data-target="members" onclick="selectTarget(this)">
                                        <div class="target-icon"><i class="fas fa-user-check"></i></div>
                                        <div class="target-title">Thành viên</div>
                                        <div class="target-desc">Đã đăng nhập</div>
                                    </div>
                                </div>
                                <div class="col-6 col-md-3">
                                    <div class="target-option" data-target="vip" onclick="selectTarget(this)">
                                        <div class="target-icon"><i class="fas fa-crown"></i></div>
                                        <div class="target-title">VIP</div>
                                        <div class="target-desc">Thành viên VIP</div>
                                    </div>
                                </div>
                                <div class="col-6 col-md-3">
                                    <div class="target-option" data-target="admins" onclick="selectTarget(this)">
                                        <div class="target-icon"><i class="fas fa-user-shield"></i></div>
                                        <div class="target-title">Admin</div>
                                        <div class="target-desc">Quản trị viên</div>
                                    </div>
                                </div>
                            </div>
                            <input type="hidden" name="target" id="targetInput" value="all">
                        </div>

                        <!-- Mức độ ưu tiên -->
                        <div class="form-group-custom">
                            <label class="form-label-custom"><i class="fas fa-flag"></i> Mức độ ưu tiên</label>
                            <div class="d-flex flex-wrap gap-2">
                                <span class="priority-badge priority-low" data-priority="low" onclick="selectPriority(this)"><i class="fas fa-arrow-down"></i> Thấp</span>
                                <span class="priority-badge priority-normal active" data-priority="normal" onclick="selectPriority(this)"><i class="fas fa-minus"></i> Bình thường</span>
                                <span class="priority-badge priority-high" data-priority="high" onclick="selectPriority(this)"><i class="fas fa-arrow-up"></i> Cao</span>
                                <span class="priority-badge priority-urgent" data-priority="urgent" onclick="selectPriority(this)"><i class="fas fa-exclamation"></i> Khẩn cấp</span>
                            </div>
                            <input type="hidden" name="priority" id="priorityInput" value="normal">
                        </div>

                        <div class="row g-3">
                            <!-- Hết hạn -->
                            <div class="col-md-6">
                                <div class="form-group-custom mb-0">
                                    <label class="form-label-custom"><i class="fas fa-clock"></i> Thời hạn (tùy chọn)</label>
                                    <input type="datetime-local" name="expires_at" class="form-control form-control-custom">
                                </div>
                            </div>
                            <!-- Ghim -->
                            <div class="col-md-6">
                                <div class="form-group-custom mb-0">
                                    <label class="form-label-custom"><i class="fas fa-thumbtack"></i> Ghim thông báo</label>
                                    <div class="d-flex align-items-center gap-3 mt-2">
                                        <label class="toggle-switch">
                                            <input type="checkbox" name="is_pinned" id="isPinned">
                                            <span class="toggle-slider"></span>
                                        </label>
                                        <span class="text-muted" style="font-size: 0.9rem;">Ghim lên đầu danh sách</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Preview -->
                        <div class="preview-box" id="previewBox" style="display: none;">
                            <label class="form-label-custom"><i class="fas fa-eye"></i> Xem trước</label>
                            <div class="notification-item" id="previewContent"></div>
                        </div>

                        <!-- Buttons -->
                        <div class="d-flex flex-wrap gap-3 mt-4 pt-3 border-top">
                            <button type="submit" class="btn btn-custom-primary" id="submitBtn">
                                <i class="fas fa-paper-plane me-2"></i>Đăng thông báo
                            </button>
                            <button type="button" class="btn btn-custom-secondary" onclick="showPreview()">
                                <i class="fas fa-eye me-2"></i>Xem trước
                            </button>
                            <button type="reset" class="btn btn-custom-secondary" onclick="resetForm()">
                                <i class="fas fa-redo me-2"></i>Làm mới
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Danh sách thông báo -->
        <div class="col-lg-5">
            <div class="content-card">
                <div class="card-header-custom">
                    <div class="card-title-custom">
                        <div class="card-title-icon" style="background: var(--info-gradient);"><i class="fas fa-history"></i></div>
                        Thông Báo Gần Đây
                    </div>
                    <span class="badge bg-info bg-opacity-10 text-info px-3 py-2 rounded-pill"><?= count($notifications) ?> mục</span>
                </div>
                <div class="card-body-custom">
                    <div class="notification-list">
                        <?php if (empty($notifications)): ?>
                        <div class="empty-state">
                            <i class="fas fa-inbox"></i>
                            <h5>Chưa có thông báo nào</h5>
                            <p>Thông báo đã đăng sẽ hiển thị tại đây</p>
                        </div>
                        <?php else: ?>
                        <?php foreach ($notifications as $notif): ?>
                        <div class="notification-item <?= $notif['is_pinned'] ? 'pinned' : '' ?> <?= $notif['is_read'] ? 'read' : '' ?>" data-id="<?= $notif['id'] ?>">
                            <div class="d-flex align-items-center gap-3">
                                <div class="notification-icon" style="background: linear-gradient(135deg, rgba(102,126,234,0.1), rgba(118,75,162,0.1)); color: #667eea;">
                                    <i class="fas fa-<?= $notif['type'] === 'success' ? 'check' : ($notif['type'] === 'warning' ? 'exclamation' : ($notif['type'] === 'danger' ? 'times' : 'info')) ?>"></i>
                                </div>
                                <div class="notification-content">
                                    <div class="notification-title"><?= htmlspecialchars($notif['title']) ?></div>
                                    <div class="notification-meta">
                                        <i class="fas fa-user me-1"></i><?= htmlspecialchars($notif['author_name'] ?? 'Admin') ?>
                                        <span class="mx-1">|</span>
                                        <i class="fas fa-clock me-1"></i><?= date('d/m/Y H:i', strtotime($notif['created_at'])) ?>
                                        <?php if ($notif['is_pinned']): ?>
                                        <span class="badge bg-warning bg-opacity-10 text-warning ms-1" style="font-size: 0.7rem;"><i class="fas fa-thumbtack me-1"></i>Ghim</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="notification-dot <?= $notif['priority'] ?>"></div>
                            </div>
                            <div class="notification-actions mt-2 justify-content-end">
                                <button class="action-btn pin" title="Ghim/Bỏ ghim" onclick="togglePin(<?= $notif['id'] ?>)"><i class="fas fa-thumbtack"></i></button>
                                <button class="action-btn edit" title="Sửa" onclick="editNotif(<?= $notif['id'] ?>)"><i class="fas fa-edit"></i></button>
                                <button class="action-btn delete" title="Xóa" onclick="deleteNotif(<?= $notif['id'] ?>)"><i class="fas fa-trash"></i></button>
                            </div>
                        </div>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.quilljs.com/1.3.7/quill.min.js"></script>
<script>
// Khởi tạo Quill Editor
const quill = new Quill('#editor', {
    theme: 'snow',
    placeholder: 'Nhập nội dung thông báo chi tiết...',
    modules: {
        toolbar: [
            [{ 'header': [1, 2, 3, false] }],
            ['bold', 'italic', 'underline', 'strike'],
            [{ 'color': [] }, { 'background': [] }],
            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
            [{ 'align': [] }],
            ['link', 'image'],
            ['clean']
        ]
    }
});

// Cập nhật content input trước khi submit
document.getElementById('notificationForm').addEventListener('submit', function() {
    document.getElementById('contentInput').value = quill.root.innerHTML;
});

// Chọn loại thông báo
function selectType(element) {
    document.querySelectorAll('.type-option').forEach(el => el.classList.remove('active'));
    element.classList.add('active');
    document.getElementById('typeInput').value = element.dataset.type;
}

// Chọn đối tượng
function selectTarget(element) {
    document.querySelectorAll('.target-option').forEach(el => el.classList.remove('active'));
    element.classList.add('active');
    document.getElementById('targetInput').value = element.dataset.target;
}

// Chọn mức độ ưu tiên
function selectPriority(element) {
    document.querySelectorAll('.priority-badge').forEach(el => el.classList.remove('active'));
    element.classList.add('active');
    document.getElementById('priorityInput').value = element.dataset.priority;
}

// Xem trước
function showPreview() {
    const title = document.querySelector('input[name="title"]').value || 'Tiêu đề thông báo';
    const content = quill.getText().substring(0, 100) + '...';
    const type = document.getElementById('typeInput').value;
    const priority = document.getElementById('priorityInput').value;
    const isPinned = document.getElementById('isPinned').checked;

    const typeIcons = { info: 'info', success: 'check', warning: 'exclamation', danger: 'times' };
    const typeColors = { info: '#4facfe', success: '#11998e', warning: '#f5576c', danger: '#eb3349' };

    const previewHTML = `
        <div class="d-flex align-items-center gap-3">
            <div class="notification-icon" style="background: linear-gradient(135deg, ${typeColors[type]}22, ${typeColors[type]}11); color: ${typeColors[type]};">
                <i class="fas fa-${typeIcons[type]}"></i>
            </div>
            <div class="notification-content">
                <div class="notification-title">${title}</div>
                <div class="notification-meta">${content}</div>
            </div>
            <div class="notification-dot ${priority}"></div>
        </div>
        ${isPinned ? '<span class="badge bg-warning text-dark mt-2" style="font-size: 0.75rem;"><i class="fas fa-thumbtack me-1"></i>Đã ghim</span>' : ''}
    `;

    document.getElementById('previewContent').innerHTML = previewHTML;
    document.getElementById('previewBox').style.display = 'block';
    document.getElementById('previewBox').scrollIntoView({ behavior: 'smooth' });
}

// Reset form
function resetForm() {
    quill.setContents([]);
    document.querySelectorAll('.type-option, .target-option').forEach(el => el.classList.remove('active'));
    document.querySelectorAll('.type-option')[0].classList.add('active');
    document.querySelectorAll('.target-option')[0].classList.add('active');
    document.querySelectorAll('.priority-badge').forEach(el => el.classList.remove('active'));
    document.querySelector('.priority-normal').classList.add('active');
    document.getElementById('previewBox').style.display = 'none';
}

// Toggle pin
function togglePin(id) {
    if (confirm('Bạn có chắc muốn thay đổi trạng thái ghim?')) {
        fetch(`/api/notifications/toggle-pin/${id}`, { method: 'POST' })
            .then(() => location.reload())
            .catch(err => alert('Có lỗi xảy ra!'));
    }
}

// Edit
function editNotif(id) {
    alert('Chức năng sửa thông báo - Bạn có thể tích hợp API để lấy dữ liệu và điền vào form');
}

// Delete
function deleteNotif(id) {
    if (confirm('Bạn có chắc muốn xóa thông báo này?')) {
        fetch(`/api/notifications/delete/${id}`, { method: 'DELETE' })
            .then(() => {
                const item = document.querySelector(`[data-id="${id}"]`);
                item.style.animation = 'fadeOut 0.3s ease-out forwards';
                setTimeout(() => item.remove(), 300);
            })
            .catch(err => alert('Có lỗi xảy ra!'));
    }
}

// Animation cho notification items
const style = document.createElement('style');
style.textContent = `
    @keyframes fadeOut {
        from { opacity: 1; transform: translateX(0); }
        to { opacity: 0; transform: translateX(30px); }
    }
`;
document.head.appendChild(style);

// Ripple effect
function createRipple(event) {
    const button = event.currentTarget;
    const circle = document.createElement('span');
    const diameter = Math.max(button.clientWidth, button.clientHeight);
    const radius = diameter / 2;

    circle.style.width = circle.style.height = `${diameter}px`;
    circle.style.left = `${event.clientX - button.getBoundingClientRect().left - radius}px`;
    circle.style.top = `${event.clientY - button.getBoundingClientRect().top - radius}px`;
    circle.style.position = 'absolute';
    circle.style.borderRadius = '50%';
    circle.style.transform = 'scale(0)';
    circle.style.animation = 'ripple 0.6s linear';
    circle.style.background = 'rgba(255,255,255,0.3)';
    circle.style.pointerEvents = 'none';

    button.style.position = 'relative';
    button.style.overflow = 'hidden';
    button.appendChild(circle);

    setTimeout(() => circle.remove(), 600);
}

document.querySelectorAll('.btn-custom-primary, .btn-custom-secondary, .action-btn').forEach(btn => {
    btn.addEventListener('click', createRipple);
});

// Stagger animation for list items
document.querySelectorAll('.notification-item').forEach((item, index) => {
    item.style.animationDelay = `${index * 0.05}s`;
});
</script>

</body>
</html>