<?php

class FluentCRMSimpleClient extends SimpleWebClient\Client {
   
    public function __construct() {
        $this->load_settings();
    }

    public function complete_auth(
        $fluentCRM_url,
        $fluentCRM_username,
        $fluentCRM_password
    ) {
        $this->settings->fluentCRM_url = $fluentCRM_url;
        $this->settings->fluentCRM_username = $fluentCRM_username;
        $this->settings->fluentCRM_password = $fluentCRM_password;
        
        $isConnected = $this->healthCheck();
        if($isConnected) {
            $this->settings->status = 'connected';
        }
        else {
            $this->settings->status = 'pending';
        }

        $this->save_settings();
    }

    public function check_access(
        $fluentCRM_url,
        $fluentCRM_username,
        $fluentCRM_password
    ) {
        $this->settings->fluentCRM_url = $fluentCRM_url;
        $this->settings->fluentCRM_username = $fluentCRM_username;
        $this->settings->fluentCRM_password = $fluentCRM_password;
        
        $isConnected = $this->healthCheck();
        return $isConnected;
    }

    public function load_settings() {
        $this->settings = get_option('_wswebinar_fluentCRM');

        if ($this->settings == false) {
            $this->settings = (object)[];
        }
    }

    public function save_settings() {
        update_option('_wswebinar_fluentCRM', $this->settings);
    }

    public function is_connected() {
        return $this->settings != null
            && isset($this->settings->status)
            && $this->settings->status == 'connected';
    }

    public function disconnect() {
        $this->settings->status = 'disconnected';
        $this->save_settings();
    }

    protected function makeApiRequest($endpoint, $method = 'GET', $data = []) {
        $url = $this->settings->fluentCRM_url.'/wp-json/fluent-crm/v2'.$endpoint;
        $args = [
            'method'  => $method,
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode($this->settings->fluentCRM_username.':'.$this->settings->fluentCRM_password),
                'Content-Type'  => 'application/json',
            ],
            'body'    => wp_json_encode($data),
            'sslverify' => false,
        ];

        // Only set the body if data is being sent
        if ($method === 'GET' || empty($data)) {
            unset($args['body']);
        }

        $response = wp_remote_request($url, $args);
        if (is_wp_error($response)) {
            return $response;
        }

        $statusCode = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $decodedBody = json_decode($body, true);

        return $decodedBody;
    }

    // CRUD operations for Subscribers

    public function createSubscriber($data) {
        return $this->makeApiRequest('/subscribers', 'POST', $data);
    }

    public function getSubscriber($id) {
        return $this->makeApiRequest('/subscribers/' . $id, 'GET');
    }

    public function updateSubscriber($id, $data) {
        return $this->makeApiRequest('/subscribers/' . $id, 'PUT', $data);
    }

    public function deleteSubscriber($id) {
        return $this->makeApiRequest('/subscribers/' . $id, 'DELETE');
    }

    // Operations for Lists

    public function get_lists() {
        $response = $this->makeApiRequest('/lists', 'GET');
        if (!is_wp_error($response) && isset($response['lists'])) {
            return $response['lists'];
        }
        else {
            return [];
        }
    }

    public function createList($data) {
        return $this->makeApiRequest('/lists', 'POST', $data);
    }

    // Operations for Tags

    public function getTags() {
        return $this->makeApiRequest('/tags', 'GET');
    }

    public function getAllTags() {
        $response = $this->makeApiRequest('/tags?page=1&per_page=1000000000', 'GET');
        if (!is_wp_error($response) && isset($response['tags']) && isset($response['tags']['data'])) {
            return $response['tags']['data'];
        }
        else {
            return [];
        }
    }

    public function createTag($data) {
        return $this->makeApiRequest('/tags', 'POST', $data);
    }

    public function healthCheck() {
        $endpoint = '/lists';
        $response = $this->makeApiRequest($endpoint, 'GET');
        if (!is_wp_error($response) && isset($response['lists'])) {
            return true;
        } else {
            return false;
        }
    }

    public function createOrUpdateSubscriber($data) {
        $existingSubscriber = $this->getExistingSubscriberByEmail($data['email']);
        if ($existingSubscriber) {
            $id = $existingSubscriber['id'];
            $data['attach_tags'] = $data['tags'];
            $data['attach_lists'] = $data['lists'];
            return $this->updateSubscriber($id, $data);
        } else {
            return $this->createSubscriber($data);
        }
    }
    
    private function getExistingSubscriberByEmail($email) {
        $subscribers = $this->makeApiRequest('/subscribers/0?get_by_email='.$email, 'GET');
        if (!is_wp_error($subscribers) && isset($subscribers['subscriber'])) {
            return $subscribers['subscriber'];
        }
        return null;
    }
}
