<?php
/********************************************************************************
 * (c)1337 aheadware.com - All rights reserved
 ********************************************************************************/


class TB_Server_Core_OneSignal
{
    /**
     * @param $headline
     * @param $message
     * @param array $profileIds
     * @param array|NULL $additionalData
     */
    public static function sendToProfiles( $headline, $message, array $profileIds, array $additionalData = NULL )
    {

        if ( 'LIVE' !== Francis_Utils_Config::get( 'environment' ) ) return;

        $playerIds = self::getPlayerIdsFromProfileIds( $profileIds );

        $content = array(
            "en" => $message
        );

        $headings = array(
            "en" => $headline
        );

        $fields = array(
            "app_id" => Francis_Utils_Config::get( 'onesignal.appId' ),
            //"included_segments" => array('Active Users'),
            "include_player_ids" => $playerIds,
            "data" => $additionalData,
            "contents" => $content,
            "headings" => $headings
        );

        try
        {
            $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'));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

            $response = curl_exec($ch);
            //$res = json_decode( $response );
            curl_close($ch);
        }
        catch( Exception $e )
        {
            // @todo Logg
        }
    }

    /**
     * @param array $profileIds
     * @return array
     */
    private static function getPlayerIdsFromProfileIds( array $profileIds )
    {
        $playerIds = array();

        $accountIds = TB_Shared_Ent_TeamData_Profile::getAccountIdOfProfileIds( $profileIds );
        $playerIds = TB_Shared_Ent_Core_DeviceReg::getDeviceRegsByAccountIds( $accountIds );

        return $playerIds;
    }
}