<?php

class CasafariAPI {

    protected $clientURL;
    protected $clientSecret;

    function __construct($clientURL, $clientSecret) {
        $this->clientURL = $clientURL;
        $this->clientSecret = $clientSecret;
    }

    //********************** AUX FUNCTIONS **********************

    private function getResults($url, $params = []) {
        $paramarray = [];
        $paramurl = '';
        if(count($params)) foreach($params as $key => $val) $paramarray[] = $key.'='.$val;
        if(count($paramarray)) $paramurl = '?'.implode('&',$paramarray);
        $url .= $paramurl;
        $headers = $this->getHeaders();
        $postfields = [];
        $curl = $this->getRequest($url, $headers, json_encode($postfields));
        return $curl;
    }

    private function postResults($url, $params = []) {
        $headers = $this->getHeaders();
        $postfields = $params;
        $curl = $this->getRequest($url, $headers, json_encode($postfields), 'POST');
        return $curl;
    }

    private function putResults($url, $params = []) {
        $headers = $this->getHeaders();
        $postfields = $params;
        $curl = $this->getRequest($url, $headers, json_encode($postfields), 'PUT');
        return $curl;
    }

    private function getRequest($url, $headers = [], $postfields = [], $requesttype = 'GET') {
        //$headers = [];
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_CUSTOMREQUEST => $requesttype,
            CURLOPT_POST => count($postfields),
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_POSTFIELDS => $postfields
        ]);
        $resp = curl_exec($curl);
        $info = curl_getinfo($curl);
        $response = new stdClass();
        $response->response = json_decode($resp);
        $response->info = $info;
        //$response->headers = $headers;
        return $response;
    }

    private function getHeaders() {
        $headers = [
            'Content-Type: application/json',
            'Accept: application/json',
            'Authorization: Basic '.$this->clientSecret
        ];
        return $headers;
    }

    //********************** MAIN FUNCTIONS **********************

    function getLocations($params = []) {
        $url = $this->clientURL.'/api/Property/Location';
        return $this->postResults($url, $params)->response;
    }

    function getProperties($params = []) {
        $url = $this->clientURL.'/api/Property/ListProperties';
        return $this->postResults($url, $params)->response;
    }

    function getLeads($params = []) {
        $url = $this->clientURL.'/api/CodeTable';
        return $this->getResults($url)->response;
    }

    function postLead($params = []) {
        $url = $this->clientURL.'/api/Leads/Insert';
        return $this->postResults($url, $params)->response;
    }

}

?>