<?php
include "_api/appconfig.php";
session_start();

class Connection
{
    public $db;
    public $hostname;
    //public $fromMail = "noreply@cygnusa.com";
    public $passchar = "1234567890";
    public $groupID = "/topics/cygnusajtech1976";
    public $errorMsg = "NULL";
    public $pageData = "NULL";
    public $langDir = "../language/common.json";

    public function __construct()
    {
        $hostname = $_SERVER['HTTP_HOST'];
        //$this->db = $this->getConnection();
    }
    public function checkDatabase()
    {
        global $host;
        global $user;
        global $pass;
        global $dbname;
        try
        {
            $database = new PDO("mysql:host=" . HOST . ";dbname=" . DBNAME, DBUSER, DBPASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
            //$database->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
            return true;
        } catch (Exception $e) {
            return false;
        }
    }
    public function generateToken($length = 256)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }
    public function loadJSON($lang)
    {
        $pageData = json_decode(file_get_contents($this->langDir));
        $data = null;
        foreach ($pageData as $key => $value) {
            if ($key == $lang) {
                $data = $value;
            }
        }
        return $data;
    }

    public function getMessage($lang, $module, $message)
    {
        //echo $module.$message;
        if (file_exists("../language/" . $lang . "/admin.php")) {
            include_once "../language/" . $lang . "/admin.php";

            //echo $module." ".$message;
            //print_r($string[$module]);
            if (!isset($string[$module])) {
                echo $this->message(false, 'MODULE LANGUAGE FILE NOT FOUND');
            }

            if (!isset($string[$module][$message])) {
                echo $this->message(false, 'MESSAGE LANGUAGE FILE NOT FOUND');
            }

            return $string[$module][$message];
        } else {
            //$parent->response(array('response'=>'failed','message'=>'LANGUAGE FILE NOT FOUND'),500);
            echo $this->message(false, 'LANGUAGE FILE NOT FOUND');
        }
    }
    public function getConnection()
    {

        $this->db = new PDO("mysql:host=" . HOST . ";dbname=" . DBNAME, DBUSER, DBPASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->db->exec("SET CHARACTER SET utf8");
        return $this->db;
    }
    public function query($str)
    {
        try
        {
            $result = $this->db->query($str);
            return $result;
        } catch (PDOException $e) {
            echo "MYSQL ERROR " . $e->getMessage();exit;
        } catch (Exception $e) {
            echo "Error " . $e->getMessage();exit;
            //$this->response(array('response'=>'failed','message'=>$e->getMessage()),500);
        }
    }
    public function lastinsetid()
    {
        return $this->db->lastInsertId();
    }
    public function prepare($str)
    {
        $result = $this->db->prepare($str);
        return $result;
    }
    public function getUpdateData($str)
    {
        try
        {
            $selectquery = $this->query($str);
            $selectarr = $selectquery->fetchAll(PDO::FETCH_OBJ);
            return $selectarr[0];
        } catch (PDOException $e) {
            header("HTTP/1.1 500 Internal Server Error");
            $this->message(false, "MYSQL ERROR " . $e->getMessage());
        } catch (Exception $e) {
            //echo "Error ".$e->getMessage(); exit;
            header("HTTP/1.1 500 Internal Server Error");
            $this->message(false, "PHP ERROR " . $e->getMessage());
            //$this->response(array('response'=>'failed','message'=>$e->getMessage()),500);
        }
    }

    public function selectQuery($table_name, $field_name, $condition, $limitations = '')
    {
        try {
            if ($field_name == "") {
                $field_name = "*";
            }

            $select_query_str = "SELECT $field_name FROM $table_name";
            if ($condition != "") {
                $select_query_str .= " where $condition";
            }

            if ($limitations != "") {
                $select_query_str .= " limit $limitations";
            }

            //echo $select_query_str;
            $query_obj = $this->executeQuery($select_query_str);
            $num_rows = $query_obj->rowCount($query_obj);
            $result_value = array();
            if ($num_rows > 0) {
                $result_value = $query_obj->fetchAll(PDO::FETCH_OBJ);
            }
            return array('nr' => $num_rows, 'result' => $result_value);

        } catch (PDOException $e) {
            header("HTTP/1.1 500 Internal Server Error");
            $this->message(false, "MYSQL ERROR " . $e->getMessage());
        } catch (Exception $e) {
            header("HTTP/1.1 500 Internal Server Error");
            $this->message(false, "PHP ERROR " . $e->getMessage());
        }
    }

    public function message($cont, $mess, $item = null)
    {

        //header('Set-Cookie: same-site-cookie=foo; SameSite=Lax');
        //header('Set-Cookie: cross-site-cookie=bar; SameSite=None; Secure');
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
        header("Content-Type:application/json");

        $obj = new stdClass();
        $obj->mess = $mess;
        $obj->cont = $cont;
        if ($item != null) {
            $obj->item = $item;
        } else if (is_array($item)) {
            $obj->item = $item;
        }
        echo json_encode($obj);
        exit(0);

        return null;
    }
    public function errormessage($cont, $mess, $item = null)
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
        header("Content-Type:application/json");

        $obj = new stdClass();
        $obj->mess = $mess;
        $obj->cont = $cont;
        if ($item != null) {
            $obj->item = $item;
        }
        echo json_encode($obj);
        exit;
    }
    public function generatPassword($passLen)
    {
        $passChars = $this->passchar;
        $passArray = str_split($passChars);
        $newPassArray = array_rand($passArray, $passLen);
        $newPass = "";
        if ($passLen != 1) {
            for ($i = 0; $i < $passLen; $i++) {
                $newPass .= $passArray[$newPassArray[$i]];
            }
        } else {
            $newPass = $passArray[$newPassArray];
        }
        return $newPass;
    }
    /*
    public function sendNotification($conn,$string,$title,$type){
    global $prefix;
    $selectnotification = $conn->query("SELECT * FROM ".$prefix."notification WHERE id=1");
    $notificationrow = $selectnotification->fetchAll(PDO::FETCH_OBJ);
    $notificationid = ((int) $notificationrow[0]->notificationid)+1;
    $data = array( 'message' => $string,'title' => $title,'type' => $type,'notificationid' => $notificationid);
    $updatenotification = $conn->query("UPDATE ".$prefix."notification SET notificationid='$notificationid' WHERE id=1");
    $conn->sendGoogleCloudMessage($data,$conn->groupID,"group");
    }
     */

