<?php
session_start();
include_once('../includes/db.php');

if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: admin_login.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = sanitize($_POST['title'] ?? '');
    $message = sanitize($_POST['message'] ?? '');
    $selectedUsers = $_POST['users'] ?? [];

    $stmt = $conn->prepare("INSERT INTO notifications (title, message, created_at) VALUES (?, ?, NOW())");
    $stmt->bind_param("ss", $title, $message);
    $stmt->execute();
    $stmt->close();

    if (!empty($selectedUsers)) {
        $fields = [
            'app_id' => '51ed977d-f573-4f8a-a74e-839b45f38c15',
            'include_external_user_ids' => $selectedUsers,
            'headings' => ['en' => $title],
            'contents' => ['en' => $message]
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json; charset=utf-8',
            'Authorization: Basic YOUR_REST_API_KEY'
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_exec($ch);
        curl_close($ch);
    }

    header("Location: manage_notifications.php");
    exit;
}

$users = fetchAll("SELECT id, name, onesignal_id FROM users WHERE onesignal_id IS NOT NULL");
$notifications = fetchAll("SELECT * FROM notifications ORDER BY created_at DESC");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Notifications - PrintShop Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f1f5f9;
            font-family: 'Segoe UI', sans-serif;
        }

        .main-content {
            margin-left: 250px;
            padding: 30px;
        }

        .card {
            border-radius: 1rem;
            border: none;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
        }

        .card-header {
            font-size: 18px;
            font-weight: 600;
            padding: 16px 24px;
        }

        .form-check-label {
            font-size: 14px;
        }

        .form-label {
            font-weight: 500;
        }

        .btn {
            border-radius: 8px;
        }

        .table td, .table th {
            vertical-align: middle;
        }
    </style>
</head>
<body>

<div class="d-flex">
    <?php include('admin_sidebar.php'); ?>

    <div class="main-content flex-grow-1">
        <!-- Send Notification -->
        <div class="card mb-4">
            <div class="card-header bg-black text-white rounded-top">
                🔔 Send Notification
            </div>
            <div class="card-body">
                <form method="POST">
                    <div class="mb-3">
                        <label class="form-label">Title</label>
                        <input type="text" name="title" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Message</label>
                        <textarea name="message" rows="3" class="form-control" required></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Select Users</label>
                        <div class="border rounded p-3 bg-white" style="max-height: 220px; overflow-y: auto;">
                            <?php if (!empty($users)): ?>
                                <?php foreach ($users as $user): ?>
                                    <div class="form-check mb-1">
                                        <input class="form-check-input" type="checkbox" name="users[]" value="<?= htmlspecialchars($user['onesignal_id']) ?>" id="user<?= $user['id'] ?>">
                                        <label class="form-check-label" for="user<?= $user['id'] ?>">
                                            <?= htmlspecialchars($user['name']) ?> (<?= htmlspecialchars($user['onesignal_id']) ?>)
                                        </label>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="alert alert-warning mb-0">No users available for notifications.</div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-success">📨 Send Notification</button>
                </form>
            </div>
        </div>

        <!-- Sent Notifications Table -->
        <div class="card">
            <div class="card-header bg-dark text-white rounded-top">
                📣 Sent Notifications
            </div>
            <div class="card-body">
                <?php if (empty($notifications)): ?>
                    <div class="alert alert-info">No notifications found.</div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover bg-white mt-2">
                            <thead class="table-dark">
                                <tr>
                                    <th>#</th>
                                    <th>Title</th>
                                    <th>Message</th>
                                    <th>Created At</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($notifications as $index => $note): ?>
                                    <tr>
                                        <td><?= $index + 1 ?></td>
                                        <td><?= htmlspecialchars($note['title']) ?></td>
                                        <td><?= nl2br(htmlspecialchars($note['message'])) ?></td>
                                        <td><?= date("Y-m-d H:i", strtotime($note['created_at'])) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

</body>
</html>
