<?php

include '../db_connect.php';

$userid = $_POST['userid'];
$body   = $_POST['body'];
$title  = $_POST['title'];
$type   = $_POST['type']; // general / friend / chat / like
$image  = $_POST['image'] ?? "";

require 'get-access-token.php';
$con = dbConnect();

/* ---------------------------------------
   CHECK USERID LENGTH
---------------------------------------- */
$useridLength = strlen($userid);

if ($useridLength == 8) {
    // normal user
    $sql = "SELECT token FROM signup WHERE userid = ?";
} elseif ($useridLength == 9) {
    // page user
    $sql = "SELECT token FROM page_table WHERE userid = ?";
} else {
    die("Invalid userid length");
}

/* ---------------------------------------
   FETCH TOKEN
---------------------------------------- */
$stmt = $con->prepare($sql);
$stmt->bind_param("s", $userid);
$stmt->execute();
$stmt->bind_result($token);
$stmt->fetch();
$stmt->close();

if (empty($token)) {
    die("User token not found");
}

/* ---------------------------------------
   SELECT CHANNEL BASED ON TYPE
---------------------------------------- */
$channel = "bpaysocial_general";

if ($type === "friend") {
    $channel = "bpaysocial_friend";
} elseif ($type === "chat") {
    $channel = "bpaysocial_chat";
} elseif ($type === "like") {
    $channel = "bpaysocial_like";
}

/* ---------------------------------------
   FIREBASE SETUP
---------------------------------------- */
$serviceAccountKeyFile = 'service-account-file.json';
$accessToken = getAccessToken($serviceAccountKeyFile);

$url = "https://fcm.googleapis.com/v1/projects/bpay-social/messages:send";

/* ---------------------------------------
   PAYLOAD
---------------------------------------- */
$dataPayload = [
    "title" => $title,
    "body"  => $body,
    "type"  => $type,
    "image" => $image
];

$notification = [
    "title" => $title,
    "body"  => $body
];

$arrayToSend = [
    "token" => $token,
    "notification" => $notification,
    "data" => $dataPayload,
    "android" => [
        "notification" => [
            "channel_id" => $channel
        ]
    ]
];

$json = json_encode(["message" => $arrayToSend]);

$headers = [
    "Content-Type: application/json",
    "Authorization: Bearer " . $accessToken
];

/* ---------------------------------------
   SEND FCM
---------------------------------------- */
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

if ($response === false) {
    die("FCM Send Error: " . curl_error($ch));
}

curl_close($ch);

echo $response;
?>
