<?php

class Costreamv1Controller extends RController
{
    /**
     * @return array action filters
     */
    public function filters()
    {
            return array(
                'rights',
            );
    }

    protected function beforeAction($action)
    {
//        $actionToRun = $action->getId();
//
//// btdebug('beforeAction-START:'.$actionToRun);
//
//        if(in_array($actionToRun, ['authenticate','testapi','pagehit','resendfinalemails', 'livescoreadmin','getmatch2','matchsheet','testmatchnew','resetdata','getadsenseads'])) {
//            return true;
//        }
//
//        $noTokenReqd = in_array($actionToRun, [
//            'livescoreadmin',
//            'getmatch2',
//            'initdata',
//            'getmatchnew',
//            'checkteampassword',
//            'updatematchsheetdata',
//            'refreshmatchupdatesV2',
//            'refreshmatchscores'
//        ]);
//
////btdebug('checking auth for '.$actionToRun.' (CheckToken: '.($noTokenReqd ? 'false)' : 'true)'));
//
//        // check token validity
////        $this->_checkAuth();        // $noTokenReqd
//
////        p2l($this->token, 'token');
//
////        btdebug($this->token);
////        btdebug('tokenIsValid: ' . ($this->tokenIsValid ? 'true' : 'false'));
//        $this->lslog = new LivescoreLog($this->ignore);
//
//        $activityid = 0;
//        if(!$noTokenReqd) {
//
//            if($this->tokenIsValid) {
//                $activityid = $this->lslog->addActivity($this->token->payload->dev, $actionToRun, 0);
//            }
//            else {
//                if(isset($this->token->payload->dev)) {
//                    $activityid = $this->lslog->addActivity($this->token->payload->dev, $actionToRun, 2, $this->token->reason);
//                }
//                else {
//                    $activityid = $this->lslog->addActivity('none', $actionToRun, 2, $this->token->reason);
//                }
//            }
//
//            if($this->tokenIsValid === false ) {
//                $this->_sendResponse(401, CJSON::encode($this->token), $this->format);   //echo CJSON::encode(, $this->format);
//                app()->end();
//                return false;
//            }
//        }

        return parent::beforeAction($action);
//btdebug('beforeAction-END');
    }


    public function actionTestNowInTimezone() {
        $tz = $_POST['timezone'] ?? 'Australia/Melbourne';
        $tzdata = getNowInTimezone($tz);
        $data = [
            'timezone' => $tz,
            'tzone-time' => $tzdata,
            'tzone-today'=> $tzdata->format('Y-m-d'),
            'server-time' => date('Y-m-d H:i:s', time())
        ];
        echo CJSON::encode($data);
        app()->end();
    }
    
    public function actionTest()
    {
        $reqheaders = apache_request_headers();

        $publickey = $reqheaders['PUBLIC-KEY'] ?? null;

        $appid = $reqheaders['Origin'] ?? ($reqheaders['Referer'] ?? null);
        $appid = substr($appid,-1,1) == "/" ? substr($appid, 0, -1) : $appid;    //[strlen($appid)-1] == '/' substr($appid,0,-1) '' : '/';
        $pos = strrpos($appid, '/', -1);
        if($pos > 10) {
            $appid = substr($appid, 0, $pos);
        }

        $member = Restapiauth::model()->find('publickey=:pk', [':pk'=>$publickey]);
        $pcheck = 'auth failed - invalid pubkey';

        if($member) {
            $domains = explode(PHP_EOL, $member->domains);

            if(in_array($appid, $domains)) {
                $this->appids[$this->appid] = $appid;
                $this->memberorgid = $member->orgid;
                $validSource = true;
                $pcheck = 'auth success';
//                        btdebug($appid.' was validated');
            }
            else {
//                        btdebug($appid.' was NOT validated');
                $pcheck = 'auth failed - valid pubkey, invalid referrer';
            }

        }

        echo CJSON::encode([
            'data'=>'connected successfully',
            'pubkeycheck'=>$pcheck,
            'post'=>$_POST,
            'headers'=>$reqheaders,
            'server'=>$_SERVER
        ]);

        app()->end();
    }