    /* ////////////////////////////////////// GET MYSQL EXECUTEQUERY ///////////////////////////////// */
    public function executeQuery($str)
    {
        try
        {
            $result = $this->db->query($str);
            return $result;
        } catch (PDOException $e) {
            header("HTTP/1.1 500 Internal Server Error");
            $this->message(false, "MYSQL ERROR " . $e->getMessage());
        } catch (Exception $e) {
            header("HTTP/1.1 500 Internal Server Error");
            $this->message(false, "PHP ERROR " . $e->getMessage());
        }
    }
    /* ////////////////////////////////////// GET MYSQL VALUES ///////////////////////////////// */
    public function getQueryValue($str)
    {
        try
        {
            $result = $this->executeQuery($str);
            $result_value = $result->fetchAll(PDO::FETCH_OBJ);
            return $result_value;
        } catch (PDOException $e) {
            header("HTTP/1.1 500 Internal Server Error");
            $this->message(false, "MYSQL ERROR " . $e->getMessage());
        } catch (Exception $e) {
            header("HTTP/1.1 500 Internal Server Error");
            $this->message(false, "PHP ERROR " . $e->getMessage());
        }
    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /* /////////////////////////////// VALIDATE FILE ////////////////////////////// */
    public function validateFile($obj)
    {
        try {

            if (is_object($obj)) {
                (!(isset($obj->filekey) && isset($obj->size) && isset($obj->type) && is_array($obj->type))) ? $this->errormessage(false, 'CODE ERROR') : null;
                (!(isset($_FILES[$obj->filekey]) && ($_FILES[$obj->filekey]["error"] == 0))) ? $this->errormessage(false, 'FILE NOT FOUND') : null;
                $maxsize = $obj->size * 1024 * 1024;
                ($maxsize < $_FILES[$obj->filekey]['size']) ? $this->errormessage(false, 'INVALID FILE SIZE') : null;
                $fileParts = pathinfo($_FILES[$obj->filekey]['name']);

                $fileext_arr = explode('?', $fileParts['extension']);

                (!@in_array(strtolower($fileext_arr[0]), $obj->type)) ? $this->errormessage(false, 'You can upload only ' . @implode(', ', $obj->type) . " file type.") : null;

            } else {
                $this->errormessage(false, 'validateFile fields missing');
            }
        } catch (Exception $e) {
            $this->errormessage(false, $e->getMessage());
        }
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* ////////////////////////////////////// UPLOAD FILE ///////////////////////////////// */
    public function uploadFile($obj)
    {
        $filekey = $obj->filekey;
        $path = $obj->path;
        $fileprefix = (isset($obj->fileprefix)) ? $obj->fileprefix : 'file';
        if (is_object($obj) && isset($_FILES[$obj->filekey])) {
            $tempFile = $_FILES[$obj->filekey]['tmp_name'];
            $fileParts = pathinfo($_FILES[$obj->filekey]['name']);

            $fileext_arr = explode('?', $fileParts['extension']);
            $fileExtension = strtolower($fileext_arr[0]);

            $file_prehead = (IS_LIVE_SERVER != '1') ? "_development" : "";
            $fileName = (isset($obj->filename)) ? $obj->filename . $file_prehead . '.' . $fileExtension : $fileprefix . '_' . date('YmdHis') . uniqid() . $file_prehead . '.' . $fileExtension;
            $targetFile = $path . $fileName;
            @move_uploaded_file($tempFile, $targetFile);
            //shell_exec("sudo chmod -R 777 ".$targetFile);
            chmod($targetFile, 0777);

            return $fileName;
        } else {
            $this->errormessage(false, 'FILE NOT FOUND');
        }
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// get ip ////////////////////////////// */
    public function getIp($data = array())
    {
        $ip = $_SERVER['REMOTE_ADDR'];
        if ($ip) {
            if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            }
            return $ip;
        }
        // There might not be any data
        return false;
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// get ip ////////////////////////////// */
    public function insertUserLog($conn, $activity)
    {
        if (isset($_SESSION["userid"])) {
            $client_ip = self::getIp($parent);

            $conn->executeQuery("INSERT INTO " . TABLE_USER_LOG . "( `userid`,`device_type`, `module`, `ip`, `created_on`) VALUES ('" . $_SESSION["userid"] . "','admin','" . $activity . "','" . $client_ip . "','" . NOW . "')");
        }
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// GET MONTH DATES ////////////////////////////// */
    public function getMonthDates($month, $year)
    {
        $month_str = date('Y-m', strtotime($year . "-" . $month . "-01"));
        $month_start = $month_str . "-01";
        $month_days = date('t', strtotime($month_start));

        $month_date = array();
        $day_arr = array();
        for ($i = 1; $i <= $month_days; $i++) {
            $date_str = date('Y-m-d', strtotime($year . "-" . $month . "-" . $i));
            $day_arr[] = ($i < 10) ? "0" . $i : (string) $i;
            $month_date[] = $date_str;
        }
        $month_last = $date_str;

        $data_arr = array('start' => $month_start, 'month' => $month_date, 'last' => $month_last, 'date' => $day_arr);
        return $data_arr;
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* ////////////////////////////////////// ANDRIOD GCM FUNCTION ///////////////////////////////// */
    private function sendGoogleCloudMessage($messagearr, $reg_id)
    {

        // print_r($reg_id);
        $title = $messagearr['title'];
        $message = $messagearr['message'];
        $messagearr['body'] = $messagearr['message'];

        $fields = array(
            'registration_ids' => $reg_id,
            'priority' => "high",
            'notification' => array("title" => $title, "body" => $message, "sound" => "default"),
            'data' => $messagearr,
        );

        $headers = array(
            GOOGLE_FCM_URL,
            'Content-Type: application/json',
            'Authorization: key=' . GOOGLE_API_KEY,
        );
        //echo "<br>";

        // $ch = curl_init();
        // curl_setopt($ch, CURLOPT_URL, GOOGLE_FCM_URL);
        // curl_setopt($ch, CURLOPT_POST, true);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        // $result = curl_exec($ch);
        //   echo $result;
        // curl_close($ch);
        echo $result="";
    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /* ////////////////////////////////////// IOS CLOUD MESSAGE FUNCTION ///////////////////////////////// */
    private function sendFCMIOSCloudMessage($messagearr, $reg_id)
    {

        // print_r($reg_id);
        $title = $messagearr['title'];
        $message = $messagearr['message'];

        $fields = array(
            //'to'=> $reg_id,
            "content_available" => true,
            'registration_ids' => $reg_id,
            'priority' => "high",
            'aps' => array("content-available" => 1),
            'notification' => $messagearr,
            // 'notification'              =>  $messagearr,
            'data' => array('published' => NOW),
            'notId' => rand(1000, 9999),
        );

        $headers = array(
            GOOGLE_FCM_URL,
            'Content-Type: application/json',
            'Authorization: key=' . GOOGLE_API_KEY,
        );
        //echo "<br>";

        // $ch = curl_init();
        // curl_setopt($ch, CURLOPT_URL, GOOGLE_FCM_URL);
        // curl_setopt($ch, CURLOPT_POST, true);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        // $result = curl_exec($ch);
        // echo $result;
        // curl_close($ch);
        echo $result="";
    }

    /* ////////////////////////////////////// SEND NOTIFICATION ///////////////////////////////// */
    public function sendUserNotification($message, $usertokenarr)
    {
        // print_r($message);
        // print_r($usertokenarr);

        //STRUCTURE $usertokenarr =array('android'=>$arr,'ios'=>$arr);
        // $android_ids = (isset($usertokenarr['android'])) ? $usertokenarr['android'] : array();
        // $ios_ids = (isset($usertokenarr['ios'])) ? $usertokenarr['ios'] : array();

        // if (count($android_ids) > 0) {
        //     $ids_arr = array_chunk($android_ids, 1000);
        //     if (count($ids_arr) > 0) {
        //         foreach ($ids_arr as $groupids) {
        //             $this->sendGoogleCloudMessage($message, $groupids);
        //         }
        //     }
        // }

        // if (count($ios_ids) > 0) {
        //     //echo "asdasd";
        //     $ids_arr = array_chunk($ios_ids, 1000);
        //     if (count($ids_arr) > 0) {
        //         foreach ($ids_arr as $groupids) {
        //             $this->sendFCMIOSCloudMessage($message, $groupids);
        //             //$this->sendIoCloudMessage($message,$groupids);
        //         }
        //     }

        // }

    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /* ////////////////////////////////////// USER ADD WALLET ///////////////////////////////// */
    public function userAddWallet($conn, $obj, $userid)
    {

        $user_str = "SELECT *  FROM  " . TABLE_USER . "  WHERE userid='" . $userid . "' AND is_deleted=0 LIMIT 1";
        $user_arr = $conn->getQueryValue($user_str);
        if (count($user_arr) > 0) {
            $smpin = $user_arr[0]->smpin;
        } else {
            echo $this->message(false, 'REQUIRED USER NOT FOUND');
        }

        if (!isset($obj->type)) {
            $this->message(false, 'REQUIRED REQUIRED obj->type');
        }

        if (!isset($obj->type_id)) {
            $this->message(false, 'REQUIRED REQUIRED obj->type_id');
        }

        if (!isset($obj->amount)) {
            $this->message(false, 'REQUIRED REQUIRED obj->amount');
        }

        $obj->description = (isset($obj->description)) ? $obj->description : "";

        //NEED TO CHECK AMOUNT ALREADY ADDED
        $amount_str = "SELECT *  FROM  " . TABLE_USER_WALLET_HISTORY . "  WHERE smpin='" . $smpin . "' AND type='" . $obj->type . "' AND type_id='" . $obj->type_id . "' AND transaction_type='C'";
        $amount_arr = $conn->getQueryValue($amount_str);
        if (count($amount_arr) > 0) {
            //AMOUNT ALREADY ADDED
        } else {
            $lvl_points = (isset($obj->lvl_points)) ? $obj->lvl_points : 0;
            $conn->executeQuery("INSERT INTO " . TABLE_USER_WALLET_HISTORY . "( `smpin`, `type`, `type_id`, `description`, `lvl_points`, `amount`, `transaction_type`, `created_on`, `modified_on`) VALUES ('" . $smpin . "','" . $obj->type . "','" . $obj->type_id . "','" . $obj->description . "','" . $lvl_points . "','" . $obj->amount . "' ,'C','" . NOW . "','" . NOW . "')");
            //UPDATE POINT IN USER
            $conn->executeQuery("UPDATE  " . TABLE_USER_WALLET . " SET amount=amount+" . $obj->amount . " WHERE smpin='" . $smpin . "' ");
        }

    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /* /////////////////////////////// USER ADD POINTS //////////////////////////////////////////////// */
    public function userAddPoints($obj, $userid = 0)
    {
        $user_str = "SELECT *  FROM  " . TABLE_USER . "  WHERE userid='" . $userid . "' AND is_deleted=0 LIMIT 1";
        $user_arr = $this->getQueryValue($user_str);
        if (count($user_arr) > 0) {
            $smpin = $user_arr[0]->smpin;
        } else {
            echo "userAddPoints USER NOT FOUND";exit;

        }

        if (!isset($obj->type)) {echo "userAddPoints obj->type MISSING";exit;}
        if (!isset($obj->type_id)) {echo "userAddPoints obj->type_id MISSING";exit;}
        if (!isset($obj->points)) {echo "userAddPoints obj->points MISSING";exit;}
        $obj->description = (isset($obj->description)) ? $obj->description : "";

        //NEED TO CHECK POINTS ALREADY ADDED
        $points_str = "SELECT *  FROM  " . TABLE_USER_EPOINTS_HISTORY . "  WHERE smpin='" . $smpin . "' AND type='" . $obj->type . "' AND type_id='" . $obj->type_id . "' AND transaction_type='C'";
        $points_arr = $this->getQueryValue($points_str);
        if (count($points_arr) > 0) {
            //POINTS ALREADY ADDED
        } else {
            $this->executeQuery("INSERT INTO " . TABLE_USER_EPOINTS_HISTORY . "( `smpin`, `type`, `type_id`, `description`, `points`, `transaction_type`, `created_on`, `modified_on`) VALUES ('" . $smpin . "','" . $obj->type . "','" . $obj->type_id . "','" . $obj->description . "','" . $obj->points . "' ,'C','" . NOW . "','" . NOW . "')");
            //UPDATE POINT IN USER
            $this->executeQuery("UPDATE  " . TABLE_USER_EPOINTS . " SET points=points+" . $obj->points . " WHERE smpin='" . $smpin . "' ");
        }

    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

}
