<?php

class PullApi extends Api
{
    public $apiName = 'pull';

    /*
curl -H "Content-Type: application/json" -H "Authorization: Server-Token 99dfe35fcb7de1ee" \
 https://svrsavvy.sworks.float.sg/SAVVY/oauth2/api/pull/?member_id=22&oauth2_token_id=153
    */
    public function indexAction()
    {
        $member_id = $this->requestParams["member_id"] ?? 0;
        $oauth2_token_id = $this->requestParams["oauth2_token_id"] ?? 0;
        if ($oauth2_token_id<1 || $member_id<1) {
            return $this->response(
                array(
                    "error" => "Invalid request"
                ), 500);
        }
        list ($html, $result) = PullApi::callPullService($member_id, $oauth2_token_id);
        if (is_array($result)) {
            if (isset($result["id"])) {
                return $this->response($result, 200);
            } else if (isset($result["message"])) {
                return $this->response(
                    array(
                        'error' => $result["message"]
                    ), 500);
            }
        }
        return $this->response(
            array(
                'error' => 'Failed to call service'
            ), 500);
    }

    public function callPullService($member_id, $oauth2_token_id) {
        global $savvyext;
        $httpAuthToken = $savvyext->cfgReadChar('system.oauth2_token');
        $oauth2_url = $savvyext->cfgReadChar('system.oauth2_url');
        $data = http_build_query(
            array(
                'member_id' => $member_id,
                'oauth2_token_id' => $oauth2_token_id
            )
        );
        $url = $oauth2_url."pull?" . $data;
        $opts = array(
            'http' => array(
                'header'  =>
                    "Accept: application/json\r\n" .
                    "Authorization: Server-Token ${httpAuthToken}\r\n"
            ),
      	    "ssl" => array(
        	"verify_peer"=>false,
        	"verify_peer_name"=>false,
      	    )
        );
        $context = stream_context_create($opts);
        $body = file_get_contents($url, false, $context);
        return array($body, json_decode($body,true));
    }

    /**
     * Method GET
     * Get single record (by id)
     * http://DOMAIN/pull/?member_id=22&oauth2_token_id=153
     * @return string
     */
    public function viewAction()
    {
        //id must be the first parameter after /trips/x
        /*
        $id = array_shift($this->requestUri);

        if($id && (int)$id>0){
            $db = new Db();
            $tripOptions = Trips::getOptionsById($db->getConnect(), (int)$id);
            if(is_array($tripOptions) && count($tripOptions)>0){
                return $this->response(
                    array(
                        'id' => $id,
                        'count' => count($tripOptions),
                        'options' => $tripOptions
                    ), 200);
            }
        }*/
        return $this->response(
            array(
                'error'=> 'Data not found'
            ), 404);
    }

    /**
     * Method POST
     * Create new record
     * http://DOMAIN/pull + request parameters name, email
     * @return string
     */
    /*    
curl -d '{"oauth2_provider_id":1, "member_id":7, "refresh_token":"refresh", "access_token":"access", "email":"acidumirae@gmail.com", "name":"Anatolii Okhotnikov"}' \
-H "Content-Type: application/json" -H "Authorization: Server-Token 99dfe35fcb7de1ee" \
-X POST https://svrsavvy.sworks.float.sg/SAVVY/oauth2/api/pull

curl -d '{"encrypted_payload": "ba16ece8fc1131ab0ecd5f0136d60d2508e982bc289b117e54b2f8f86c6e56c512ad9644b0e1655a27e8e1cd60cb39a5c3c47ae1adb83bbb65e6ab71dc4fc31233b936340b2572a0e6372de56358342d1a8e414c15e38b404c1a37e5b71f21a45ad9bf487e2830d699454ed4fddc9e8f5296771abc3c3eca5768f5184dbf056d0e50d6f0fbd5a0ad"}' \
-H "Content-Type: application/json" -H "Authorization: Server-Token 99dfe35fcb7de1ee" \
-X POST https://svrsavvy.sworks.float.sg/SAVVY/oauth2/api/pull
    */
    public function createAction()
    {
        $message = "Invalid request";
        $oauth2_provider_id = $this->requestParams["oauth2_provider_id"] ?? 0;
        $member_id = $this->requestParams["member_id"] ?? 0;
        $refresh_token = $this->requestParams["refresh_token"] ?? "";
        $access_token = $this->requestParams["access_token"] ?? "";
        $email = $this->requestParams["email"] ?? 0;
        $name = $this->requestParams["name"] ?? "";
        /* $refresh_token!="" && */
        if ($refresh_token!="" && $oauth2_provider_id>0 && $member_id>0 && $access_token!="" && $name!=""
                && filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $db = new Db();
            $token = OAuth2::saveToken(
                $db->getConnect(), 
                $oauth2_provider_id,
                $member_id,
                $refresh_token,
                $access_token,
                $email,
                $name);
            if ($token && $token["id"]>0) {
                list($html, $result) = PullApi::callPullService($member_id, $token["id"]);
                if (is_array($result)) {
                    if (isset($result["id"])) {
                        $result["token"] = $token;
                        return $this->response($result, 200);
                    } else if (isset($result["message"])) {
                        $message = $result["message"];
                    } else if (isset($result["error"])) {
                        $message = $result["error"];
                    } else {
                        $message = $html;
                    }
                } else {
                    $message = "Failed to call pull service";
                }
            } else {
                $message = "Failed to save OAuth2 token";
            }
        }
        return $this->response(
            array(
                "error" => $message
            ), 500);
    }

    public function updateAction()
    {
        return $this->response(
            array(
                "error" => "Update error"
            ), 400);
    }

    public function deleteAction()
    {
        return $this->response(
            array(
                "error" => "Delete error"
            ), 500);
    }
}
