<?php

namespace BitApps\PiPro\src\Integrations\Flowlu;

use BitApps\Pi\Deps\BitApps\WPKit\Helpers\JSON;
use BitApps\Pi\Helpers\MixInputHandler;
use BitApps\Pi\src\Flow\NodeInfoProvider;

if (!\defined('ABSPATH')) {
    exit;
}

final class FlowluAccountService
{
    private $http;

    private $baseUrl;

    private NodeInfoProvider $nodeInfoProvider;

    public function __construct($httpClient, $baseUrl, NodeInfoProvider $nodeInfoProvider)
    {
        $this->http = $httpClient;
        $this->baseUrl = $baseUrl;
        $this->nodeInfoProvider = $nodeInfoProvider;
    }

    public function createAccount()
    {
        $name = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('name.value'));
        $firstName = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('first-name.value'));
        $lastName = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('last-name.value'));
        $accountTypeId = $this->nodeInfoProvider->getFieldMapConfigs('account-type-id.value');
        $email = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('email.value'));
        $phone = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('phone.value'));
        $position = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('position.value'));

        $data = [];
        if (!empty($name)) {
            $data['name'] = $name;
        }
        if (!empty($firstName)) {
            $data['first_name'] = $firstName;
        }
        if (!empty($lastName)) {
            $data['last_name'] = $lastName;
        }
        if (!empty($accountTypeId)) {
            $data['type'] = $accountTypeId;
        }
        if (!empty($email)) {
            $data['email'] = $email;
        }
        if (!empty($phone)) {
            $data['phone'] = $phone;
        }
        if (!empty($position)) {
            $data['position'] = $position;
        }

        try {
            $response = $this->http->request(
                $this->baseUrl . '/module/crm/account/create',
                'POST',
                JSON::encode($data),
                []
            );

            $responseCode = $this->http->getResponseCode();
            $success = $responseCode >= 200 && $responseCode < 300;

            return [
                'response'    => $response,
                'payload'     => $data,
                'status_code' => $responseCode,
                'success'     => $success
            ];
        } catch (\Exception $e) {
            return [
                'response'    => [
                    'success' => false,
                    'message' => 'Failed to create account: ' . $e->getMessage()
                ],
                'payload'     => $data,
                'status_code' => 500,
                'success'     => false
            ];
        }
    }

    public function updateAccount()
    {
        $accountId = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('account-id.value'));
        if (empty($accountId)) {
            return [
                'response'    => ['success' => false, 'message' => 'Account ID is required'],
                'payload'     => [],
                'status_code' => 400,
                'success'     => false
            ];
        }
        $name = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('name.value'));
        $firstName = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('first-name.value'));
        $lastName = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('last-name.value'));
        $accountTypeId = $this->nodeInfoProvider->getFieldMapConfigs('account-type-id.value');
        $email = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('email.value'));
        $phone = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('phone.value'));
        $position = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('position.value'));

        $data = [];
        if (!empty($name)) {
            $data['name'] = $name;
        }
        if (!empty($firstName)) {
            $data['first_name'] = $firstName;
        }
        if (!empty($lastName)) {
            $data['last_name'] = $lastName;
        }
        if (!empty($accountTypeId)) {
            $data['type'] = $accountTypeId;
        }
        if (!empty($email)) {
            $data['email'] = $email;
        }
        if (!empty($phone)) {
            $data['phone'] = $phone;
        }
        if (!empty($position)) {
            $data['position'] = $position;
        }

        try {
            $response = $this->http->request(
                $this->baseUrl . "/module/crm/account/update/{$accountId}",
                'POST',
                JSON::encode($data),
                []
            );

            $responseCode = $this->http->getResponseCode();
            $success = $responseCode >= 200 && $responseCode < 300;

            return [
                'response'    => $response,
                'payload'     => $data,
                'status_code' => $responseCode,
                'success'     => $success
            ];
        } catch (\Exception $e) {
            return [
                'response'    => [
                    'success' => false,
                    'message' => 'Failed to update account: ' . $e->getMessage()
                ],
                'payload'     => $data,
                'status_code' => 500,
                'success'     => false
            ];
        }
    }

    public function getAccount()
    {
        $accountId = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('account-id.value'));
        if (empty($accountId)) {
            return [
                'response'    => ['success' => false, 'message' => 'Account ID is required'],
                'payload'     => [],
                'status_code' => 400,
                'success'     => false
            ];
        }
        try {
            $response = $this->http->request(
                $this->baseUrl . "/module/crm/account/get/{$accountId}",
                'GET',
                [],
                []
            );

            $responseCode = $this->http->getResponseCode();
            $success = $responseCode >= 200 && $responseCode < 300;

            return [
                'response'    => $response,
                'payload'     => ['account_id' => $accountId],
                'status_code' => $responseCode,
                'success'     => $success
            ];
        } catch (\Exception $e) {
            return [
                'response'    => [
                    'success' => false,
                    'message' => 'Failed to get account: ' . $e->getMessage()
                ],
                'payload'     => ['account_id' => $accountId],
                'status_code' => 500,
                'success'     => false
            ];
        }
    }

    public function listAccounts()
    {
        try {
            $response = $this->http->request(
                $this->baseUrl . '/module/crm/account/list',
                'GET',
                [],
                []
            );

            $responseCode = $this->http->getResponseCode();
            $success = $responseCode >= 200 && $responseCode < 300;

            return [
                'response'    => $response,
                'payload'     => [],
                'status_code' => $responseCode,
                'success'     => $success
            ];
        } catch (\Exception $e) {
            return [
                'response'    => [
                    'success' => false,
                    'message' => 'Failed to list accounts: ' . $e->getMessage()
                ],
                'payload'     => [],
                'status_code' => 500,
                'success'     => false
            ];
        }
    }

    public function deleteAccount()
    {
        $accountId = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('account-id.value'));
        if (empty($accountId)) {
            return [
                'response'    => ['success' => false, 'message' => 'Account ID is required'],
                'payload'     => [],
                'status_code' => 400,
                'success'     => false
            ];
        }

        try {
            $response = $this->http->request(
                $this->baseUrl . "/module/crm/account/delete/{$accountId}",
                'GET',
                [],
                []
            );

            $responseCode = $this->http->getResponseCode();
            $success = $responseCode >= 200 && $responseCode < 300;

            return [
                'response'    => $response,
                'payload'     => ['account_id' => $accountId],
                'status_code' => $responseCode,
                'success'     => $success
            ];
        } catch (\Exception $e) {
            return [
                'response'    => [
                    'success' => false,
                    'message' => 'Failed to delete account: ' . $e->getMessage()
                ],
                'payload'     => ['account_id' => $accountId],
                'status_code' => 500,
                'success'     => false
            ];
        }
    }
}
