<?php
$user = $_POST['user'];
$title = $_POST['title'];
$body = $_POST['body'];
$domain = $_POST['domain'];


$news_id = $_POST["news_id"];


function getAccessToken($jsonKeyPath)
{
    try {

        $jwt = generateJWT($jsonKeyPath);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://oauth2.googleapis.com/token');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
            'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
            'assertion' => $jwt,
        ]));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded',
        ]);

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

        $jsonResponse = json_decode($response, true);
    } catch (\Throwable $th) {
        echo $th;
    }
    return $jsonResponse['access_token'];
}

function generateJWT($jsonKeyPath)
{
    $jsonKey = json_decode(file_get_contents($jsonKeyPath), true);

    $header = base64_encode(json_encode([
        'alg' => 'RS256',
        'typ' => 'JWT',
    ]));

    $iat = time();
    $exp = $iat + 3600; // 1 час
    $claimSet = base64_encode(json_encode([
        'iss' => $jsonKey['client_email'],
        'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
        'aud' => 'https://oauth2.googleapis.com/token',
        'exp' => $exp,
        'iat' => $iat,
    ]));

    $signatureInput = $header . '.' . $claimSet;

    openssl_sign($signatureInput, $signature, openssl_pkey_get_private($jsonKey['private_key']), 'sha256');
    $signature = base64_encode($signature);

    return $signatureInput . '.' . $signature;
}





// $jsonKeyPath = '../../notifications-c5c54-a9705bfea23c.json';
$jsonKeyPath = 'secrets/notifications-c5c54-a9705bfea23c.json';


$accessToken = getAccessToken($jsonKeyPath);



$url = 'https://fcm.googleapis.com/v1/projects/notifications-c5c54/messages:send';
$host = $_SERVER['HTTP_HOST'];




// HERE NEW LOGIC
// GET ALl MANDANTS FROM NEWS ID
$mysql_con = new mysqli("localhost", "web4_intranet", "WewJedjuAbEynk3", "web4_intranet");

$allowed_contact_ids = [];

$all_mandants_query = "SELECT main_mandant_id FROM `main_collection_mandant_link` WHERE main_collection_id = " . (int) $news_id;
$sql_all_mandants = @mysqli_query($mysql_con, $all_mandants_query);
while ($row = @mysqli_fetch_assoc($sql_all_mandants)) {
    $all_mandants[] = $row["main_mandant_id"];
}

$all_departments_query = "SELECT main_department_id FROM `main_collection_department_link` WHERE main_collection_id = " . (int) $news_id;
$sql_all_departments = @mysqli_query($mysql_con, $all_departments_query);
while ($row = @mysqli_fetch_assoc($sql_all_departments)) {
    $all_departments[] = $row["main_department_id"];
}

$all_fachbereich_query = "SELECT main_fachbereich_id FROM `main_collection_fachbereich_link` WHERE main_collection_id = " . (int) $news_id;
$sql_all_fachbereichs = @mysqli_query($mysql_con, $all_fachbereich_query);
while ($row = @mysqli_fetch_assoc($sql_all_fachbereichs)) {
    $all_fachbereichs[] = $row["main_fachbereich_id"];
}

$all_einrichtungen_query = "SELECT main_einricht_id FROM `main_collection_einricht_link` WHERE main_collection_id = " . (int) $news_id;
$sql_all_einrichtungen = @mysqli_query($mysql_con, $all_einrichtungen_query);
while ($row = @mysqli_fetch_assoc($sql_all_einrichtungen)) {
    $all_einrichtungen[] = $row["main_einricht_id"];
}

$all_role_query = "SELECT main_role_id FROM `main_collection_role_link` WHERE main_collection_id = " . (int) $news_id;
$sql_all_rolles = @mysqli_query($mysql_con, $all_role_query);
while ($row = @mysqli_fetch_assoc($sql_all_rolles)) {
    $all_rolles[] = $row["main_role_id"];
}



$query_get_all_contacts = "SELECT * FROM main_contact_department";
$sql_get_all_contacts = @mysqli_query($mysql_con, $query_get_all_contacts);


while ($row = mysqli_fetch_assoc($sql_get_all_contacts)) {

    $count++;
    // 1. Mandant
    if (!empty($all_mandants) && !in_array($row["main_mandant_id"], $all_mandants)) {
        continue;
    }

    // 2. Department
    if (!empty($all_departments) && !in_array($row["main_department_id"], $all_departments)) {
        continue;
    }

    if (!empty($all_fachbereichs) && !in_array($row["main_bereich_id"], $all_fachbereichs)) {
        continue;
    }

    if (!empty($all_einrichtungen) && !in_array($row["main_einricht_id"], $all_einrichtungen)) {
        continue;
    }

    if (!empty($all_rolles) && !in_array($row["main_role_id"], $all_rolles)) {
        continue;
    }

    $allowed_contact_ids[] = $row["main_contact_id"];
}

$allowed_contact_ids = array_unique($allowed_contact_ids);

foreach ($allowed_contact_ids as $cid) {
    $query_contact_token = "SELECT * FROM token_contact WHERE contact_id = " . (int) $cid . " AND in_system = 1 ORDER BY id DESC LIMIT 1";
    $sql_contactn_token = @mysqli_query($mysql_con, $query_contact_token);


    while ($row_token = @mysqli_fetch_assoc($sql_contactn_token)) {


        $contactId = trim($row_token['contact_id'] ?? '');
        $token = trim($row_token['token'] ?? '');

        if (
            $contactId === '' || $contactId === 'undefined' ||
            $token === '' || $token === 'undefined'
        ) {
            continue;
        }


        $data = [
            'message' => [
                'token' => $row_token["token"],
                'notification' => [
                    'title' => $title,
                    'body' => $body,
                ],
            ],
        ];




        $jsonData = json_encode($data);

        $ch = curl_init($url);


        $headers = [
            'Authorization: Bearer ' . $accessToken,
            'Content-Type: application/json; charset=UTF-8',
        ];


        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);


        $response = curl_exec($ch);

        curl_close($ch);




    }
}

?>