    protected function getJsonData()
    {
        $json = file_get_contents('php://input');
        $obj = json_decode($json, true);
    
        return $obj;
    }
    
    public function actionCompsToday() 
    {
        try {

            $post = $this->getJsonData();
            
            // get timezone of user so we can get correct date for today
            $tz = $post['timezone'] ?? 'Australia/Melbourne';
            $orgid = $post['orgid'] ?? 0;
            
            $orgs = ['ALL_ACTIVE'];

            $drawlist = isset($post['matchids']) ? explode(',', $post['matchids']) : [];
            
            $mytoday = date('Y-m-d', time());

            // get list of matches being played today that have a status of scheduled
            $draws = null;
            if($orgid > 0) {
                $draws = Draw::model()->with('drawround.comp','drawround.comp.orgyear')->findAll('playdate=:dt AND matchstatus=:st AND orgyear.orgid=:oid AND comp.statusid=:st2', [':dt'=>$mytoday, ':st'=>1, ':oid'=>$orgid,':st2'=>1]);
            }
            else {
                $draws = Draw::model()->with('drawround.comp')->findAll('playdate=:dt AND matchstatus=:st AND comp.statusid=:st2', [':dt'=>$mytoday, ':st'=>1, ':st2'=>1]);
            }

            /*
                comps[compid]
                    fullname
                    org
                        code
                        name
                    matches[drawid]
                        rounddesc
                        matchformat
                        matchno
                        home/away
                            teamname
                            shortname
                            framescore
                            framepoints
            */ 
//echo count($draws).' draws.'.'<br>';         
            $data = [];
            if( count($drawlist) > 0) 
            {
//print_r($drawlist).'<br>';
                $matchislive = 0;
                foreach($draws as $draw) 
                {
//                    echo $draw->id.'<br>';

                    if(in_array($draw->id, $drawlist)) 
                    {
//                        print_r($draw);
                        // get the comp id
                        $comp = $draw->drawround->comp;
                        $lsdata = $comp->cso->livescoresettings;
                        $org = $comp->orgyear->org;
                        $dround = $draw->drawround;
                        
                        $mformat = null;
                        if($comp->isCompFormatTeams()) 
                        {
                            $gb = $comp->getgameblocklist();
                            $msid = $dround->msheetid;
                
                            $results = $gb->loadGameTotalsTeams($msid);
                
                            $mformat = $results['games'].($results['extra'] === 0 ? '' : ' + '.$results['extra']).' games';
                        }
                        else {
                            $mformat = getMatchFormatDesc($comp->gameblocklist, $dround->msheetid);
                        }

                        $hframescore = is_null($draw->remotematch) ? $draw->homeframescore : $draw->remotematch->homeframescore;
                        $hframepoints = is_null($draw->remotematch) ? $draw->homeframepoints : $draw->remotematch->homeframepoints;
                        
                        $aframescore = is_null($draw->remotematch) ? $draw->awayframescore : $draw->remotematch->awayframescore;
                        $aframepoints = is_null($draw->remotematch) ? $draw->awayframepoints : $draw->remotematch->awayframepoints;
                        
                        $matchislive += $this->matchislive($comp, $draw->remotematch);

                        // if($comp->isCompFormatTeams()) {
                        //     if($draw->remotematch->remotestatusid == 2 && $draw->remotematch->legendlock > 0) {
                        //         $matchislive++;
                        //     }
                        // }
                        // else {
                        //     if($draw->remotematch->remotestatusid == 1) {
                        //         $matchislive = 2;
                        //     }
                        // }
                        
// d2l(is_null($draw->remotematch) ? 'no livescore data': $draw->remotematch);

                        // add t ? 'he match info
                        $data[$draw->id] = [
                            'roundid' => $draw->drawroundid,
                            'matchformat' => $mformat,
                            'matchno' => $draw->gameno,
                            'matchtime' => LibComp::getStartTime( $comp->starttime, $dround->starttime, $draw->playtime ),
                            'hasmatchpoints' => intval($lsdata->hasmatchpoints),
                            'matchislive' => ($matchislive > 1 ? 1 : ($matchislive < 0 ? 2 : 0)),
                            'home' => [
                                'teamname' => $draw->hteam->teamlabel,
                                'shortname' => $draw->hteam->shortlabel,
                                'framescore' => intval($hframescore),
                                'framepoints' => intval($hframepoints)
                            ],
                            'away' => [
                                'teamname' => $draw->ateam->teamlabel,
                                'shortname' => $draw->ateam->shortlabel,
                                'framescore' => intval($draw->awayframescore),
                                'framepoints' => intval($draw->awayframepoints)
                            ]
                        ]; 
                    }
                }
            }
            else {
                foreach($draws as $draw) 
                {
                    // get the comp id
                    $comp = $draw->drawround->comp;
                    $org = $comp->orgyear->org;
                    $ok = false;

                    // store the comp info if new
                    $isorg = (in_array($org->orgcode, $orgs) || in_array('ALL_ACTIVE', $orgs));
                    
                    if( ! isset($data[$comp->id]) && $isorg) {   //  && in_array($org->orgcode, $orgs)
//                    if( ! isset($data[$comp->id]) ) {
                        $data[$comp->id] = [
                            'compname' => $comp->compnamefull,
        //                    'starttime' => $comp->starttime,
                            'org' => [ 'code' => $org->orgcode, 'name' => $org->orgname ],
                            'rounds' => [],
                            'matches' => []
                        ];
                        $ok = true;
                    }
                    elseif( isset($data[$comp->id]) && $isorg) {  //  && in_array($org->orgcode, $orgs)
                        $ok = true;
                    }
                    
                    if($ok) {
                        $dround = $draw->drawround;
                        
                        $mformat = getMatchFormatDesc($comp->gameblocklist, $dround->msheetid);
                        
                        // store the round info if new
                        if( ! isset($data[$comp->id]['rounds'][$draw->drawroundid]) ) {
                            $data[$comp->id]['rounds'][$draw->drawroundid] = [
                                // 'rdate' => $dround->compdate,
                                // 'rtime' => $dround->starttime,
                                'rounddesc' => LibComp::formatDrawroundLabel($dround, false)
                            ];
                        }

                        // init the remotematchstatus
                        $hlstatus = 0;
                        $alstatus = 0;
                        
                        $matchislive = 0;
                        if($comp->isCompFormatTeams()) 
                        {
                            // each team has its own remotematch record
                            if($draw->remotematches) {
                                foreach($draw->remotematches as $rm) {
                                    if($rm->hora == 'H') {
                                        $hlstatus = $rm->remotestatusid;
                                    }
                                    else {
                                        $alstatus = $rm->remotestatusid;
                                    }
                                }
                                $matchislive += $this->matchislive($comp, $draw->remotematch);
                                // if($draw->remotematch->remotestatusid == 2 && $draw->remotematch->legendlock > 0) {
                                //     $matchislive++;
                                // }
                            }
                        }
                        else {
                            // only one remotematch record
                            if($draw->remotematch) {
                                $hlstatus = $draw->remotematch->remotestatusid;
                                $alstatus = $draw->remotematch->remotestatusid;
                            }
                            $matchislive += $this->matchislive($comp, $draw->remotematch);
                            // if($draw->remotematch->remotestatusid == 1) {
                            //     $matchislive = 2;
                            // }
                        }
                        
                        $lsdata = $comp->cso->livescoresettings;

                        $hframescore = is_null($draw->remotematch) ? $draw->homeframescore : $draw->remotematch->homeframescore;
                        $hframepoints = is_null($draw->remotematch) ? $draw->homeframepoints : $draw->remotematch->homeframepoints;
                        
                        $aframescore = is_null($draw->remotematch) ? $draw->awayframescore : $draw->remotematch->awayframescore;
                        $aframepoints = is_null($draw->remotematch) ? $draw->awayframepoints : $draw->remotematch->awayframepoints;
                        
                        // add the match info
                        $data[$comp->id]['matches'][$draw->id] = [
                            'roundid' => $draw->drawroundid,
                            'matchformat' => $mformat,
                            'matchno' => $draw->gameno,
                            'matchtime' => LibComp::getStartTime( $comp->starttime, $dround->starttime, $draw->playtime ),
                            'hasmatchpoints' => intval($lsdata->hasmatchpoints),
                            'matchislive' => ($matchislive > 1 ? 1 : ($matchislive < 0 ? 2 : 0)),
                            'home' => [
                                'teamname' => $draw->hteam->teamlabel,
                                'shortname' => $draw->hteam->shortlabel,
                                'framescore' => intval($hframescore),
                                'framepoints' => intval($hframepoints),
                                'status' => $draw->hometeamstatus,
                                'livestatus' => $hlstatus                                 
                            ],
                            'away' => [
                                'teamname' => $draw->ateam->teamlabel,
                                'shortname' => $draw->ateam->shortlabel,
                                'framescore' => intval($aframescore),
                                'framepoints' => intval($aframepoints),
                                'status' => $draw->awayteamstatus,
                                'livestatus' => $alstatus 
                            ]
                        ];
                    }
                }
            }
            
            echo CJSON::encode($data);
        
        }
        catch (Exception $e) {
            echo $e->getMessage();
        }

        app()->end();
    }
    
