<?php
// send_notification.php (Definitive Player ID Version)

header('Content-Type: application/json; charset=utf-8');

include 'db_connect.php'; 

if (isset($conn)) {
    $conn->set_charset("utf8mb4");
}

$ONE_SIGNAL_APP_ID = "1f5a994d-b58c-458d-8541-fd1b4da5a27e";
$ONE_SIGNAL_REST_API_KEY = "os_v2_app_d5njstnvrrcy3bkb7unu3jncp2x2p3oyw5tefn5nhsbm2ardd2rplkzfa7b63kiqsmmnezprpjt3crxcameqnqvpj2xglxabd2cng7q";

function sendOneSignalNotification($title, $message, $imageUrl, $appId, $apiKey, $player_ids = array()) {
    $content = array("en" => $message);
    $headings = array("en" => $title);

    $fields = array(
        'app_id' => $appId,
        'contents' => $content,
        'headings' => $headings,
        'small_icon' => 'ic_stat_notifications', 
        'large_icon' => 'ic_stat_notifications', 
        'android_accent_color' => '000000',
    );

    // --- PLAYER ID TARGETING ---
    if (!empty($player_ids)) {
        $fields['include_player_ids'] = $player_ids;
    } else {
        // Fallback to the old working method if no player IDs are found/provided
        $fields['included_segments'] = array('All');
    }
    // --- END TARGETING ---

    if ($imageUrl != null && !empty($imageUrl)) {
        $fields['big_picture'] = $imageUrl;
    }

    $fields_json = json_encode($fields, JSON_UNESCAPED_UNICODE);

    $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 ' . $apiKey
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_json);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

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

$response = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = isset($_POST['title']) ? $_POST['title'] : '';
    $message = isset($_POST['message']) ? $_POST['message'] : '';
    $imageUrl = isset($_POST['image_url']) ? $_POST['image_url'] : null;
    $target_user_role = isset($_POST['target_user_role']) ? $_POST['target_user_role'] : null;
    $target_user_id = isset($_POST['target_user_id']) ? (int)$_POST['target_user_id'] : 0;

    if (!empty($title) && !empty($message) && isset($conn)) {

        $player_ids_to_send = array();

        // Determine the target player IDs from the database
        if ($target_user_role) {
            $stmt = $conn->prepare("SELECT onesignal_player_id FROM users WHERE role = ? AND onesignal_player_id IS NOT NULL");
            $stmt->bind_param("s", $target_user_role);
            $stmt->execute();
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $player_ids_to_send[] = $row['onesignal_player_id'];
            }
            $stmt->close();
        } elseif ($target_user_id > 0) {
            $stmt = $conn->prepare("SELECT onesignal_player_id FROM users WHERE id = ? AND onesignal_player_id IS NOT NULL");
            $stmt->bind_param("i", $target_user_id);
            $stmt->execute();
            $result = $stmt->get_result();
            if ($row = $result->fetch_assoc()) {
                $player_ids_to_send[] = $row['onesignal_player_id'];
            }
            $stmt->close();
        }

        // Logic to save notification to DB
        if (!isset($target_user_id) || $target_user_id == 0) {
             $stmt_insert = $conn->prepare("INSERT INTO notifications (title, message, image_url) VALUES (?, ?, ?)");
             $stmt_insert->bind_param("sss", $title, $message, $imageUrl);
             $stmt_insert->execute();
             $stmt_insert->close();
        }

        // Construct absolute URL for OneSignal
        $oneSignalImageUrl = $imageUrl;
        if ($imageUrl != null && !empty($imageUrl) && !preg_match('/^https?:\/\//', $imageUrl)) {
            $baseUrl = "https://flowtechbd.com"; 
            $oneSignalImageUrl = (substr($imageUrl, 0, 1) === '/') ? $baseUrl . $imageUrl : $baseUrl . '/' . $imageUrl;
        }

        // Send the notification
        $oneSignalResponse = sendOneSignalNotification($title, $message, $oneSignalImageUrl, $ONE_SIGNAL_APP_ID, $ONE_SIGNAL_REST_API_KEY, $player_ids_to_send);
        
        $response['status'] = 'success';
        $response['message'] = 'Notification processed.';
        $response['onesignal_response'] = json_decode($oneSignalResponse);

    } else {
        $response['status'] = 'error';
        $response['message'] = 'Title, message, and database connection are required.';
    }
} else {
    $response['status'] = 'error';
    $response['message'] = 'Invalid request method.';
}

echo json_encode($response, JSON_UNESCAPED_UNICODE);

if (isset($conn)) {
    $conn->close();
}
?>