<?php

function sendOneSignalNotification($title, $message, $playerIds, $url = null, $imageUrl = null) {
    $content = array(
        "en" => $message
    );

    $fields = array(
        'app_id' => "99424ad8-e933-4396-bc62-40c08c6d5b8d", // Your OneSignal App ID
        'include_player_ids' => $playerIds,
        'headings' => array("en" => $title),
        'contents' => $content
    );

    // Add optional URL
    if ($url) {
        $fields['url'] = $url;
    }

    // Add optional Image URL
    if ($imageUrl) {
        $fields['big_picture'] = $imageUrl; // OneSignal specific key for large images
    }

    $fields = json_encode($fields);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json; charset=utf-8',
        'Authorization: Basic NjdhMzQ5OTktNWU1NC00MDBjLWE1YjktMTBhZmU4YzNlZDJl' // Your OneSignal REST API Key
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}

function fetchPlayerIdsFromOneSignal($limit = 50, $offset = 0) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/players?app_id=99424ad8-e933-4396-bc62-40c08c6d5b8d&limit={$limit}&offset={$offset}");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json; charset=utf-8',
        'Authorization: Basic NjdhMzQ5OTktNWU1NC00MDBjLWE1YjktMTBhZmU4YzNlZDJl' // Your OneSignal REST API Key
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    $response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($response, true);
    if (isset($data['players'])) {
        return array_column($data['players'], 'id'); // Extracting player IDs
    }
    return [];
}

$title = $_POST['title'] ?? '';
$message = $_POST['message'] ?? '';
$target = $_POST['target'] ?? '';
$url = $_POST['url'] ?? null;
$imageUrl = $_POST['image_url'] ?? null;
$playerId = $_POST['player_id'] ?? '';

$toastMessage = "";
$toastType = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($target === 'all') {
        // Fetch all player IDs from OneSignal
        $playerIds = fetchPlayerIdsFromOneSignal();

        if (!empty($playerIds)) {
            $response = sendOneSignalNotification($title, $message, $playerIds, $url, $imageUrl);
            $toastMessage = "Notification sent to all users!";
            $toastType = "success";
        } else {
            $toastMessage = "No players found!";
            $toastType = "error";
        }
    } elseif ($target === 'select') {
        if ($playerId) {
            $response = sendOneSignalNotification($title, $message, array($playerId), $url, $imageUrl);
            $toastMessage = "Notification sent to selected user!";
            $toastType = "success";
        } else {
            $toastMessage = "Player ID is missing!";
            $toastType = "error";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>SwiftBIT | Dashboard</title>
  <!-- Favicon -->
  <link rel="shortcut icon" href="./img/svg/logo.svg" type="image/x-icon">
  <!-- Custom styles -->
  <link rel="stylesheet" href="./css/style.min.css">
</head>
<style>
    .container2 {
        background-color: #fff;
        border-radius: 15px;
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
        width: 97%;
        padding: 30px;
        margin: 6px;
        text-align: center;
        animation: fadeIn 0.5s ease-in-out;
    }

    @keyframes fadeIn {
        from { opacity: 0; transform: scale(0.9); }
        to { opacity: 1; transform: scale(1); }
    }

    h1 {
        color: #333;
        margin-bottom: 25px;
        font-size: 24px;
    }

    label {
        display: block;
        color: #555;
        margin-bottom: 10px;
        font-weight: 600;
    }

    input[type="text"], input[type="url"], textarea, select {
        width: 100%;
        padding: 12px;
        margin-bottom: 20px;
        border: none;
        border-radius: 8px;
        background-color: #f0f0f0;
        box-sizing: border-box;
        font-size: 14px;
    }

    textarea {
        height: 100px;
        resize: none;
    }

    .btn {
        width: 100%;
        background-color: #48c6ef;
        color: white;
        padding: 12px;
        border: none;
        border-radius: 8px;
        cursor: pointer;
        font-weight: 700;
        font-size: 16px;
        text-transform: uppercase;
        transition: background-color 0.3s ease;
    }

    .btn:hover {
        background-color: #6f86d6;
    }

    .btn:disabled {
        background-color: #ccc;
        cursor: not-allowed;
    }

    .toast {
        display: none;
        position: fixed;
        top: 20px;
        right: 20px;
        background-color: #333;
        color: white;
        padding: 12px 20px;
        border-radius: 8px;
        z-index: 1000;
        opacity: 0;
        transform: translateX(100%);
        transition: transform 0.5s ease, opacity 0.5s ease;
    }

    .toast.success {
        background-color: #48c6ef;
    }

    .toast.error {
        background-color: #f44336;
    }

    .toast.show {
        display: block;
        opacity: 1;
        transform: translateX(0%);
    }
</style>
<body>
  <div class="layer"></div>
<!-- ! Body -->
<a class="skip-link sr-only" href="#skip-target">Skip to content</a>
<div class="page-flex">
  <!-- ! Sidebar -->
  <aside class="sidebar">
    <!-- Sidebar content -->
  </aside>
  <div class="main-wrapper">
    <!-- ! Main nav -->
    <nav class="main-nav--bg">
      <div class="container main-nav">
        <!-- Main nav content -->
      </div>
    </nav>
    <!-- ! Main start -->

    <div class="container2">
        <h1>Send Notification</h1>
        <form method="POST" action="">
            <label for="title">Notification Title:</label>
            <input type="text" id="title" name="title" value="<?php echo htmlspecialchars($title); ?>" required>

            <label for="message">Notification Message:</label>
            <textarea id="message" name="message" required><?php echo htmlspecialchars($message); ?></textarea>

            <label for="target">Target:</label>
            <select id="target" name="target" required>
                <option value="all" <?php if ($target === 'all') echo 'selected'; ?>>All Users</option>
                <option value="select" <?php if ($target === 'select') echo 'selected'; ?>>Select User</option>
            </select>

            <div id="playerIdField" style="display: <?php echo $target === 'select' ? 'block' : 'none'; ?>;">
                <label for="player_id">Player ID:</label>
                <input type="text" id="player_id" name="player_id" value="<?php echo htmlspecialchars($playerId); ?>">
            </div>

            <label for="url">Optional URL:</label>
            <input type="url" id="url" name="url" value="<?php echo htmlspecialchars($url); ?>">

            <label for="image_url">Optional Image URL:</label>
            <input type="url" id="image_url" name="image_url" value="<?php echo htmlspecialchars($imageUrl); ?>">

            <button type="submit" class="btn">Send Notification</button>
        </form>

        <div id="toast" class="toast"></div>
    </div>

    <script>
        document.getElementById('target').addEventListener('change', function() {
            var playerIdField = document.getElementById('playerIdField');
            if (this.value === 'select') {
                playerIdField.style.display = 'block';
            } else {
                playerIdField.style.display = 'none';
            }
        });

        // Toast Notification
        var toast = document.getElementById('toast');
        var toastMessage = "<?php echo $toastMessage; ?>";
        var toastType = "<?php echo $toastType; ?>";

        if (toastMessage) {
            toast.classList.add(toastType);
            toast.textContent = toastMessage;
            toast.classList.add('show');

            setTimeout(function() {
                toast.classList.remove('show');
            }, 3000);
        }
    </script>

    <!-- ! Main close-->

    <!-- Chart library -->
    <script src="./plugins/chart.min.js"></script>
    <!-- Icons library -->
    <script src="plugins/feather.min.js"></script>
    <!-- Custom scripts -->
    <script src="js/script.js"></script>
  </div>
</body>
</html>
