<?php

/*
 * awframework from aw.inc present aw controller
 * it will help you develop easy and fast with secure tools
 * you can edit and add what you feel right
 * don't change in strucure of file
 */

require_once("imp/_imp.php");

class Controllers {

    //public vars
    public $smarty;
    public $hosturl;
    public $controllname;
    public $shcontrollname;
    public $tableName;
    public $active;
    private $cards_arr;

    // it will run in everytime with
    // default requried
    public function __construct() {
        require_once("../public/aw_config.php");
        require_once("imp/_autho.php"); //general functions
        $this->smarty = $smarty;
        $this->hosturl = $hosturl;
        $this->cards_arr = array();

        //here name of controll to known
        $this->controllname = 'notification';
        $this->shcontrollname = 'الإشعارات';
        $this->tableName = 'notification';
        $this->smarty->assign('controllname', $this->controllname);
        $this->smarty->assign('shcontrollname', $this->shcontrollname);

        //breadcrumbs
        require_once("../../library/plugins/Breadcrumbs/Breadcrumbs_ar.php");
        $acty = filter_input(INPUT_GET, 'ac');
        $bc = new breadcrumbs($hosturl, $this->controllname, $this->shcontrollname, $acty);
        $bc->crumbs();
        $breadcrumbs = $bc->breadcrumbs;
        $smarty->assign('breadcrumbs', $breadcrumbs);

        # here show the active page in menu
        // array called active[] with level of active element
        $active[0] = 'notification'; //controller name or tab name
        $active[1] = 'notification'; //controller name
        $this->active = $active;


        #include upload function
        require_once("../../library/plugins/classupload/uploadfunctions.php");
        //here will call all php pages
        require_once("_header.php");
        require_once("_sidebar.php");
        require_once("_leftsidebar.php");
        require_once("_footer.php");
    }

    //here the frist page and
    //the frist action in this class
    public function index() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('notification/add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function addit() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //vars here
        $title = filter_input(INPUT_POST, 'title');
        $content = filter_input(INPUT_POST, 'content');
        $date = filter_input(INPUT_POST, 'date');
        
        $content = $this->removeHtmlTag($content);
       
        //here the add
        $notification = R::dispense('notification');
        $notification->title = $title;
        $notification->content = $content ;
        $notification->date = $date;

        try {
            $id = R::store($notification);
            //$newContent = (strlen($content) > 13) ? substr($content,0,80).'...' : $content;
            $this->sendPush($title , $content);
             
           header('Location:' . $this->hosturl . '/' . $this->controllname . '/show');
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/error/notadd/' . $this->controllname);
        }
    }

    public function show() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //here will load the menu show
        $notification = R::findAll('notification', 'order by id desc');
        $this->smarty->assign('returnedData', $notification);
        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('notification/show.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function edit() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $notification = R::findAll('notification', 'order by id desc');
        $this->smarty->assign('notification', $notification);
        //get id for item
        $itemid = filter_input(INPUT_GET, 'id');
        //load all here
        $one_notification = R::load('notification', $itemid);
        $this->smarty->assign('returnedData', $one_notification);


        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('notification/edit.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function updateit() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        //vars here
        $title = filter_input(INPUT_POST, 'title');
        $content = filter_input(INPUT_POST, 'content');
        $date = filter_input(INPUT_POST, 'date');

        $id = filter_input(INPUT_POST, 'id');
        //R::debug( TRUE );
        //load all parents here
        $notification = R::load('notification', $id);

        $content = $this->removeHtmlTag($content);
         // $newContent = (strlen($content) > 13) ? substr($content,0,80).'...' : $content;
        //here the upadte
        $notification->title = $title;
        $notification->content = $content;
        $notification->date = $date;

        try {
            R::store($notification);
            
            
           $this->sendPush($title , $content);
          
            
            header('Location:' . $this->hosturl . '/' . $this->controllname . '/show');
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

    public function del() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //get id for item
        $itemid = filter_input(INPUT_GET, 'id');
        //load all item here
        $notification = R::load('notification', $itemid);

        try {
            R::trash($notification);
            header('Location:' . $this->hosturl . '/' . $this->controllname . '/show');
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/error/notdel/' . $this->controllname);
        }
    }
    

    public function deleteselected() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //get id for item
        $deleteidsString = $_POST['deleteids'];
        $deleteidsArray = explode(',', $deleteidsString);
        foreach ($deleteidsArray as $id) {
            $notification = R::load('notification', $id);
            R::trash($notification);
        }
        echo 1;
    }
    
    public function removeHtmlTag($text){
            $text = preg_replace('/</','<',$text);
            $text = preg_replace('/>/','>',$text);
            $desc = html_entity_decode(strip_tags($text));
            $desc = preg_replace('/[\r\t]/',' ',$desc);
            $desc = preg_replace('//',' ',$desc); 
            $text = preg_replace('/\r/',' ',$text); 
            $content = strip_tags($text); 
            return $content;
    }
    
   public function sendPush($title , $content ){
        $sQuery = "SELECT * FROM deviceids";
        $dSliderData = R::getAll($sQuery);
    
        foreach ($dSliderData as $val) {
            $devid = $val['devid'];
            if( $devid != '' ){
                $head = $title ;
                $msg =$content ;
                                
                $this->init_push('','',$devid, $head , $msg);
            }
        }
    }
    
   public function init_push($page_name , $load_id , $user_device_id, $head , $msg) {
        $msg = $msg;
        $head = $head;
        $content = array("en" => $msg);
        $headings = array("en" => $head);
        $fields = array(
            'android_sound' => "default",
            "sound" => "default",
            'app_id' => '0bbd1ecf-89d2-4dae-8b5e-008a5f8a7089', //# [Keys & IDS] ONESIGNAL APP ID from onesignal site.
            //'include_player_ids' => array('5f09ff33-7102-4f63-9699-9d589a445a62'),
            'include_player_ids' => array($user_device_id),
            //# user id which sent from Appicaition .
            'data' => array(
                "foo" => "bar" ,
                "page_name" => $page_name ,
                "load_id"  => $load_id ,
                "sound" => "default",
                "android_sound" => "default"
            ),
            'contents' => $content,
            'headings' => $headings,
            'large_icon' => 'https://bus.gt4host.com/onesignal_icon.png',
            //'big_picture' => 'https://cdn4.iconfinder.com/data/icons/iconsimple-logotypes/512/github-512.png'
        );
    
        $fields = json_encode($fields);
        $restKey = 'MjQ5N2ZjOGItOTVhNS00YjBmLTliMWItMjBkNWQ5MWNmMDll'; //# [Keys & IDS] REST API KEY from onesignal site.
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
            'Authorization: Basic ' . $restKey));
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
    
        //curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
    
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    
        $result = curl_exec($ch);
        curl_close($ch);
        //print_r($result);
        //return $result;
    }


    // at the end of class call
    public function __destruct() {
        //colse connection
        R::close();
    }

}
