<?php
require_once __DIR__ . '/includes/layout.php';
require_login();

$userId = current_user_id();
$search = trim($_GET['search'] ?? '');

$sql = "
    SELECT id, type, title, message, link, is_read, created_at
    FROM notifications
    WHERE user_id = ?
";
$types = 'i';
$params = [$userId];

if ($search !== '') {
    $sql .= " AND (title LIKE ? OR message LIKE ? OR type LIKE ?)";
    $searchLike = '%' . $search . '%';
    $types .= 'sss';
    array_push($params, $searchLike, $searchLike, $searchLike);
}

$sql .= " ORDER BY created_at DESC, id DESC";

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$notifications = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$totalNotifications = count($notifications);
$unreadNotifications = count(array_filter($notifications, static fn($notification) => empty($notification['is_read'])));
$readNotifications = $totalNotifications - $unreadNotifications;

render_layout_start('Notifikasi - Dashboard Audit MAINPP');
?>
<style>
.notification-summary-grid {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 14px;
    margin-bottom: 18px;
}
.notification-summary-card {
    padding: 16px;
    border: 1px solid #e5edf7;
    border-radius: 14px;
    background: linear-gradient(180deg, #ffffff 0%, #f8fbff 100%);
    box-shadow: 0 10px 24px rgba(15, 23, 42, 0.05);
    display: flex;
    align-items: center;
    gap: 12px;
}
.notification-summary-icon {
    width: 42px;
    height: 42px;
    border-radius: 13px;
    background: #eef5ff;
    color: #0f4c81;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 17px;
}
.notification-summary-card.unread .notification-summary-icon {
    background: #fff7ed;
    color: #d97706;
}
.notification-summary-card.read .notification-summary-icon {
    background: #ecfdf5;
    color: #16a34a;
}
.notification-summary-value {
    display: block;
    color: #0f172a;
    font-size: 24px;
    font-weight: 900;
    line-height: 1;
}
.notification-summary-label {
    display: block;
    margin-top: 5px;
    color: #64748b;
    font-size: 12px;
    font-weight: 900;
    text-transform: uppercase;
}
.notification-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
    margin-top: 10px;
}
.notification-actions-left,
.notification-actions-right {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    align-items: center;
}
.notification-actions-right {
    justify-content: flex-end;
}
.notification-btn-alt {
    border: none;
    border-radius: 12px;
    padding: 12px 16px;
    font-size: 14px;
    font-weight: 800;
    cursor: pointer;
    text-decoration: none;
    background: #eef5ff;
    color: #0f4c81;
}
.notification-table tr.unread-row td {
    background: #f8fbff;
}
.notification-subject {
    font-weight: 800;
    color: #0f172a;
}
.notification-snippet {
    color: #4b5563;
    line-height: 1.5;
}
.checkbox-col {
    width: 44px;
}
.notification-type-icon {
    width: 34px;
    height: 34px;
    border-radius: 11px;
    background: #eef5ff;
    color: #0f4c81;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    margin-right: 10px;
}
.notification-title-wrap {
    display: flex;
    align-items: center;
}
@media (max-width: 800px) {
    .notification-summary-grid {
        grid-template-columns: 1fr;
    }
}
html[data-theme="dark"] .notification-summary-card {
    background: #111827;
    border-color: #263244;
}
html[data-theme="dark"] .notification-summary-value,
html[data-theme="dark"] .notification-subject {
    color: #e5e7eb;
}
html[data-theme="dark"] .notification-summary-label,
html[data-theme="dark"] .notification-snippet {
    color: #94a3b8;
}
</style>

<?php if (isset($_GET['success']) && $_GET['success'] === 'marked'): ?>
    <div class="status-message status-success">Notifikasi yang dipilih berjaya ditandakan sebagai dibaca.</div>
<?php elseif (isset($_GET['success']) && $_GET['success'] === 'deleted'): ?>
    <div class="status-message status-success">Notifikasi yang dipilih berjaya dipadam.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'no_selection'): ?>
    <div class="status-message status-warning">Pilih sekurang-kurangnya satu notifikasi dahulu.</div>
<?php endif; ?>

