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

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

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

    public function updatePipeline()
    {
        $pipelineId = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('pipeline-id.value'));
        $name = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('name.value'));

        if (empty($pipelineId)) {
            return [
                'response'    => [
                    'success' => false,
                    'message' => 'Pipeline ID is required to update pipeline'
                ],
                'payload'     => [],
                'status_code' => 400,
                'success'     => false
            ];
        }
        $data = [];
        if (!empty($name)) {
            $data['name'] = $name;
        }

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

    public function getPipeline()
    {
        $pipelineId = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('pipeline-id.value'));

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

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

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

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

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

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

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