<?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 FlowluOpportunityService
{
    private $http;

    private $baseUrl;

    private NodeInfoProvider $nodeInfoProvider;

    /**
     * OpportunityService constructor.
     */
    public function __construct($httpClient, $baseUrl, NodeInfoProvider $nodeInfoProvider)
    {
        $this->http = $httpClient;
        $this->baseUrl = $baseUrl;
        $this->nodeInfoProvider = $nodeInfoProvider;
    }

    /**
     * Create Flowlu opportunity.
     *
     * @return array
     */
    public function createOpportunity()
    {
        $opportunityName = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('opportunity-name.value'));
        $accountId = $this->nodeInfoProvider->getFieldMapConfigs('account-id.value');
        $contactId = $this->nodeInfoProvider->getFieldMapConfigs('contact-id.value');
        $stageId = $this->nodeInfoProvider->getFieldMapConfigs('stage-id.value');
        $amount = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('amount.value'));
        $description = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('description.value'));

        $opportunityData = [];
        if (!empty($opportunityName)) {
            $opportunityData['name'] = $opportunityName;
        }
        if (!empty($accountId)) {
            $opportunityData['customer_id'] = $accountId;
        }
        if (!empty($contactId)) {
            $opportunityData['contact_id'] = $contactId;
        }
        if (!empty($stageId)) {
            $opportunityData['pipeline_stage_id'] = $stageId;
        }
        if (!empty($amount)) {
            $opportunityData['amount'] = $amount;
        }
        if (!empty($description)) {
            $opportunityData['description'] = $description;
        }

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


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

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

    public function updateOpportunity()
    {
        $opportunityId = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('opportunity-id.value'));
        $opportunityName = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('opportunity-name.value'));
        $accountId = $this->nodeInfoProvider->getFieldMapConfigs('account-id.value');
        $contactId = $this->nodeInfoProvider->getFieldMapConfigs('contact-id.value');
        $stageId = $this->nodeInfoProvider->getFieldMapConfigs('stage-id.value');
        $amount = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('amount.value'));
        $description = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('description.value'));


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

        $opportunityData = [];
        if (!empty($opportunityName)) {
            $opportunityData['name'] = $opportunityName;
        }
        if (!empty($accountId)) {
            $opportunityData['customer_id'] = $accountId;
        }
        if (!empty($contactId)) {
            $opportunityData['contact_id'] = $contactId;
        }
        if (!empty($stageId)) {
            $opportunityData['pipeline_stage_id'] = $stageId;
        }
        if (!empty($amount)) {
            $opportunityData['amount'] = $amount;
        }
        if (!empty($description)) {
            $opportunityData['description'] = $description;
        }

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

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

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

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

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

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

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

    public function deleteOpportunity()
    {
        $opportunityId = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('opportunity-id.value'));

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

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

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