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

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);

    $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('/var/www/web10/htdocs/intranet/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);



// Format current date to match the validity_from format (YYYY-MM-DD)
$currDate = date('Y-m-d');

// Query to get all collections where validity_from matches today's date
$query_get_all_current_collections = "SELECT * FROM main_collection WHERE delayed_notification = 1 AND validity_from = '$currDate'";
$result_collections = $conn->query($query_get_all_current_collections);

if ($result_collections->num_rows > 0) {
    // Loop through each collection
    while ($row = $result_collections->fetch_assoc()) {

        print_r($row["description"]);
        print_r($row["id"]);
        $article_name = $row["description"];


        echo "<br>--------------------<br>";

        $department_ids = [];
        $role_ids = [];

        $query_get_department = "SELECT * FROM intranet_teil_link WHERE content_type = 'collection' AND content_id = " . $row['id'];
        $result_department = $conn->query($query_get_department);

        while ($row_department = $result_department->fetch_assoc()) {
            $department_ids[] = $row_department['main_department_id'];
            var_dump($row_department);
        }

        echo "<br>--------------------<br>";

        $query_get_role = "SELECT * FROM intranet_role_link WHERE content_type = 'collection' AND content_id = " . $row['id'];
        $result_role = $conn->query($query_get_role);

        while ($row_role = $result_role->fetch_assoc()) {
            $role_ids[] = $row_role['main_role_id'];
            var_dump($row_role);
        }

        // Create comma-separated strings
        $abteilung = implode(',', $department_ids);
        $role = implode(',', $role_ids);

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

        $mergedArray = [];

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


        $tokenArray = [];
        // print_r($mergedArray);
        // print_r($abteilungArray);
        // print_r($roleArray);
        var_dump($mergedArray);
        foreach ($mergedArray as $element) {

            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'];
            }
            // var_dump($sql);
            var_dump($sql);
            $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";
                                }
                            }
                        }
                    }
                }
            }
        }
        // var_dump($tokenArray);
        // foreach ($tokenArray as $token) {
        //     // print("würde gesendet: <br>");
        //     send($token['token'], "Neuer Beitrag im Intranet", $article_name);
        // }


    }
} else {
    echo "No collections found for today.";
}

$query = "INSERT INTO cron_jobs (name) VALUES ('send_custom_notif')";
$result = $conn->query($query);