    protected function matchislive($comp, $rem) {
        
        $matchislive = 0;
        
        try {
            if($comp->isCompFormatTeams()) {
                if($rem->remotestatusid == 2 && $rem->legendlock > 0) {
                    $matchislive++;
                    $matchislive = 1;
                }
                else {
                    if($rem->remotestatusid > 2) {
                        $matchislive = -10;
                    }
                }
            }
            else {
                if($rem->remotestatusid == 2) {
                    $matchislive = 2;
                }
                elseif($rem->remotestatusid > 2) {
                    $matchislive = -10;
                }
            }
            return $matchislive;
        }
        catch(Exception $e) {
            Yii::log('matchislive::'.$e->getMessage());
            return 0;
        }
    }

    public function actionOrganisation() 
    {
        $orgid = $_POST['orgid'] ?? 0;
        
        if($orgid == 0) {
            $sql = "SELECT id, orgname, stateabbr FROM organisation WHERE orgstatusid=1 ORDER BY orgname DESC";
            $cmd = db()->createCommand($sql);
            $orgs = $cmd->queryAll(true);
            $o = [];
            foreach($orgs as $org) {
               $o[$org['id']] = $org;
    //           p2l($org);
            }
            echo CJSON::encode($orgs);
        }
        app()->end();
    }

