<?php

class SignupOrLoginGoogleApi extends Api
{
    public $apiName = 'signuporlogingoogle';

    /*
curl -H "Content-Type: application/json" -H "Authorization: Server-Token 99dfe35fcb7de1ee" \
 https://svrsavvy.sworks.float.sg/SAVVY/oauth2/api/signuporlogingoogle/?email=savvy@chiefsoft.com
    */
    public function indexAction()
    {
        $email = $this->requestParams["email"] ?? 0;
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $db = new Db();
            $result = OAuth2::getMemberByEmail($db->getConnect(), $email);
            if (isset($result["id"])) {
                $result["member_id"] = $result["id"];
                return $this->response($result, 200);
            } else {
                return $this->response(
                    array(
                        'error' => 'Account is not found'
                    ), 500);
            }
        }
        return $this->response(
            array(
                'error' => 'Invalid e-mail'
            ), 500);
    }

    /**
     * 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, "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/signuporlogingoogle

curl -d '{"encrypted_payload": ""}' \
-H "Content-Type: application/json" -H "Authorization: Server-Token 99dfe35fcb7de1ee" \
-X POST https://svrsavvy.sworks.float.sg/SAVVY/oauth2/api/signuporlogingoogle
    */
    public function createAction()
    {
        error_log("SignupOrLoginGoogleApi::createAction()");
        global $savvyext;
        $saveToken = true;
        $message = "";
        $member_id = 0;
        $oauth2_provider_id = (int)($this->requestParams["oauth2_provider_id"] ?? 0);
        $refresh_token = $this->requestParams["refresh_token"] ?? "";
        $access_token = $this->requestParams["access_token"] ?? "";
        $email = $this->requestParams["email"] ?? "";
        $name = $this->requestParams["name"] ?? "";
        /* $refresh_token!="" && */
        if ($refresh_token=="" || $oauth2_provider_id<1 || $access_token=="" || $name==""
                || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $data = array();
            $data[] = $refresh_token=="";
            $data[] = $oauth2_provider_id<1;
            $data[] = $access_token=="";
            $data[] = $name=="";
            $data[] = !filter_var($email, FILTER_VALIDATE_EMAIL);
            error_log("SignupOrLoginGoogleApi: Invalid OAuth2 data");
            return $this->response(
                array(
                    "debug" => $data,
                    "error" => "Invalid OAuth2 data"
                ), 500);
        }
        
        $db = new Db();
        $member = OAuth2::getMemberByEmail($db->getConnect(), $email);
        if (isset($member["id"])) {
            error_log("SignupOrLoginGoogleApi: User found");
            // User found
            $member_id = $member["id"];
            // We must create session and populate all fields properly
            $in = array (
                "action" => SAVVY_USER_LOGINACCOUNT,
                "loc" => $_SERVER["REMOTE_ADDR"],
                "pid" => 100,
                "username" => $member["username"], /* Could be different from e-mail connected? */
                "impersonate" => 1 /* we willbypass password check - we do not know the password! */
            );
            $member = $savvyext->savvyext_api($in);
            // Do we save a new token?
            $saveToken = true; //false;
        } else {
            error_log("SignupOrLoginGoogleApi: Create new user");
            list($firstname, $lastname) = SignupOrLoginGoogleApi::splitName($name);
            // Create new user
            $in = array(
                "action" => SAVVY_USER_CREATEACCOUNT,
                "loc" => $_SERVER["REMOTE_ADDR"],
                "pid" => 100,
                "web" => 120012, /* MVP_DIRECT_CALL */
                "start_mode" => 1,
                "username" => $email,
                "password" => "savvy",
                "email" => $email,
                "firstname" => $firstname,
                "lastname" => $lastname,
                "phone" => ""
            );
            $member = $savvyext->savvyext_api($in);
            if (isset($member["member_id"]) && $member["member_id"]>0) {
                //User created!
                $member_id = $member["member_id"];
                $surveyData = $this->requestParams["signUpSurveyData"] ?? [];
                Oauth2::saveMembersSurvey($db->getConnect(), $surveyData, $member);
            } else {
                return $this->response(
                    array(
                        "error" => "Failed to register new user"
                    ), 500);
            }
            $saveToken = true; // New user & new token?
        }
        // Save token
        $token = array();
        if ($saveToken) {
            error_log("SignupOrLoginGoogleApi: Will save OAuth2 token!");
            $token = OAuth2::saveToken(
                $db->getConnect(), 
                $oauth2_provider_id,
                $member_id,
                $refresh_token,
                $access_token,
                $email,
                $name);
            if ($token && $token["id"]>0) {
                error_log("SignupOrLoginGoogleApi: token saved! id=".$token["id"]);
                list($html, $result) = PullApi::callPullService($member_id, $token["id"]);
                if (is_array($result)) {
                    if (isset($result["id"])) {
                        $result["token"] = $token;
                        $result["member"] = $member;
                        $result["member_id"] = $member_id;
                        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";
                    error_log("SignupOrLoginGoogleApi: ".$message);
                }
            } else {
                $message = "Failed to save OAuth2 token";
                error_log("SignupOrLoginGoogleApi: ".$message);
            }
        } else {
            error_log("SignupOrLoginGoogleApi: get latest token");
            // Do we get any token for the existing user?
            $token = OAuth2::getLatestToken($db->getConnect(), $member_id, $oauth2_provider_id);
        }
        return $this->response(
            array(
                "error" => $message,
                "token" => $token,
                "member" => $member,
                "member_id" => $member_id
            ), 200);
    }

    private function splitName($name) {
        $my_name = trim($name);
        $firstname = " ";
        $lastname = " ";
        $pos = strpos(trim($my_name), " ");
        if ($pos!==false) {
            $firstname = trim(substr($my_name, 0, $pos));
            $lastname = trim(substr($my_name, $pos));
        } else {
            $firstname = $my_name ?? " ";
        }
        if ($firstname=="") $firstname = " ";
        if ($lastname=="") $lastname = " ";
        return array($firstname, $lastname);
    }

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

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