<?php
require_once '../config/db.php';
require_once '../config/auth.php';
require_once '../config/functions.php';
requireAdmin();

$page_title = 'Notifications';
$msg = '';

// Mark all read
if (isset($_POST['mark_all_read'])) {
    $conn->query("UPDATE notifications SET status='read'");
    logActivity($conn, 'mark_all_read', 'notification', null, 'Marked all notifications as read');
    $msg = '<div class="alert alert-success">All notifications marked as read.</div>';
}

// Bulk delete
if (isset($_POST['bulk_delete']) && !empty($_POST['notif_ids'])) {
    $ids = array_map('intval', $_POST['notif_ids']);
    $ids_str = implode(',', $ids);
    $conn->query("DELETE FROM notifications WHERE id IN ($ids_str)");
    $count = count($ids);
    logActivity($conn, 'delete_notifications', 'notification', null, 'Bulk deleted ' . $count . ' notification(s)');
    $msg = '<div class="alert alert-success">' . $count . ' notification(s) deleted.</div>';
}

// Send manual notification
if (isset($_POST['send_notif'])) {
    $uid = (int)$_POST['target_user'];
    $message = sanitize($conn, $_POST['message']);
    $type = sanitize($conn, $_POST['notif_type']);
    if ($uid === 0) {
        $all_users = $conn->query("SELECT id FROM users WHERE role='user'");
        while ($u = $all_users->fetch_assoc()) {
            createNotification($conn, $u['id'], $message, $type);
        }
        logActivity($conn, 'send_notification', 'notification', null, 'Sent notification to all users: ' . $message);
        $msg = '<div class="alert alert-success">Notification sent to all users.</div>';
    } else {
        createNotification($conn, $uid, $message, $type);
        $target = $conn->query("SELECT name FROM users WHERE id=$uid")->fetch_assoc();
        logActivity($conn, 'send_notification', 'notification', $uid, 'Sent notification to ' . $target['name'] . ': ' . $message);
        $msg = '<div class="alert alert-success">Notification sent.</div>';
    }
}

$notifications = $conn->query("SELECT n.*, u.name as user_name FROM notifications n JOIN users u ON n.user_id=u.id ORDER BY n.created_at DESC LIMIT 100");
$users = $conn->query("SELECT id, name FROM users WHERE role='user' ORDER BY name");
$sms_logs = $conn->query("SELECT s.*, u.name as user_name FROM sms_logs s LEFT JOIN users u ON s.user_id=u.id ORDER BY s.created_at DESC LIMIT 50");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $page_title ?> - RELINK Admin</title>
<link rel="stylesheet" href="/lostfound_relink/assets/css/style.css">
</head>
<body>
<div class="layout">
    <?php include '../includes/admin_sidebar.php'; ?>
    <div class="main-content">
        <?php include '../includes/topbar.php'; ?>
        <div class="page-content">
            <?= $msg ?? '' ?>
            <div class="grid-2 mb-24">
                <div class="card">
                    <div class="card-header">
                        <h3>📢 Send Notification</h3>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="form-group">
                                <label>Target User</label>
                                <select name="target_user" class="form-control">
                                    <option value="0">All Users</option>
                                    <?php while($u=$users->fetch_assoc()): ?>
                                    <option value="<?= $u['id'] ?>"><?= htmlspecialchars($u['name']) ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>Type</label>
                                <select name="notif_type" class="form-control">
                                    <option value="general">General</option>
                                    <option value="match">Match</option>
                                    <option value="approved">Approved</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>Message</label>
                                <textarea name="message" class="form-control" rows="3" required placeholder="Enter notification message..."></textarea>
                            </div>
                            <button type="submit" name="send_notif" class="btn btn-primary btn-block">Send Notification</button>
                        </form>
                    </div>
                </div>
                <div class="card">
                    <div class="card-header">
                        <h3>📱 SMS Logs</h3>
                    </div>
                    <div class="table-wrapper" style="max-height:320px;overflow-y:auto">
                        <table>
                            <thead><tr><th>User</th><th>Phone</th><th>Status</th><th>Date</th></tr></thead>
                            <tbody>
                            <?php while($s=$sms_logs->fetch_assoc()): ?>
                            <tr>
                                <td><?= htmlspecialchars($s['user_name'] ?? 'N/A') ?></td>
                                <td><?= htmlspecialchars($s['phone']) ?></td>
                                <td><span class="badge badge-<?= $s['status'] ?>"><?= $s['status'] ?></span></td>
                                <td><?= date('M d H:i', strtotime($s['created_at'])) ?></td>
                            </tr>
                            <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="card">
                <div class="card-header">
                    <h3>🔔 All Notifications</h3>
                    <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
                        <button type="button" id="adminSelectAll" class="btn btn-sm btn-light" onclick="toggleSelectAll('adminNotifForm')">☑ Select All</button>
                        <form method="POST" id="adminBulkDeleteForm" onsubmit="return confirmBulkDelete()">
                            <button name="bulk_delete" class="btn btn-sm btn-danger" id="adminDeleteBtn" disabled>🗑 Delete Selected (<span id="adminSelCount">0</span>)</button>
                        </form>
                        <form method="POST"><button name="mark_all_read" class="btn btn-sm btn-secondary">✓ Mark All Read</button></form>
                    </div>
                </div>
                <form method="POST" id="adminNotifForm">
                <?php while($n=$notifications->fetch_assoc()): ?>
                <div class="notif-item <?= $n['status'] ?>" style="cursor:default">
                    <input type="checkbox" name="notif_ids[]" value="<?= $n['id'] ?>" class="notif-checkbox" form="adminBulkDeleteForm"
                           style="width:16px;height:16px;flex-shrink:0;cursor:pointer;accent-color:var(--danger)">
                    <div class="notif-icon"><?= $n['notification_type']==='match'?'🤝':($n['notification_type']==='approved'?'✅':'🔔') ?></div>
                    <div class="notif-content">
                        <div class="msg"><strong><?= htmlspecialchars($n['user_name']) ?>:</strong> <?= htmlspecialchars($n['message']) ?></div>
                        <div class="time"><?= date('M d, Y H:i', strtotime($n['created_at'])) ?> · <span class="badge badge-<?= $n['status'] ?>"><?= $n['status'] ?></span></div>
                    </div>
                </div>
                <?php endwhile; ?>
                </form>
            </div>
        </div>
    </div>
</div>
<script src="/lostfound_relink/assets/js/main.js"></script>
<script>
function toggleSelectAll(formId) {
    const form = document.getElementById(formId) || document;
    const boxes = document.querySelectorAll('.notif-checkbox');
    const allChecked = [...boxes].every(b => b.checked);
    boxes.forEach(b => b.checked = !allChecked);
    updateDeleteBtn();
}

function updateDeleteBtn() {
    const checked = document.querySelectorAll('.notif-checkbox:checked').length;
    const btn = document.getElementById('adminDeleteBtn');
    const count = document.getElementById('adminSelCount');
    if (btn) { btn.disabled = checked === 0; count.textContent = checked; }
}

function confirmBulkDelete() {
    const count = document.querySelectorAll('.notif-checkbox:checked').length;
    return count > 0 && confirm('Delete ' + count + ' selected notification(s)? This cannot be undone.');
}

document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.notif-checkbox').forEach(cb => cb.addEventListener('change', updateDeleteBtn));
});
</script>