    public function actionLivescores()
    {
        $this->layout = "none";

echo CJSON::encode(['error'=>1]);

/*
        $api = $_GET['api'] ?? null;
        $key = $_GET['key'] ?? 'no-key';
        $cid = $_GET['cid'] ?? 0;
        $ids = $_GET['ids'] ?? null;
        $drid = $_GET['drid'] ?? null;

        $crit = new CDbCriteria();

        $comp = null;

        $mids = [];
        
        try {
            
            if( !( is_null($ids) && is_null($drid) ) )
            {
                $comp = Comp::model()->findByPk($cid);

                //if comp is teams format, use the code that draws data from VwActiveremotematch2
                if ($comp && $comp->isCompFormatTeams()) {

                    if (!is_null($drid)) {
                        $crit->addCondition('drid=' . $drid);
                    } else {
                        $dids = explode(',', $ids);
                        foreach ($dids as $idx => $did) {
                            $mids[$did]['idx'] = $idx;
                        }
                        $crit->addInCondition('drawid', $dids);
                    }

                    $draws = VwActiveremotematch2::model()->findAll($crit);

                    $origin = trim($_SERVER['HTTP_ORIGIN']) == '' ? 'OK' : $_SERVER['HTTP_ORIGIN'];

                    $origin .= substr($origin, strlen($origin) - 1) == '/' ? '' : '/';

                    $source_urls = [];

                    foreach ($draws as $draw) {
                        $ok = false;

                        $dround = Drawround::model()->findByPk($draw->drid);
                        $mformat = getMatchFormatDesc($comp->gameblocklist, $dround->msheetid);

                        // publickey, domains, statusid
                        if ($api == '1') {
                            // $org = Restapiauth::model()->find('orgid='.$draw->orgid);

                            // if( $org->publickey == $key )
                            // {
                            $source_urls = preg_split("/\r\n|\n|\r/", $org->domains);

                            if (in_array($origin, $source_urls)) {
                                $ok = true;
                            }
                            // else {
                            //     $mids = [];
                            //     $mids['error'] = ['errno'=>1,'desc'=>'API key not set or incorrect for this Organisation'];
                            //     break;
                            // }
                            // }
                            // else {
                            //     $mids[$draw->drawid]['error'] = ['errno'=>2,'desc'=>$origin.' not approved', 'uri'=>$source_urls];
                            // }
                        } else {
                            $ok = true;
                        }
                        
                        $mformat = getMatchFormatDesc($comp->gameblocklist, $dround->msheetid);

                        if ($draw->hora == 'H') {
                            $mids[$draw->drawid] = [
                                'compname' => $draw->compname,
                                'grade' => $draw->grade,
                                'matchformat' => $mformat,
                                'remotestatusid' => $draw->remotestatusid,
                                'hometeamlabel' => $draw->teamlabel,
                                'homeshortlabel' => $draw->shortlabel,
                                'awayteamlabel' => null,
                                'awayshortlabel' => null,
                                'homescore' => intval($draw->homeframescore + $draw->homeframescoreadj),
                                'homescorepoints' => intval($draw->homeframepoints),
                                'homeframepointsadj' => intval($draw->homeframepointsadj),
                                'awayscore' => intval($draw->awayframescore + $draw->awayframescoreadj),
                                'awayscorepoints' => intval($draw->awayframepoints),
                                'awayframepointsadj' => intval($draw->awayframepointsadj),
                                'venueabbr' => $draw->shortname,
                                'venuename' => $draw->venuename,
                                'timezone' => $draw->timezone
                            ];
                        } else {
                            $mids[$draw->drawid]['awayteamlabel'] = $draw->teamlabel;
                            $mids[$draw->drawid]['awayshortlabel'] = $draw->shortlabel;
                        }

                    }
                }
                else {
                    // comp is not a teams event and is livescoring is handled differently (/comp/rmu)

                    if (!is_null($drid)) {
                        $crit->addCondition('drawroundid=' . $drid);
                    } else {
                        $dids = explode(',', $ids);
                        foreach ($dids as $idx => $did) {
                            $mids[$did]['idx'] = $idx;
                        }
                        $crit->addInCondition('t.id', $dids);
                    }

                    $draws = Draw::model()->with('drawround', 'drawround.comp','hteam','ateam','venue','remotematch')->findAll($crit);

                    foreach($draws as $draw) 
                    {
                        $mformat = getMatchFormatDesc($draw->drawround->comp->gameblocklist, $draw->drawround->msheetid);
                        
                        if($draw->drawround->compid === $cid ) 
                        {
                            $mids[$draw->id] = [
                                'compname' => $draw->drawround->comp->compname,
                                'grade' => $draw->drawround->comp->grade,
                                'matchformat' => $mformat,
                                'remotestatusid' => $draw->remotematch->remotestatusid,
                                'hometeamlabel' => $draw->hteam->teamlabel,
                                'homeshortlabel' => $draw->hteam->shortlabel,
                                'awayteamlabel' => $draw->ateam->teamlabel,
                                'awayshortlabel' => $draw->ateam->teamlabel,
                                'homescore' => intval($draw->remotematch->homeframescore + $draw->remotematch->homeframescoreadj),
                                'homescorepoints' => intval($draw->remotematch->homeframepoints),
                                'homeframepointsadj' => intval($draw->remotematch->homeframepointsadj),
                                'awayscore' => intval($draw->remotematch->awayframescore + $draw->remotematch->awayframescoreadj),
                                'awayscorepoints' => intval($draw->remotematch->awayframepoints),
                                'awayframepointsadj' => intval($draw->remotematch->awayframepointsadj),
                                'venueabbr' => $draw->venue->shortname,
                                'venuename' => $draw->venue->venuename,
                                'timezone' => $draw->venue->timezone
                            ];
                        }
                        else {
                            $mids[$draw->id] = ['error'=>1, 'message'=>'drawid '.$draw->id.' does not belong to comp '.$cid];
                        }
                    }
                }

                if( $api == '1') {
    
                    // header('Access-Control-Allow-Origin: ' . ($_SERVER['HTTP_ORIGIN'] ?? "no-origin"));
                    header('Access-Control-Allow-Origin: https://scrbd.co-stream.live/');
                    
                    header( 'HTTP/1.1 200 OK');  
    
                    echo CJSON::encode($mids);
                    
                }
            }
            else {
                echo CJSON::encode(['error'=>1]);
            }
        }
        catch(Exception $e) {
            
            echo CJSON::encode(['error'=>$e->getMessage()]);
            
        }
*/        
        app()->end();
    }

/* COMMON FUNCTIONS */

