<?php
// ✅ Debug mode ON
error_reporting(E_ALL);
ini_set('display_errors', 1);

include("_serveur.php");        // contains $link
include("sjmSendPush.php"); // contains sendPush()

$messageStatus = "";
$sentDevices = [];

// Function to insert notification + send push to devices
function sendNotificationToUser($link, $title, $message, $date, $userID) {
    global $sentDevices;

    // Get user type
    $res = $link->query("SELECT type FROM users WHERE id=".(int)$userID." LIMIT 1");
    if (!$res || $res->num_rows == 0) return;
    $row = $res->fetch_assoc();
    $userType = $row['type'];

    // Insert into notifications
    $stmt = $link->prepare("INSERT INTO notifications (title, description, date, userType, userID) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("sssii", $title, $message, $date, $userType, $userID);
    $stmt->execute();
    $stmt->close();

    // Fetch devices for this user
    $deviceQuery = $link->prepare("SELECT id, deviceType FROM devices WHERE userID = ?");
    $deviceQuery->bind_param("i", $userID);
    $deviceQuery->execute();
    $deviceResult = $deviceQuery->get_result();

    while ($deviceRow = $deviceResult->fetch_assoc()) {
        $pushid     = $deviceRow['id'];        // device token
        $deviceType = $deviceRow['deviceType']; // ios or android
        if($deviceType=="ios") $deviceType="iOS";
        // Build payload
        $payload = [
            'type'    => $deviceType,
            'data'    => ["title" => $title, "body" => $message],
            'devices' => [$pushid]
        ];

        // Send push using the included function
        $result = sendPush(json_encode($payload));

        // Save device info for display
        $sentDevices[] = [
            'userID'     => $userID,
            'deviceID'   => $pushid,
            'deviceType' => $deviceType,
            'pushResult' => $result
        ];
    }

    $deviceQuery->close();
}

// Handle form submission
if (isset($_POST['send']) || isset($_POST['sendType1']) || isset($_POST['sendType2'])) {
    $title = trim($_POST['title']);
    $message = trim($_POST['message']);
    $date = date("Y-m-d");

    if (isset($_POST['sendType1'])) {
        $sql = "SELECT id FROM users WHERE type = 1";
        $result = $link->query($sql);
        while ($row = $result->fetch_assoc()) {
            sendNotificationToUser($link, $title, $message, $date, $row['id']);
        }
        $messageStatus = "<div class='success'>✅ Notification sent to all Type 1 users.</div>";
    }
    elseif (isset($_POST['sendType2'])) {
        $sql = "SELECT id FROM users WHERE type = 2";
        $result = $link->query($sql);
        while ($row = $result->fetch_assoc()) {
            sendNotificationToUser($link, $title, $message, $date, $row['id']);
        }
        $messageStatus = "<div class='success'>✅ Notification sent to all Type 2 users.</div>";
    }
    elseif (!empty($_POST['users'])) {
        foreach ($_POST['users'] as $userID) {
            sendNotificationToUser($link, $title, $message, $date, $userID);
        }
        $messageStatus = "<div class='success'>✅ Notifications sent to selected users.</div>";
    }
    else {
        $messageStatus = "<div class='error'>⚠️ Please select at least one user or choose a group.</div>";
    }
}

// Fetch all type 1 & 2 users
$sql = "SELECT id, username, firstName, lastName, type 
        FROM users 
        WHERE type IN (1,2) 
        ORDER BY type, lastName";
$result = $link->query($sql);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Send Notifications</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
h2 { color: #333; }
input[type=text], textarea { width: 400px; padding: 5px; }
button { margin: 5px; padding: 8px 15px; cursor: pointer; border: none; border-radius: 4px; }
button:hover { opacity: 0.9; }
.user-list { border: 1px solid #ccc; padding: 10px; max-height: 300px; overflow-y: auto; width: 420px; background: #f9f9f9; }
.success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; padding: 10px; margin-bottom: 15px; }
.error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; padding: 10px; margin-bottom: 15px; }
.device-box { margin-top:20px; padding:10px; border:1px solid #ddd; background:#f1f1f1; white-space: pre-wrap; }
</style>
</head>
<body>

<h2>Send Notification</h2>
<?php echo $messageStatus; ?>

<form method="post" action="">
    <label><b>Title:</b></label><br>
    <input type="text" name="title" id="title" required><br><br>

    <label><b>Message:</b></label><br>
    <textarea name="message" id="message" rows="5" required></textarea><br><br>

    <div class="user-list">
        <label><input type="checkbox" id="selectAll" onclick="toggleAll(this)"> <b>Select All</b></label><br><br>
        <?php
        if ($result && $result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                echo "<label><input type='checkbox' name='users[]' value='{$row['id']}'> 
                      {$row['firstName']} {$row['lastName']} ({$row['username']}) [Type: {$row['type']}]</label><br>";
            }
        } else {
            echo "⚠️ No users with type 1 or 2 found in database.";
        }
        ?>
    </div><br>

    <button type="submit" name="send">📩 Send to Selected Users</button>
    <button type="submit" name="sendType1" style="background:#007bff; color:white;" onclick="return previewConfirm('Type 1')">👥 Send to All Type 1 Users</button>
    <button type="submit" name="sendType2" style="background:#28a745; color:white;" onclick="return previewConfirm('Type 2')">👥 Send to All Type 2 Users</button>
</form>

<?php if (!empty($sentDevices)) : ?>
<div class="device-box">
    <h3>📱 Push Results:</h3>
    <ul>
    <?php foreach ($sentDevices as $d): ?>
        <li>
            UserID <?= $d['userID']; ?> → DeviceID: <?= $d['deviceID']; ?> (<?= $d['deviceType']; ?>)<br>
            <b>API Response:</b><br><?= htmlentities($d['pushResult']); ?>
        </li>
    <?php endforeach; ?>
    </ul>
</div>
<?php endif; ?>

<script>
function toggleAll(source) {
    let checkboxes = document.getElementsByName('users[]');
    for(let i=0; i < checkboxes.length; i++) {
        checkboxes[i].checked = source.checked;
    }
}
function previewConfirm(group) {
    let title = document.getElementById("title").value.trim();
    let message = document.getElementById("message").value.trim();
    if (title === "" || message === "") {
        alert("⚠️ Please enter both Title and Message before sending.");
        return false;
    }
    return confirm("🚨 Send this notification to ALL " + group + " users?\n\n" +
                   "Title: " + title + "\nMessage:\n" + message);
}
</script>
</body>
</html>
<?php $link->close(); ?>
