<?php

namespace BitApps\PiPro\src\Integrations\GoogleMeet;

use BitApps\Pi\Deps\BitApps\WPKit\Helpers\DateTimeHelper;
use BitApps\Pi\Deps\BitApps\WPKit\Helpers\JSON;
use BitApps\Pi\Deps\BitApps\WPKit\Http\Client\HttpClient;
use DateTime;

if (!\defined('ABSPATH')) {
    exit;
}

class GoogleMeetService
{
    private HttpClient $http;

    private array $headers;

    private string $baseUrl;

    /**
     * GoogleMeetService constructor.
     *
     * @param array $headers
     */
    public function __construct($headers)
    {
        $this->http = new HttpClient();
        $this->headers = $headers;
        $this->baseUrl = 'https://www.googleapis.com/calendar/v3/calendars/';
    }

    public function createMeeting($fieldMapData, $calendarId)
    {
        $endPoint = $this->baseUrl . $calendarId . '/events?conferenceDataVersion=1';

        if (!empty($fieldMapData['attendees'])) {
            $fieldMapData['attendees'] = array_map(fn ($email) => ['email' => trim($email)], array_filter(explode(',', $fieldMapData['attendees'])));
        }

        $wpTimezone = DateTimeHelper::wp_timezone();
        $startDateTime = new DateTime($fieldMapData['start'], $wpTimezone);
        $endDateTime = new DateTime($fieldMapData['end'], $wpTimezone);

        $fieldMapData = array_merge(
            $fieldMapData,
            [
                'start' => [
                    'dateTime' => $startDateTime->format('c'),
                    'timeZone' => DateTimeHelper::wp_timezone_string(),
                ],
                'end' => [
                    'dateTime' => $endDateTime->format('c'),
                    'timeZone' => DateTimeHelper::wp_timezone_string(),
                ],
                'conferenceData' => [
                    'createRequest' => [
                        'conferenceSolutionKey' => ['type' => 'hangoutsMeet'],
                        'requestId'             => uniqid(),
                    ],
                ],
            ]
        );

        unset($fieldMapData['unique_id']);
        $meetingData = JSON::encode($fieldMapData);
        $response = $this->http->request($endPoint, 'POST', $meetingData, $this->headers);

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