<?php

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/PHPClass.php to edit this template
 */

/**
 * Description of SsoHelper
 * @property MasPortal $portalmodel
 * @property Array $errorArray
 * @property bool $hasError
 * @author Manu
 */
class SsoHelper {

    const TOKEN_ENDPOINT = "index.php?r=ssignon/ssoauth/issuetoken";
    const LOGIN_ENDPOINT = "index.php?r=ssignon/ssoauth/sslogin";

    private $pimaryUsernameIdentity;
    private $portalmodel;
    private $portaId;
    private $identityField;
    private $token;
    private $errorArray = [];
    private $hasError = false;

    public function __construct($pimaryUsernameIdentity, $portaId, $identityField) {
        $this->portaId = $portaId;
        $this->pimaryUsernameIdentity = $pimaryUsernameIdentity;
        $this->identityField = $identityField;
    }

    private function init() {
        $this->clearError();
        $this->portalmodel = MasPortal::model()->findByPk($this->portaId);
        if (empty($this->portalmodel)) {
            $this->addError("portal", "Invalid portal.");
        } elseif ($this->portalmodel->isActive != "Y") {
            $this->addError("portal", "Portal is disabled.");
        } else {

        }
    }

    private function clearError() {
        $this->hasError = false;
        $this->errorArray = [];
    }

    private function addError($attribute, $errorMessage) {
        $this->hasError = true;
        $this->errorArray[strtolower(trim($attribute))][] = $errorMessage;
    }

    public function getToken() {
        $endPoint = "index.php?r=ssoauth/issuetoken";
        $this->init();
        $returnArray = [];
        if ($this->hasError) {
            return [
                "status" => "error",
                "error" => $this->errorArray
            ];
        }
        if (!$this->hasError) {

            $paramData = [
                "emp_id" => $this->pimaryUsernameIdentity,
                "username" => $this->pimaryUsernameIdentity,
                "identity_field" => $this->identityField,
                "token" => $this->token
            ];
//            print_r($paramData);
            $url = $this->portalmodel->return_url . SsoHelper::TOKEN_ENDPOINT;
//            echo $url;
//            die();
            $apiResult = $this->apiHelper($url, $paramData);
//            print_r($apiResult);
//            die();
            return $apiResult;
        }
    }

    private function apiHelper($url, $data) {
        // Initialize cURL session
//        echo $url;
        $ch = curl_init($url);
        // Set cURL options
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); // Encode data as query string
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return response as a string instead of outputting
        // Execute cURL request
        $response = curl_exec($ch);

        // Check for errors
        $statusArray = [];
        if ($response === false) {
            $statusArray = ["status" => "error"];
        } else {
            $dataArray = json_decode($response, true);
            $statusArray = ["status" => "success", "data" => $dataArray];
        }
        // Close cURL session
        curl_close($ch);
        return $statusArray;
    }

    public function isUserExist($portalId, $userId) {

    }

}
