<?php

class BankloginApi extends Api
{
    public $apiName = 'banklogin';

    public function indexAction()
    {
        return $this->response(
            array(
                "error" => "Data not found"
            ), 400);
    }

    /**
     * Method GET
     * Get single record (by id)
     * http://DOMAIN/geocode/1
     * @return string
     */
    public function viewAction()
    {
        return $this->response(
            array(
                'error'=> 'Data not found'
            ), 404);
    }

    public function createAction()
    {
        global $savvyext;
        $path = $this->requestParams['path'];
        $method = $this->requestParams['method'];
        $authToken = $this->requestParams['auth_token'] ?? "";
        $data = $this->requestParams['data'] ?? array();

        $url = $savvyext->cfgReadChar('microservices.account') . "/api/v1/" . rtrim($path, '/') . '/';

        $opts = array(
            'http' => array(
                'method' => $method,
                'protocol_version' => 1.1,
                'header'  => 
                    "Accept: application/json\r\n"
            ),
      	    "ssl" => array(
        	"verify_peer"=>false,
        	"verify_peer_name"=>false,
            )
        );

        if(!empty($authToken)){
            $opts['http']['header'] .=  "Authorization: Token ${authToken}\r\n";
        }

        if($method == 'GET') {
            if(is_array($data)) {
                $data = "?" . http_build_query($data);
            }

            $url .= $data;
            $opts['http']['header'] .= "Content-Type: application/x-www-form-urlencoded\r\n";
        } 
        else {
            $opts['http']['content'] = json_encode($data);
            $opts['http']['header'] .= "Content-Type: application/json\r\nConnection: close\r\n";
            $opts['http']['header'] .= "Content-length: " . strlen($opts['http']['content']);
        }

        $context = stream_context_create($opts);

        try {
            $body = file_get_contents($url, false, $context);
            $result = json_decode($body,true);

            return $this->response(
                array(
                    'data'=>$result,
                    'options'=>""), 200);
        } catch (Exception $e) {
            error_log(json_encode($e));
            $message = $e->getMessage();
        }
        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);
    }

}
