<?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 FlowluOpportunitySourceService
{
    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 createOpportunitySource()
    {
        $name = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('name.value'));

        $data = [];
        if (!empty($name)) {
            $data['name'] = $name;
        }

        try {
            $response = $this->http->request(
                $this->baseUrl . '/module/crm/source/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 opportunity source: ' . $e->getMessage()
                ],
                'payload'     => $data,
                'status_code' => 500,
                'success'     => false
            ];
        }
    }

    public function updateOpportunitySource()
    {
        $sourceId = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('source-id.value'));
        $name = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('name.value'));

        if (empty($sourceId)) {
            return [
                'response'    => [
                    'success' => false,
                    'message' => 'Source ID is required to update opportunity source'
                ],
                'payload'     => [],
                'status_code' => 400,
                'success'     => false
            ];
        }

        $data = [];
        if (!empty($name)) {
            $data['name'] = $name;
        }

        try {
            $response = $this->http->request(
                $this->baseUrl . "/module/crm/source/update/{$sourceId}",
                '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 opportunity source: ' . $e->getMessage()
                ],
                'payload'     => $data,
                'status_code' => 500,
                'success'     => false
            ];
        }
    }

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

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

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

    public function listOpportunitySources()
    {
        try {
            $response = $this->http->request(
                $this->baseUrl . '/module/crm/source/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 opportunity sources: ' . $e->getMessage()
                ],
                'payload'     => [],
                'status_code' => 500,
                'success'     => false
            ];
        }
    }

    public function deleteOpportunitySource()
    {
        $sourceId = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('source-id.value'));

        if (empty($sourceId)) {
            return [
                'response'    => [
                    'success' => false,
                    'message' => 'Source ID is required to delete opportunity source'
                ],
                'payload'     => [],
                'status_code' => 400,
                'success'     => false
            ];
        }
        try {
            $response = $this->http->request(
                $this->baseUrl . "/module/crm/source/delete/{$sourceId}",
                'GET',
                [],
                []
            );

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

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