<?php

namespace BitApps\PiPro\src\Integrations\Pabbly;

// Prevent direct script access
if (!\defined('ABSPATH')) {
    exit;
}

use BitApps\Pi\src\Authorization\AuthorizationFactory;
use BitApps\Pi\src\Authorization\AuthorizationType;
use BitApps\PiPro\Deps\BitApps\WPKit\Http\Client\HttpClient;

final class PabblyZohoProjectsService
{
    private $baseUrl;

    private $connectionId;

    private $http;

    /**
     * PabblyZohoProjectsService constructor.
     *
     * @param mixed $baseUrl
     * @param mixed $connectionId
     */
    public function __construct($baseUrl, $connectionId)
    {
        $this->baseUrl = $baseUrl;
        $this->connectionId = $connectionId;
        $this->http = new HttpClient();
    }

    /**
     * Create a new project in Zoho Projects.
     *
     * @param array $projectData Project data from field mapping
     * @param mixed $portalId    Zoho Projects portal ID
     *
     * @return array
     */
    public function createProject($projectData, $portalId)
    {
        $tokenAuthorization = AuthorizationFactory::getAuthorizationHandler(
            AuthorizationType::BEARER_TOKEN,
            $this->connectionId
        );

        // Build request parameters from field mapping
        $requestParams = [];
        foreach ($projectData as $data) {
            $key = $data['column'] ?? '';
            $value = $data['value'] ?? '';

            if (!empty($key) && !empty($value)) {
                $requestParams[$key] = $value;
            }
        }

        // Construct the API endpoint
        // Format: /restapi/portal/{PORTALID}/projects/
        $endpoint = $this->baseUrl . '/restapi/portal/' . $portalId . '/projects/';

        $headers = [
            'Authorization' => 'Zoho-oauthtoken ' . $tokenAuthorization->getAccessToken(),
            'Content-Type'  => 'application/x-www-form-urlencoded'
        ];

        // Zoho Projects API expects form-encoded data
        $bodyParams = http_build_query($requestParams);

        $response = $this->http->request(
            $endpoint,
            'POST',
            $bodyParams,
            $headers
        );

        return [
            'response'    => $response,
            'payload'     => $requestParams,
            'status_code' => $this->http->getResponseCode()
        ];
    }
}
