<?php

namespace BitApps\PiPro\src\Integrations\ActiveCampaign;

// Prevent direct script access
if (!\defined('ABSPATH')) {
    exit;
}

use BitApps\PiPro\Deps\BitApps\WPKit\Helpers\JSON;
use BitApps\PiPro\Deps\BitApps\WPKit\Http\Client\HttpClient;

class ActiveCampaignHelper
{
    private $BASE_URL;

    private $http;

    private $headers;

    public function __construct($headers, $baseUrl)
    {
        $this->BASE_URL = $baseUrl;
        $this->http = new HttpClient();
        $this->headers = $headers;
    }

    public function createContact($data)
    {
        $url = $this->BASE_URL . '/api/3/contacts';
        $contactPayload = [
            'contact' => [
                'email'     => $data['email'],
                'firstName' => $data['firstName'] ?? '',
                'lastName'  => $data['lastName'] ?? '',
                'phone'     => $data['phone'] ?? ''
            ]
        ];
        $response = $this->http->request($url, 'POST', JSON::encode($contactPayload), $this->headers);

        return [
            'response'    => $response,
            'payload'     => $contactPayload,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function updateContact($data)
    {
        $url = $this->BASE_URL . '/api/3/contacts/' . $data['contactId'];
        $contactPayload = [
            'contact' => [
                'email'     => $data['email'],
                'firstName' => $data['firstName'] ?? '',
                'lastName'  => $data['lastName'] ?? '',
                'phone'     => $data['phone'] ?? ''
            ]
        ];
        $response = $this->http->request($url, 'PUT', JSON::encode($contactPayload), $this->headers);

        return [
            'response'    => $response,
            'payload'     => $contactPayload,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function updateContactByEmail($data)
    {
        $url = $this->BASE_URL . '/api/3/contact/sync';
        $response = $this->http->request($url, 'POST', JSON::encode($data), $this->headers);

        return [
            'response'    => $response,
            'payload'     => $data,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function addOrRemoveTagContact($data)
    {
        $type = 'POST';
        $tagId = '';
        $payload = [];

        switch ($data['action-type']) {
            case 'remove':
                $type = 'DELETE';
                $tagId = $data['tag'];

                break;

            default:
                $payload = [
                    'contactTag' => [
                        'contact' => $data['contact'],
                        'tag'     => $data['tag']
                    ]
                ];

                break;
        }
        $url = $this->BASE_URL . '/api/3/contactTags/' . $tagId;

        $response = $this->http->request($url, $type, JSON::encode($payload), $this->headers);

        return [
            'response'    => $response,
            'payload'     => $payload,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function addOrRemoveContactAutomation($data)
    {
        switch ($data['action-type']) {
            case 'add':
                $url = "{$this->BASE_URL}/api/3/contactAutomations";
                $method = 'POST';
                $payload = [
                    'automation' => $data['automation'],
                    'contact'    => $data['contact']
                ];

                break;

            case 'remove':
                $url = "{$this->BASE_URL}/api/3/contactAutomations/{$data['contact']}";
                $method = 'DELETE';
                $payload = $data;

                break;
        }
        $response = $this->http->request($url, $method, JSON::encode($payload), $this->headers);

        return [
            'response'    => $response,
            'payload'     => $payload,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function subscribeOrUnsubscribeContactList($data)
    {
        switch ($data['action-type']) {
            case 'subscribe':
                $url = "{$this->BASE_URL}/api/3/contactLists";
                $method = 'POST';
                $payload = [
                    'contactList' => [
                        'contact' => $data['contact'],
                        'list'    => $data['list'],
                        'status'  => 1
                    ]
                ];

                break;

            case 'unsubscribe':
                $url = "{$this->BASE_URL}/api/3/contactLists";
                $method = 'POST';
                $payload = [
                    'contactList' => [
                        'contact' => $data['contact'],
                        'list'    => $data['list'],
                        'status'  => 2
                    ]
                ];

                break;
        }
        $response = $this->http->request($url, $method, JSON::encode($payload), $this->headers);

        return [
            'response'    => $response,
            'payload'     => $payload,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function createDeal($data, $fields)
    {
        $payload = [
            'deal' => [
                'title'       => $data['title'],
                'contact'     => $data['contact'],
                'account'     => $data['account'],
                'currency'    => $data['currency'],
                'description' => $data['description'],
                'value'       => $data['value'],
                'stage'       => $data['stage'],
                'owner'       => $data['owner'],
                'fields'      => $fields
            ]
        ];

        $url = $this->BASE_URL . '/api/3/deals';

        $response = $this->http->request($url, 'POST', JSON::encode($payload), $this->headers);

        return [
            'response'    => $response,
            'payload'     => $payload,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function getAllUser()
    {
        $url = $this->BASE_URL . '/api/3/users';

        $response = $this->http->request($url, 'GET', null, $this->headers);

        return [
            'response'    => $response,
            'payload'     => [],
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function findUser($data)
    {
        $url = $this->BASE_URL . '/api/3/users/email/' . $data['email'];

        $response = $this->http->request($url, 'GET', null, $this->headers);

        return [
            'response'    => $response,
            'payload'     => [],
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function findAccount($data)
    {
        $url = $this->BASE_URL . '/api/3/accounts/' . $data['accountId'];

        $response = $this->http->request($url, 'GET', null, $this->headers);

        return [
            'response'    => $response,
            'payload'     => [],
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function findAccountByName($data)
    {
        $url = $this->BASE_URL . '/api/3/accounts?filters[name]=' . rawurlencode($data['name']);
        $response = $this->http->request($url, 'GET', [], $this->headers);

        return [
            'response'    => $response,
            'payload'     => ['Account Name' => $data['name']],
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function findContact($data)
    {
        $url = $this->BASE_URL . '/api/3/contacts/' . $data['contactId'];

        $response = $this->http->request($url, 'GET', null, $this->headers);

        return [
            'response'    => $response,
            'payload'     => [],
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function findContactByEmail($data)
    {
        $url = $this->BASE_URL . '/api/3/contacts?email=' . rawurlencode($data['email']);
        $response = $this->http->request($url, 'GET', [], $this->headers);

        return [
            'response'    => $response,
            'payload'     => ['Email' => $data['email']],
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function getAllContact()
    {
        $url = $this->BASE_URL . '/api/3/contacts';

        $response = $this->http->request($url, 'GET', null, $this->headers);

        return [
            'response'    => $response,
            'payload'     => [],
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function getAllAccount()
    {
        $url = $this->BASE_URL . '/api/3/accounts';

        $response = $this->http->request($url, 'GET', null, $this->headers);

        return [
            'response'    => $response,
            'payload'     => [],
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function createAccount($data, $fields)
    {
        $url = $this->BASE_URL . '/api/3/accounts';
        $payload = [
            'account' => [
                'name'       => $data['name'],
                'accountUrl' => $data['accountUrl'] ?? '',
                'owner'      => $data['owner'] ?? null,
                'fields'     => $fields ?? []
            ]
        ];

        $response = $this->http->request($url, 'POST', JSON::encode($payload), $this->headers);

        return [
            'response'    => $response,
            'payload'     => $payload,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function updateAccount($data, $fields)
    {
        $url = $this->BASE_URL . '/api/3/accounts/' . $data['accountId'];
        $payload = [
            'account' => [
                'name'       => $data['name'],
                'accountUrl' => $data['accountUrl'] ?? '',
                'owner'      => $data['owner'] ?? null,
                'fields'     => $fields ?? []
            ]
        ];

        $response = $this->http->request($url, 'PUT', JSON::encode($payload), $this->headers);

        return [
            'response'    => $response,
            'payload'     => $payload,
            'status_code' => $this->http->getResponseCode()
        ];
    }
}