    private function _sendResponse($status = 200, $body = '', $content_type = 'application/json')
    {
        $data = [];

        if(strpos($body, '"error":') !== false) {
            $data = CJSON::decode($body);
            if(isset($data['error'])) {
                $status = 401;
            }
        }

        if($status != 200) {
            if(isset($data['error'])) {
                foreach($data['error'] as $id => $err) {
//                    btdebug('Livescore Error. '.$status.' - '.$err['id'].' - '.$err['text']);
                    if(isset($err['errdata'])) {
//                        btdebug($err['errdata']);
                    }
                }
            }
        }

//        header('Access-Control-Allow-Origin: *');
//        header('Access-Control-Allow-Methods: GET, POST');
//        header("Access-Control-Allow-Headers: X-Requested-With");

        // set the status
        $status_header = 'HTTP/1.1 ' . $status . ' ' . $this->_getStatusCodeMessage($status);

        header('Access-Control-Allow-Origin: '.$this->appids[$this->appid]);
//        header('Access-Control-Allow-Origin: http://livescore.poolstat.net.au');

        header($status_header);

        // and the content type
        header('Content-type: ' . $content_type);

        // pages with body are easy
        if($body != '')
        {
            // send the body
            echo $body;
        }
        // we need to create the body if none is passed
        else
        {
            // create some body messages
            $message = array('Status'=>false);
            echo CJSON::encode($message);

            // servers don't always have a signature turned on
            // (this is an apache directive "ServerSignature On")
            $signature = isset($_SERVER['SERVER_SIGNATURE']) ?
                $_SERVER['SERVER_SIGNATURE'] :
                $_SERVER['SERVER_SOFTWARE'] . ' Server at ' . $_SERVER['SERVER_NAME'] . ' Port ' . $_SERVER['SERVER_PORT'];

            if(is_array($message)) {
                $message = print_r($message, true);
            }
            // this should be templated in a real-world solution
            //<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
            $body = '<!DOCTYPE HTML>
                <html>
                <head>
                    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
                    <title>' . $status . ' ' . $this->_getStatusCodeMessage($status) . '</title>
                </head>
                <body>
                    <h1>' . $this->_getStatusCodeMessage($status) . '</h1>
                    <p>' . $message . '</p>
                    <hr />
                    <address>' . $signature . '</address>
                </body>
                </html>';

            echo $body;
        }

        foreach (Yii::app()->log->routes as $route)
            if ($route instanceof CWebLogRoute)
                $route->enabled=false;

        app()->end();
    }