<div class="notification-summary-grid">
    <div class="notification-summary-card">
        <span class="notification-summary-icon"><i class="fa-solid fa-bell"></i></span>
        <span>
            <span class="notification-summary-value"><?= (int) $totalNotifications ?></span>
            <span class="notification-summary-label">Jumlah Notifikasi</span>
        </span>
    </div>
    <div class="notification-summary-card unread">
        <span class="notification-summary-icon"><i class="fa-solid fa-envelope"></i></span>
        <span>
            <span class="notification-summary-value"><?= (int) $unreadNotifications ?></span>
            <span class="notification-summary-label">Belum Dibaca</span>
        </span>
    </div>
    <div class="notification-summary-card read">
        <span class="notification-summary-icon"><i class="fa-solid fa-circle-check"></i></span>
        <span>
            <span class="notification-summary-value"><?= (int) $readNotifications ?></span>
            <span class="notification-summary-label">Sudah Dibaca</span>
        </span>
    </div>
</div>

<div class="page-card">
    <h3><i class="fa-solid fa-bell"></i> Notifikasi</h3>
    <form method="GET" class="search-form">
        <div class="search-input-wrap">
            <i class="fa-solid fa-magnifying-glass"></i>
            <input type="text" name="search" class="search-input" placeholder="Cari tajuk, mesej atau jenis notifikasi" value="<?= htmlspecialchars($search) ?>">
        </div>
        <button type="submit" class="search-btn">Cari</button>
        <a href="notifications.php" class="reset-btn">Reset</a>
    </form>
    
    <div class="notification-toolbar">
        <div class="notification-actions-left">
            <button type="button" class="notification-btn-alt" onclick="selectAllNotifications()"><i class="fa-solid fa-check-double"></i> Pilih Semua</button>
            <button type="button" class="notification-btn-alt" onclick="unselectAllNotifications()"><i class="fa-solid fa-xmark"></i> Nyahpilih</button>
        </div>
        <div class="notification-actions-right">
            <button type="submit" form="notifications-bulk-form" name="action" value="mark_read" class="notification-btn-alt"><i class="fa-solid fa-envelope-open"></i> Tanda Dibaca</button>
            <button type="submit" form="notifications-bulk-form" name="action" value="delete" class="danger-btn" onclick="return confirm('Padam notifikasi yang dipilih?')"><i class="fa-solid fa-trash"></i> Padam</button>
        </div>
    </div>
</div>

<form id="notifications-bulk-form" action="notifications_action.php" method="POST">
    <div class="table-container">
        <table class="notification-table">
            <thead>
                <tr>
                    <th class="checkbox-col"><input type="checkbox" id="master-checkbox" onclick="toggleMasterSelection(this)"></th>
                    <th>Bil</th>
                    <th>Tajuk</th>
                    <th>Mesej</th>
                    <th>Tarikh</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($notifications)): ?>
                    <?php $bil = 1; foreach ($notifications as $notification): ?>
                    <tr class="<?= empty($notification['is_read']) ? 'unread-row' : '' ?>">
                        <td class="checkbox-col">
                            <input type="checkbox" name="selected_notifications[]" value="<?= (int) $notification['id'] ?>" class="notification-checkbox">
                        </td>
                        <td><?= $bil++ ?></td>
                        <td>
                            <span class="notification-title-wrap">
                                <span class="notification-type-icon"><i class="fa-solid fa-bell"></i></span>
                                <span class="notification-subject"><?= htmlspecialchars($notification['title']) ?></span>
                            </span>
                        </td>
                        <td><span class="notification-snippet"><?= htmlspecialchars($notification['message']) ?></span></td>
                        <td><?= htmlspecialchars(date('d/m/Y h:i A', strtotime((string) $notification['created_at']))) ?></td>
                        <td>
                            <span class="status-badge <?= !empty($notification['is_read']) ? 'approval-approved' : 'approval-pending' ?>">
                                <?= !empty($notification['is_read']) ? 'Dibaca' : 'Belum Dibaca' ?>
                            </span>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="6" class="empty-state">Tiada notifikasi ditemui.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

</form>
<?php
$extraJs = <<<HTML
<script>
function getNotificationCheckboxes() {
    return document.querySelectorAll('.notification-checkbox');
}

function selectAllNotifications() {
    getNotificationCheckboxes().forEach((checkbox) => {
        checkbox.checked = true;
    });
    const master = document.getElementById('master-checkbox');
    if (master) master.checked = true;
}

function unselectAllNotifications() {
    getNotificationCheckboxes().forEach((checkbox) => {
        checkbox.checked = false;
    });
    const master = document.getElementById('master-checkbox');
    if (master) master.checked = false;
}

function toggleMasterSelection(source) {
    getNotificationCheckboxes().forEach((checkbox) => {
        checkbox.checked = source.checked;
    });
}
</script>
HTML;

render_layout_end($extraJs);
?>
