<?php

class SignupOrLoginAppleApi extends Api
{
    public $apiName = 'signuporloginapple';

    /*
curl -H "Content-Type: application/json" -H "Authorization: Server-Token 99dfe35fcb7de1ee" \
 https://svrsavvy.sworks.float.sg/SAVVY/oauth2/api/signuporloginapple/?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"];
                unset($result["password"]);
                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
     */
    /*    
{
 "oauth2_provider_id":2, 
 "authorization_code": "c707cc913cca04439953da4df234e0781.0.mss.2i20cbkfT2jO9G3yFl5_8Q",
 "identity_token": "eyJraWQiOiJlWGF1bm1MIiwiYWxnIjoiUlMyNTYifQ.eyJpc3Mi0iJodHRwczovL2FwcGxlaWQuYXBwbGUuY29tIiwiYXVkIjoic2cubXlmbG9hdC5mbG9hdGFwcCIsImV4cCI6MTU5MjQ4Nzg4MCwiaWF0IjoxNTkyNDg3MjgwLCJzdWIiOiIwMDAwMjIuNTUwOGQxMzU0OGUxNGIyOTk4YTFmNzVlZWNlZTRiZGYuMTYyOSIsImNfaGFzaCI6IkVUcTFqazdjbE9BQlRjdmF0OFZnQUEiLCJlbWFpbCI6In1hbm1rdXJrajdAcHJpdmF0ZXJlbGF5LmFwcGxlaWQuY29tIiwiZW1haWxfdmVyaWZpZWQiOiJ0cnVlIiwiaXNfcHJpdmF0ZV9lbWFpbCI6InRydWUiLCJhdXRoX3RpbWUiOjE1OTI0ODcyODAsIm5vbmNlX3N1cHBvcnRlZCI6dHJ1ZX0.DnptAwgs0kIsLv1LjxKZ8QetfutaDNqdHdDsPH5SG8xpzDEz798-NTBGLvcHpSHwBYLzm2W9G-VcSFRTOrjDcv1ZfzoYjwe107nTLzd5HOсEOTd-0gb3tn4xEjrdjiQxSyJKZqDUvfFO0g-x7sowzOtd3RRBIV7S0f1Cg5cX6qxJn-pSHh960oe18P8_IdykPnt-nuUZcqvsUr1tkN64SBJKCDPjZjOXJ_a0fBpOdw0BAviPiLEYtcHvtoCuSGWMBUWAueVXompo4FVVaQvp4diYFrI33H8j71t62uahgT_CKWBVeu1smBTIwANbdg-JRo8r7fr94JauPUvQh-2sZw",
 "user_id": "000022.5508d13548e14b2998a1f75eecee4bdf.1629",
 "email": "aciudmirae@mac.com",
 "name": "Anatolii Okhotnikov"
}

curl -d '{"oauth2_provider_id":2, "identity_token":"identity_token", "authorization_code":"authorization_code", "user_id": "000022.5508d13548e14b2998a1f75eecee4bdf.1629", "email":"", "name":"Anatolii Okhotnikov"}' \
-H "Content-Type: application/json" -H "Authorization: Server-Token 99dfe35fcb7de1ee" \
-X POST https://svrsavvy.sworks.float.sg/SAVVY/oauth2/api/signuporloginapple

curl -d '{"encrypted_payload": ""}' \
-H "Content-Type: application/json" -H "Authorization: Server-Token 99dfe35fcb7de1ee" \
-X POST https://svrsavvy.sworks.float.sg/SAVVY/oauth2/api/signuporloginapple
    */
    public function createAction()
    {
        error_log("SignupOrLoginAppleApi::createAction()");
        global $savvyext;
        $saveToken = true;
        $message = "";
        $member_id = 0;
        $oauth2_provider_id = (int)($this->requestParams["oauth2_provider_id"] ?? 0);
        $refresh_token = $this->requestParams["identity_token"] ?? "";
        $access_token = $this->requestParams["authorization_code"] ?? "";
        $user_id = $this->requestParams["user_id"] ?? "";
        $email = $this->requestParams["email"] ?? "";
        $name = $this->requestParams["name"] ?? "";
        /* $refresh_token!="" && */
        if ($refresh_token=="" || $oauth2_provider_id!=2 || $access_token=="" || $user_id=="" || $name=="") {
            $data = array();
            $data[] = $refresh_token=="";
            $data[] = $oauth2_provider_id<1;
            $data[] = $access_token=="";
            $data[] = $name=="";
            $data[] = !filter_var($email, FILTER_VALIDATE_EMAIL);
            error_log("SignupOrLoginAppleApi: Invalid OAuth2 data");
            return $this->response(
                array(
                    "debug" => $data,
                    "error" => "Invalid OAuth2 data"
                ), 500);
        }
        
        $db = new Db();

        // If we login the second time there will be no email
        if ($email=="" || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            // Get email base on the user id
            $email = OAuth2::getMemberEmailByUserId($db->getConnect(), $oauth2_provider_id, $user_id);
        }

        $member = OAuth2::getMemberByEmail($db->getConnect(), $email);
        if (isset($member["id"])) {
            error_log("SignupOrLoginAppleApi: 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("SignupOrLoginAppleApi: Create new user");
            list($firstname, $lastname) = SignupOrLoginAppleApi::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("SignupOrLoginAppleApi: Will save OAuth2 token!");
            $token = OAuth2::saveToken(
                $db->getConnect(), 
                $oauth2_provider_id,
                $member_id,
                $refresh_token,
                $access_token,
                $email,
                $name,
                $user_id
            );
        } else {
            error_log("SignupOrLoginAppleApi: 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);
    }
}
