<?php

    class Zopim {

        private $server_url = 'https://www.zopim.com';
        private $authenticate = '/plugins/login';
        private $details = '/plugins/getAccountDetails';

        private function postData($route, $data) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $this->server_url.$route);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('User-Agent: Zendesk Chat Wordpress Plugin'));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
			$output = curl_exec($ch);
			curl_close($ch);
            return $output;
        }

        private function getAccountKey($salt) {
            $request = $this->postData($this->details, array(
                'salt' => $salt
            ));
            $response = json_decode($request);
            if(isset($response->account_key)) {
                return $response->account_key;
            }
            return false;
        }

        private function getSalt($email, $password) {
            $request = $this->postData($this->authenticate, array(
                'email' => $email,
                'password' => $password
            ));
            $response = json_decode($request);
            if(isset($response->salt)) {
                return $response->salt;
            }
            return false;
        }

        public static function getCode($email, $password) {
            $sdk = new self();
            $salt = $sdk->getSalt($email, $password);
            if($salt != false) {
                $account_key = $sdk->getAccountKey($salt);
                if($account_key != false) {
                    return $account_key;
                }
            }
            return false;
        }

    }