<?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 FlowluOpportunityStageService
{
    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 createOpportunityStage()
    {
        $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_stage/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 stage: ' . $e->getMessage()
                ],
                'payload'     => $data,
                'status_code' => 500,
                'success'     => false
            ];
        }
    }

    public function updateOpportunityStage()
    {
        $stageId = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('stage-id.value'));
        $name = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('name.value'));

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

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

    public function getOpportunityStage()
    {
        $stageId = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('stage-id.value'));

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

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

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

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

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

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

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