<?php
// FILE: public_html/Nag/notifications.php
session_start();
require_once '../db.php'; 
// ✅ LINK TO YOUR V1 HELPER
require_once '../api/fcm_helper.php';

$msg = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title']);
    $message = trim($_POST['message']);
    $target = $_POST['target']; // 'all' or specific user_id

    if ($target === 'all') {
        // 1. Save to DB for ALL users
        $users = $conn->query("SELECT id FROM users");
        while ($u = $users->fetch_assoc()) {
            $uid = $u['id'];
            $conn->query("INSERT INTO user_notifications (user_id, title, message) VALUES ($uid, '$title', '$message')");
        }
        
        // 2. Loop active tokens & Send
        // (Sending to loop is more reliable than topic for now)
        $tokens = $conn->query("SELECT fcm_token FROM users WHERE fcm_token IS NOT NULL AND fcm_token != ''");
        while($t = $tokens->fetch_assoc()){
            sendFCMV1($t['fcm_token'], $title, $message);
        }

        $msg = "<div class='alert alert-success'>Sent to ALL users!</div>";
        
    } else {
        // Send to SINGLE user
        $uid = intval($target);
        
        // 1. Save to DB
        $conn->query("INSERT INTO user_notifications (user_id, title, message) VALUES ($uid, '$title', '$message')");
        
        // 2. Fetch Token & Send Push
        $q = $conn->query("SELECT fcm_token FROM users WHERE id = $uid");
        $token = $q->fetch_assoc()['fcm_token'] ?? '';
        
        if(!empty($token)) {
            $res = sendFCMV1($token, $title, $message, ["type" => "admin_msg"]);
            $msg = "<div class='alert alert-success'>Sent! (FCM Response: " . htmlspecialchars(substr($res, 0, 50)) . "...)</div>";
        } else {
             $msg = "<div class='alert alert-warning'>Saved to DB, but User has no Device Token (App not opened yet).</div>";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Send Notifications - Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { font-family: 'Segoe UI', sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #f4f7f6; }
        .container { background: white; padding: 30px; border-radius: 15px; width: 100%; max-width: 500px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); }
        input, select, textarea { width: 100%; padding: 10px; margin-bottom: 15px; border: 1px solid #ddd; border-radius: 5px; box-sizing: border-box; }
        button { width: 100%; padding: 12px; background: #2c5364; color: white; border: none; border-radius: 5px; cursor: pointer; }
        .alert { padding: 10px; margin-bottom: 15px; border-radius: 5px; text-align: center; }
        .alert-success { background: #dcfce7; color: #166534; }
        .alert-warning { background: #fff3cd; color: #856404; }
    </style>
</head>
<body>
<div class="container">
    <h2 style="text-align:center">Send Notification</h2>
    <?php echo $msg; ?>
    <form method="POST">
        <label>Target Audience</label>
        <select name="target" required>
            <option value="all">All Users</option>
            <?php 
            $usrs = $conn->query("SELECT id, username FROM users ORDER BY id DESC");
            while($row = $usrs->fetch_assoc()): ?>
                <option value="<?php echo $row['id']; ?>"><?php echo $row['username']; ?> (ID: <?php echo $row['id']; ?>)</option>
            <?php endwhile; ?>
        </select>
        <input type="text" name="title" placeholder="Title" required>
        <textarea name="message" rows="4" placeholder="Message..." required></textarea>
        <button type="submit">Send Now</button>
    </form>
</div>
</body>
</html>