<?php

namespace App\Services;

use Google_Client;
use Google_Service_Calendar;
use Google_Service_Calendar_Event;
use Illuminate\Support\Facades\Log;

class GoogleMeetService
{
    public function createGoogleMeetEvent($title, $description, $startTime, $endTime, $attendees = [])
    {
        try {
            if (empty(settings('google_admin_email'))){
               throw new \Exception('Google admin email not set in settings.');
            }

            $serviceAccountPath = base_path('google-service-account.json');

            $client = new Google_Client();
            $client->setApplicationName('Laravel Google Meet Integration');
            $client->setAuthConfig($serviceAccountPath);
            $client->setScopes(Google_Service_Calendar::CALENDAR);
            $client->setSubject(settings('google_admin_email'));

            $service = new Google_Service_Calendar($client);

            $timezone = config('app.timezone');
            $event = new Google_Service_Calendar_Event([
                'summary' => $title,
                'description' => $description,
                'start' => [
                    'dateTime' => $startTime,
                    'timeZone' => $timezone,
                ],
                'end' => [
                    'dateTime' => $endTime,
                    'timeZone' => $timezone,
                ],
                'attendees' => $attendees,
                'conferenceData' => [
                    'createRequest' => [
                        'requestId' => 'random-string-id'
                    ]
                ],
            ]);

            $createdEvent = $service->events->insert('primary', $event, ['conferenceDataVersion' => 1]);

            $meetLink = $createdEvent->getHangoutLink();

            Log::info('Google Meet event created successfully Link='.$meetLink);
            return $meetLink;

        }catch (\Exception $e) {
            Log::error('Error creating Google Meet event: '.$e->getMessage());
            return false;
        }
    }
}
