<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of sendApplePush
 *
 * @author admin@3embed
 */
//require_once 'ConDB.php';

class sendApplePush {

    private $db;                                        //Have database connection object
    private $apns_fp;                              //Have apns connection file pointer

    /**/
    public $token;                                    //Stores device token of the current user
    public $apns_con;                             //Have connection object for the apns server
    public $push_sent;                            //boolean, have push status.. sent or not
    public $tokenAvailable;                   //boolean, tells token available or not
    public $userName;                      //string, owner name who is sending the push/invitation
    public $userLoggedIn;                   //boolean, checks if the user loggedin in his device or not
    public $userIdPush;
    public $userDeviceType;

    /* Push message and notification details */
    public $pushDetStored;                  //boolean, checks if the details of the push notification stored or not
    public $pushDetId;                          //Stores generated id, after storing push note details
    public $badgeCount;
    public $sampleVar;
    public $notificationType = 0;
    public $media_id = 0;
    public $media_url = '';
    public $mDt = '';
    public $mSid = '';
    public $mAction = '';
    public $mUser = '';
    public $mTime = '';
    public $mType = '';
    public $test;

    public function __construct() {

        $this->db = new ConDB(); //db connection object

        $passphrase = '3embed'; //certificate local private key

        $ctx = stream_context_create();
        stream_context_set_option($ctx, 'ssl', 'local_cert', 'Chumber_dist_cert.pem'); //SnapChatCert//SneakPeak_Push_distribution//Chumber_dist_cert.pem//Chumber_dev_cert
        stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

        $this->apns_fp = stream_socket_client(
                'ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); //sandbox.

        if (!$this->apns_fp) {
            $this->apns_con = false;
//            echo 'not connected';
        } else {
            $this->apns_con = true;
        }
    }

    public function getUserDetails($userId) {
        $get_user_qry = "select id as userId,DeviceType,UserName,Token,loginFlag from user where id ='" . $userId . "'";
        $user_res = mysql_query($get_user_qry, $this->db->conn);
        $user_row = mysql_fetch_assoc($user_res);

        $this->userName = $user_row['UserName'];
    }

    public function getUserToken($userId) {
        $get_user_qry = "select id as userId,DeviceType,UserName,Token,loginFlag from user where id ='" . $userId . "'";
        $user_res = mysql_query($get_user_qry, $this->db->conn);
        $user_row = mysql_fetch_assoc($user_res);
        if ($user_row['Token'] == '') {
            $this->tokenAvailable = false;
        } else {
//            print_r($user_row);
            $this->userIdPush = $user_row['userId'];
            $this->tokenAvailable = true;
            $this->token = $user_row['Token'];
            $this->userName = $user_row['UserName'];
            $this->userLoggedIn = $user_row['loginFlag'];
            $this->userDeviceType = $user_row['DeviceType'];
        }
    }

    public function snapOptions($notifType) {
        $this->notificationType = $notifType;
    }

    public function snapMediaId($media) {
        $this->media_id = $media;
    }

    public function setMediaVars($media_url, $media_id, $mdt, $msid, $mAction, $mUser, $mTime, $mType) {
        $this->media_url = $media_url;
        $this->media_id = $media_id;
        $this->mDt = $mdt;
        $this->mSid = $msid;
        $this->mAction = $mAction;
        $this->mUser = $mUser;
        $this->mTime = $mTime;
        $this->mType = $mType;
    }

    public function pushOptions($logedIn, $devType) {
        $this->userDeviceType = $devType;
        $this->userLoggedIn = $logedIn;
    }

    //send push note, takes token and message
    public function sendAPush($token_arr, $message) {
//        if ($this->userLoggedIn == '1') { //checkes if user is logged-in in the app or not, if logged in then sends push note

        if ($this->userDeviceType == '1') {
//            print_r($token_arr);
            //$this->getBadgeCount($this->userIdPush);

            if ($this->notificationType == '4') {
                $body['aps'] = array(
//                    'badge' => +1, //$this->badgeCount,
                    'alert' => $message,
                    'NotifType' => $this->notificationType,
                    'ImagePath' => $this->media_url,
                    'MediaId' => (string)$this->media_id,
                    'DateTime' => $this->mDt,
                    'SenderId' => $this->mSid,
                    'Action' => $this->mAction,
                    'User' => $this->mUser,
                    'Time' => $this->mTime,
                    'Type' => $this->mType
                );
            } else {
                $body['aps'] = array(
//                    'badge' => +1, //$this->badgeCount,
                    'alert' => $message,
//                    'sound' => 'default',
                    'NotifType' => $this->notificationType,
                    'MediaId'=>  $this->media_id
                );
            }
            
            $payload = json_encode($body);
// Build the binary notification
            $msg = '';
            foreach ($token_arr as $token) {
//                echo $token;
                $msg .= chr(0) . pack('n', 32) . pack('H*', $token) . pack('n', strlen($payload)) . $payload;
            }
//print_r($body);
//                $msg = chr(0) . pack('n', 32) . pack('H*', $token) . pack('n', strlen($payload)) . $payload;
// Send it to the server
            $result = fwrite($this->apns_fp, $msg, strlen($msg));

            if (!$result) {
                $this->push_sent = false;
                $this->test = $body;
            } else {
//                echo 'here:'.$result;
                $this->push_sent = true;
            }
        } else if ($this->userDeviceType == '2') { //Checking if the user is an android user or not
//$url = 'https://android.googleapis.com/gcm/send'; // Use this if ssl is enabled, otherwise gives ssl certificate error
            $apiKey = 'AIzaSyC-b0OQK3DXNnRy-snFY8jpIyEyJdwL-RI'; //'AIzaSyAEorUyndT0Svfro1FrodXruPHzgYvXIDo';// 'AIzaSyDtQYVOf4rDwgZ0EiYlsR0fBNHukOd67jY';
            $url = 'http://android.googleapis.com/gcm/send';
            //$registrationIDs = array($token);
            
            if ($this->notificationType == '4') {
                $data = array(
                    'badge' => +1, //$this->badgeCount,
                    'payload' => $message,
                    //'sound' => 'default',
                    'action' => $this->notificationType,
                    'ImagePath' => $this->media_url,
                    'MediaId' => $this->media_id,
                    'DateTime' => $this->mDt,
                    'SenderId' => $this->mSid,
                    'mAction' => $this->mAction,
                    'User' => $this->mUser,
                    'Time' => $this->mTime,
                    'Type' => $this->mType
                );
            } else {
                $data = array(
                    'badge' => +1, //$this->badgeCount,
                    'payload' => $message,
                    //'sound' => 'default',
                    'action' => $this->notificationType,
                    'MediaId'=>  $this->media_id
                );
            }
            
//            $data = array("payload" => $message,
//                'action' => $this->notificationType,
//                'mid' => $this->media_id);

            $fields = array(
                'registration_ids' => $token_arr,
                'data' => $data,
            );

            $headers = array(
                'Authorization: key=' . $apiKey,
                'Content-Type: application/json'
            );
            // Open connection
            $ch = curl_init();

            // Set the url, number of POST vars, POST data
            curl_setopt($ch, CURLOPT_URL, $url);

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

            // Disabling SSL Certificate support temporarly
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

            $result = curl_exec($ch);
            // Execute post
            $res_dec = json_decode($result);

            if ($res_dec->success >= 1) {
                $this->push_sent = true;
            } else {
                $this->push_sent = false;
            }

            // Close connection
            curl_close($ch);
//        echo $result;
        }
//        } else {
//            $this->push_sent = true;
//        }
    }

//stores notification details into the database
    public function storePushDetails($owner_id, $reciever_id_arr, $msg) {
        $det_stored = 0;
        foreach ($reciever_id_arr as $reciever_id) {
            $insert_notif_qry = "insert into notifications(owner_id,reciever_id,datetime,message) 
                                        values('" . $owner_id . "','" . $reciever_id . "',NOW(),'" . $msg . "')";
//        $this->sampleVar = $insert_notif_qry;
            mysql_query($insert_notif_qry, $this->db->conn);
            $insertedId = mysql_insert_id();
            if (mysql_affected_rows() > 0) {
                $det_stored++;
            }
        }
        if ($det_stored == count($reciever_id_arr)) {
            $this->pushDetStored = true;
            $this->pushDetId = $insertedId;
//            $this->test_var = 'Inserted--'.$rec_id_test.$insert_notif_qry;
        } else {
            $this->pushDetStored = false;
//            $this->test_var = $insert_notif_qry;
        }
    }

    public function getBadgeCount($userId) {
        $getBadgesQry = "select count(id) as badgeCount from Notifications where notifStatus = 3 and reciever_id = " . $userId;
        $getBadgesRes = mysql_query($getBadgesQry, $this->db->conn);
        $badgeRow = mysql_fetch_assoc($getBadgesRes);
        if ($badgeRow['badgeCount'] == 0) {
            $this->badgeCount = $badgeRow['badgeCount'];
        } else {
            $this->badgeCount = $badgeRow['badgeCount'] + 1;
        }
    }

    public function setCurrentDeviceType($devType) {
        $this->userDeviceType = $devType;
        return $this->userDeviceType;
    }

    public function closeServerConn() {
        fclose($this->apns_fp); //close connection with the apple server
//        $this->db->close($this->db->conn);
    }

}

//function checkAppleErrorResponse($apns)
//{
//    $responseBinary = fread($apns, 6);
//    if ($responseBinary !== false && strlen($responseBinary) == 6)
//    {
//        print(
//            "\n"
//            .'Error message recieved from Apple.'."\n"
//            .'For the meaning, refer to: "Provider Communication with Apple Push Notification Service"'."\n"
//        );
//        $response = unpack('Ccommand/Cstatus_code/Nidentifier', $responseBinary);
//        var_dump($response);
//    }
//}
//            if(!$newPush->apns_con){
//                checkAppleErrorResponse($newPush->apns_con);
////                echo 'conn failed';
//            }
?>
