<?php
error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR);
ini_set('display_errors', 1);

$user = $_POST['user'];
$title = $_POST['title'];
$body = $_POST['body'];
$abteilung = $_POST['abteilung'];
$role = $_POST['role'];
$domain = $_POST['domain'];
$input_collection_id = $_POST['input_collection_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;
}

function send($token, $username, $message)
{
    // $jsonKeyPath = '../../notifications-c5c54-a9705bfea23c.json';
    $jsonKeyPath = 'secrets/notifications-c5c54-a9705bfea23c.json';
    $accessToken = getAccessToken($jsonKeyPath);


    /*

    {
    "message": {
        "token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJzaG9ydGN1dCI6ImVhIn0.mcO9WT0VV_lXJp48mu3XF9E9bKEdCitoKogAk067LwQ",
            "notification": {
            "title": "Breaking News",
            "body": "New news story available."
            },
            "data": {
            "story_id": "story_12345"
            }
        }
    }

    */

    $json = json_encode([
        "message" => [
            "token" => $token,
            "notification" => [
                "title" => $username,
                "body" => $message
            ],
            "data" => [
                "story_id" => "story_12345",
                "badgeIncrement" => "1"
            ],
            "apns" => [
                "payload" => [
                    "aps" => [
                        "content-available" => 1
                    ]
                ]
            ]
        ]
    ]);



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


    $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, $json);

    $response = curl_exec($ch);


    curl_close($ch);


}


$env = parse_ini_file('../../config/.env');

$db_host = $env['MAIN_MYSQL_DB_HOST'];
$db_port = $env['MAIN_MYSQL_DB_PORT'];
$db_user = $env['MAIN_MYSQL_DB_USER'];
$db_pass = $env['MAIN_MYSQL_DB_PASS'];
$db_schema = $env['MAIN_MYSQL_DB_SCHEMA'];

$conn = new mysqli($db_host, $db_user, $db_pass, $db_schema, $db_port);

$abteilungArray = explode(',', $abteilung);
$roleArray = explode(',', $role);

$mergedArray = [];

foreach ($abteilungArray as $abteilung) {
    foreach ($roleArray as $role) {
        $mergedArray[] = [
            'abteilung' => $abteilung,
            'role' => $role
        ];
    }
}

$query_collection_name = "SELECT * FROM main_collection WHERE id = " . $input_collection_id;
$result = $conn->query($query_collection_name);
if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $collection_name = $row['description'];
} else {
    echo "collection not found";
    die();
}

$tokenArray = [];
// print_r($mergedArray);
// print_r($abteilungArray);
// print_r($roleArray);
foreach ($mergedArray as $element) {
    // $sql = "SELECT DISTINCT main_contact_id FROM main_contact_department WHERE main_mandant_id = 1 AND active = 1 and main_department_id = " . $element['abteilung'] . " and main_role_id = " . $element['role'];
    // var_dump($sql);
    if ($element['abteilung'] == "" && $element['role'] == "") {

        $sql = "SELECT DISTINCT main_contact_id FROM main_contact_department WHERE main_mandant_id = 1 AND active = 1";
    } else if ($element['abteilung'] == "") {
        $sql = "SELECT DISTINCT main_contact_id FROM main_contact_department WHERE main_mandant_id = 1 AND active = 1 and main_role_id = " . $element['role'];
    } else if ($element['role'] == "") {
        $sql = "SELECT DISTINCT main_contact_id FROM main_contact_department WHERE main_mandant_id = 1 AND active = 1 and main_department_id = " . $element['abteilung'];
    } else {
        $sql = "SELECT DISTINCT main_contact_id FROM main_contact_department WHERE main_mandant_id = 1 AND active = 1 and main_department_id = " . $element['abteilung'] . " and main_role_id = " . $element['role'];
    }
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $query = "SELECT DISTINCT main_contact.id, main_contact.name, token_contact.token as 'token' FROM main_contact LEFT JOIN token_contact ON token_contact.contact_id = main_contact.id WHERE main_contact.id = '" . $row['main_contact_id'] . "'";
            // var_dump($query);
            $user_result = $conn->query($query);
            if ($user_result->num_rows > 0) {
                while ($contact = $user_result->fetch_assoc()) {
                    if ($contact['token'] != null && $contact['token'] != "") {
                        // send($contact['token'], "Intranet", "Neuer Beitrag im Intranet");
                        $contact_info = [
                            'id' => $contact['id'],
                            'name' => $contact['name'],
                            'token' => $contact['token']
                        ];
                        if (!in_array($contact_info, $tokenArray, true)) {
                            $tokenArray[] = $contact_info;
                        } else {
                            // echo "Already in array";
                        }
                    }
                }
            }
        }
    }
}

foreach ($tokenArray as $token) {
    send($token['token'], "Neuer Beitrag im Intranet", $collection_name);
}

// send("cyO6CxjDS5S7fz5DX1vA95:APA91bGxyA0ai9h1oCt4vrEmfYu0Ics1uX8kxfWNztYgQF1oQgLD-Nql7dM88LfudccwCA3vKM7cQldqOfffbRv-9v_79B7bmnhlFOZUsEsaZVpqWoHaOEyTw7bYo6VY8aC00GGwv_M1", "Test breadcrumb", "Test message");