    private function _getStatusCodeMessage($status)
    {
        // these could be stored in a .ini file and loaded
        // via parse_ini_file()... however, this will suffice
        // for an example
        $codes = Array(
            200 => 'OK',
            400 => 'Bad Request',
            401 => 'Unauthorized',
            402 => 'Payment Required',
            403 => 'Forbidden',
            404 => 'Not Found',
            500 => 'Internal Server Error',
            501 => 'Not Implemented',
        );
        return (isset($codes[$status]) ? $codes[$status] : '');
    }

    private function _checkAuth()   // $noTokenReqd
    {
        $publickey = $_POST['publickey'] ?? null;

        $reqheaders = apache_request_headers();

        $validSource = false;

        $this->token = new TokenResponse(0, 'Headers are not valid', [
            'origin'=>$reqheaders['Origin'] ?? 'null',
            'referer'=>$reqheaders['Referer'] ?? 'null',
        ]);

        if(isset($reqheaders['Origin'])) {
            $validSource = strpos(($reqheaders['Origin'] ?? 'none'), $appid) !== false;
        }
        else {
            $validSource = strpos(($reqheaders['Referer'] ?? 'none'), $appid) !== false;
        }

        if(!$validSource) {
//btdebug($appid);
            if($appid === 'get-member-key') {
                $appid = $reqheaders['Origin'] ?? ($reqheaders['Referer'] ?? null);
                $appid = substr($appid,-1,1) == "/" ? substr($appid, 0, -1) : $appid;    //[strlen($appid)-1] == '/' substr($appid,0,-1) '' : '/';
                $pos = strrpos($appid, '/', -1);
                if($pos > 10) {
                    $appid = substr($appid, 0, $pos);
                }
//btdebug($appid);
//btdebug($publickey);
                $member = Restapiauth::model()->find('publickey=:pk', [':pk'=>$publickey]);
                if($member) {
                    $domains = explode(PHP_EOL, $member->domains);
//btdebug($appid.' '.$this->appid);
                    if(in_array($appid, $domains)) {
                        $this->appids[$this->appid] = $appid;
                        $this->memberorgid = $member->orgid;
                        $validSource = true;
//                        btdebug($appid.' was validated');
                    }
                    else {
//                        btdebug($appid.' was NOT validated');
                        throw new Exception('member parameters are not correct');
                    }
//btdebug($appid.' '.$this->appid);
                }
            }
        }


        $this->sessionid = 'none';
        if(isset($reqheaders['Cookie'])) {
            if (preg_match('/PHPSESSID=(.*?);/', $reqheaders['Cookie'], $cookie) == 1) {
                $this->sessionid = $cookie[1];
            }
        }

        // [Origin] => https://livescore.poolstat.net.au
        // or [Referer] => https://livescore.poolstat.net.au/
        //
        // [Cookie] => PHPSESSID=979uvp92e5f22r8n8s6ijfe0l7; sitevisitor=979uvp92e5f22r8n8s6ijfe0l7

        //use app_id to check origin

        // check the credentials
        if(!isset($this->appids[$this->appid])) {   // || $password != self::PASSWORD) {
            $data['error'][] = ['id'=>$this->appid, 'text'=> 'Access credentials provided but values are incorrect.'];
            $this->_sendResponse(401, CJSON::encode($data), $this->format);
        }

//        if($noTokenReqd === false)
//        {
        $this->token = new TokenResponse();

        $jwts = ['mytoken'=>self::LSTR_JWTTOKEN, 'othtoken'=>self::LSTR_JWTTOKENOTHER];

        // must be one or the other, cannot be both
        $jwtToken['mytoken'] = $_POST['mytoken'] ?? null;
        $jwtToken['othtoken'] = $_POST['othtoken'] ?? null;

        foreach($jwtToken as $key => $jwt)
        {
            // if a token header has been sent need to ensure all are valid
            if(!is_null($jwt)) {

                $jkey = $jwts[$key];

                // if tokens found, attempt to authenticate
                $this->token->authenticate($jwt);
                $this->tokenIsValid = ($this->token->tokenstatus === 1);
            }
        }
        $this->tokenIsValid = 1;
//        }
    }
}

class TokenResponse
{
    public $tokenstatus = 0;
    public $reason = 'Token Missing';
    public $payload = [];
    public $payloadraw;

    const JWT_SECRET = '83mS#JudyLJ*iTrg';

    function __construct($status = 0, $reason = 'Token Missing', $payload = [])
    {
        $this->tokenstatus = $status;
        $this->reason = $reason;
        $this->payload = $payload;
    }

    function create($payload)
    {
        $header = (object) ["alg"=>"HS256", "typ"=>"JWT"];

        // array object --> json string
        $headjson = CJSON::encode($header);
        $payljson = CJSON::encode($payload);

        // json string --> b64 encode
        $jwth = base64_encode($headjson);
        $jwtp = base64_encode($payljson);

        // encrypt b64 encoded string with secret key
        $secrethash = hash_hmac('sha256', "$jwth.$jwtp", self::JWT_SECRET);

        // make the token of header.payload.secret
        $token = "$jwth.$jwtp.$secrethash";

        return $token;
    }

    function extractpayload($token) {
        $parts = explode(".", $token);
        return $parts[1];
    }

    function authenticate($token)
    {
        $parts = explode(".", $token);

        // get the b64 encoded parts
        $jwth = $parts[0];
        $jwtp = $parts[1];
        $tokensecret = $parts[2];

        // calculate the secret to be checked
        $secrethash = hash_hmac('sha256', "$jwth.$jwtp", self::JWT_SECRET);

        // decode token parts to get json strings
//        $headjson = base64_decode($parts[0]);
        $payljson = base64_decode($parts[1]);

        $this->payloadraw = $parts[1];

        // convert json strings to array objects
//        $header = CJSON::decode($headjson, false);
        $payload = CJSON::decode($payljson, false);

        // check this secret string with the secret string from the token
        if(strcmp($secrethash, $tokensecret)==0) {

            if($payload->exp < time()) {
                $this->tokenstatus = 0;
                $this->reason = 'token has expired';
                $this->payload = $payload;
            }
            else {
                $this->tokenstatus = 1;
                $this->reason = 'token ok, expires in '.intval(($payload->exp - time())/60).' mins';
                $this->payload = $payload;
            }
        }
        else {
            $this->tokenstatus = 0;
            $this->reason = 'secret key does not match';
            $this->payload = $payload;
        }
    }
}

class TokenPayload
{
    public $dev;
    public $comp;
    public $draw;
    public $team;
    public $hora;
    public $auth;
    public $rem;
    public $tzd;
    public $iat;
    public $exp;

    function __construct($args)
    {
        foreach($args as $akey => $arg) {
            $this->$akey = $arg;
        }
    }

    public function attributes()
    {
        return (object) [
            'dev'=>$this->dev,
            'comp'=>$this->comp,
            'draw'=>$this->draw,
            'team'=>$this->team,
            'hora'=>$this->hora,
            'auth'=>$this->auth,
            'rem'=>$this->rem,
            'tzd'=>$this->tzd,
            'iat'=>$this->iat,
            'exp'=>$this->exp,
        ];
    }
}

class ActiveMatchDate
{
    public $status;
    public $isactive;
    public $activatetime;
    public $activatetimeshow;
    public $starttime;
    public $starttimeshow;
    public $starttimetime;
    public $deactivatetime;
    public $deactivatetimeshow;
    public $nowtime;
    public $nowtimeshow;
    public $playdate;
    public $playtime;
}
